diff --git a/.asciidoctorconfig.adoc b/.asciidoctorconfig.adoc new file mode 100644 index 000000000..53b403dbc --- /dev/null +++ b/.asciidoctorconfig.adoc @@ -0,0 +1,12 @@ +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// + Initial AsciiDoc editor configuration file - V1.0 + +// ++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// +// Did not found any configuration files, so create this at project root level. +// If you do not like those files to be generated - you can turn it off inside Asciidoctor Editor preferences. +// +// You can define editor specific parts here. +// For example: with next line you could set imagesdir attribute to subfolder "images" relative to the folder where this config file is located. +// :imagesdir: {asciidoctorconfigdir}/images +// +// For more information please take a look at https://github.com/de-jcup/eclipse-asciidoctor-editor/wiki/Asciidoctor-configfiles diff --git a/.gitignore b/.gitignore index cddb24767..b187e48d1 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* +node_modules bin target build.acceleo diff --git a/.mvn/extensions.xml b/.mvn/extensions.xml index f99881037..320ec9943 100644 --- a/.mvn/extensions.xml +++ b/.mvn/extensions.xml @@ -1,8 +1,8 @@ - - org.eclipse.tycho.extras - tycho-pomless - 2.5.0 - + + org.eclipse.tycho + tycho-build + 2.7.0 + \ No newline at end of file diff --git a/commons/plugins/org.eclipse.gemoc.commons.utils/.classpath b/commons/plugins/org.eclipse.gemoc.commons.utils/.classpath new file mode 100644 index 000000000..eca7bdba8 --- /dev/null +++ b/commons/plugins/org.eclipse.gemoc.commons.utils/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/commons/plugins/org.eclipse.gemoc.commons.utils/.project b/commons/plugins/org.eclipse.gemoc.commons.utils/.project new file mode 100644 index 000000000..646222aaa --- /dev/null +++ b/commons/plugins/org.eclipse.gemoc.commons.utils/.project @@ -0,0 +1,28 @@ + + + org.eclipse.gemoc.commons.utils + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/commons/plugins/org.eclipse.gemoc.commons.utils/.settings/org.eclipse.jdt.core.prefs b/commons/plugins/org.eclipse.gemoc.commons.utils/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..0c68a61dc --- /dev/null +++ b/commons/plugins/org.eclipse.gemoc.commons.utils/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,7 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/commons/plugins/org.eclipse.gemoc.commons.utils/META-INF/MANIFEST.MF b/commons/plugins/org.eclipse.gemoc.commons.utils/META-INF/MANIFEST.MF new file mode 100644 index 000000000..c8c119e2d --- /dev/null +++ b/commons/plugins/org.eclipse.gemoc.commons.utils/META-INF/MANIFEST.MF @@ -0,0 +1,9 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: GEMOC Commons Utils +Bundle-SymbolicName: org.eclipse.gemoc.commons.utils +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: Inria +Automatic-Module-Name: org.eclipse.gemoc.commons.utils +Bundle-RequiredExecutionEnvironment: JavaSE-1.8 +Export-Package: org.eclipse.gemoc.commons.utils diff --git a/commons/plugins/org.eclipse.gemoc.commons.utils/build.properties b/commons/plugins/org.eclipse.gemoc.commons.utils/build.properties new file mode 100644 index 000000000..34d2e4d2d --- /dev/null +++ b/commons/plugins/org.eclipse.gemoc.commons.utils/build.properties @@ -0,0 +1,4 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + . diff --git a/commons/plugins/org.eclipse.gemoc.commons.utils/pomfirst/pom.xml b/commons/plugins/org.eclipse.gemoc.commons.utils/pomfirst/pom.xml new file mode 100644 index 000000000..0013552f8 --- /dev/null +++ b/commons/plugins/org.eclipse.gemoc.commons.utils/pomfirst/pom.xml @@ -0,0 +1,66 @@ + + + 4.0.0 + + org.eclipse.gemoc.pomfirst + org.eclipse.gemoc.commons.utils + 1.0.0-SNAPSHOT + + jar + + + scm:git:https://github.com/eclipse/gemoc-studio-modeldebugging.git + UTF-8 + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + unpack + prepare-package + + unpack + + + + + org.eclipse.gemoc.commons + ${project.artifactId} + ${project.version} + jar + true + ${project.build.directory}/classes + ** + + + + + + + + + + + + + + nexus-eclipse-gemoc + Nexus Eclipse GEMOC + + true + + + true + + https://repo.eclipse.org/content/groups/gemoc/ + + + \ No newline at end of file diff --git a/commons/plugins/org.eclipse.gemoc.commons.utils/src/org/eclipse/gemoc/commons/utils/ExtensibleInputStream.java b/commons/plugins/org.eclipse.gemoc.commons.utils/src/org/eclipse/gemoc/commons/utils/ExtensibleInputStream.java new file mode 100644 index 000000000..d32daf69f --- /dev/null +++ b/commons/plugins/org.eclipse.gemoc.commons.utils/src/org/eclipse/gemoc/commons/utils/ExtensibleInputStream.java @@ -0,0 +1,65 @@ +/******************************************************************************* + * Copyright (c) 2020 Inria and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Inria - initial API and implementation + *******************************************************************************/ +package org.eclipse.gemoc.commons.utils; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.concurrent.LinkedBlockingQueue; + +public class ExtensibleInputStream extends InputStream { + + LinkedBlockingQueue messages = new LinkedBlockingQueue<>(); + + @Override + public int read() throws IOException { + +// System.out.println("[DEBUG] Read InputStream"); + + waitForMessage(); + + InputStream current = messages.peek(); + int c = current.read(); + if(c != -1) { + return c; + } + else { +// System.out.println("[DEBUG] End InputStream 2"); + messages.poll(); + + waitForMessage(); + + current = messages.peek(); + return current.read(); + } + } + + public void addMessage(String message) { +// System.out.println("[DEBUG] Fill InputStream"); + messages.add(new ByteArrayInputStream(message.getBytes())); + synchronized (this) { + this.notify(); + } + } + + public void waitForMessage() { + if(messages.isEmpty()) { + try { + synchronized (this) { + this.wait(); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } +// System.out.println("[DEBUG] Wait"); + } + } +} diff --git a/commons/plugins/org.eclipse.gemoc.commons.utils/src/org/eclipse/gemoc/commons/utils/ModelAwarePrintStream.java b/commons/plugins/org.eclipse.gemoc.commons.utils/src/org/eclipse/gemoc/commons/utils/ModelAwarePrintStream.java new file mode 100644 index 000000000..f7b7bc033 --- /dev/null +++ b/commons/plugins/org.eclipse.gemoc.commons.utils/src/org/eclipse/gemoc/commons/utils/ModelAwarePrintStream.java @@ -0,0 +1,222 @@ +/******************************************************************************* + * Copyright (c) 2020 Inria and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Inria - initial API and implementation + *******************************************************************************/ +package org.eclipse.gemoc.commons.utils; + +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.Locale; + +public class ModelAwarePrintStream extends PrintStream { + + private PrintStream baseStream; + private Thread modelExecutionThread; + + public ModelAwarePrintStream(OutputStream out, PrintStream baseStream) { + super(out); + this.baseStream = baseStream; + } + + public void registerModelExecutionThread(Thread modelExecutionThread) { + this.modelExecutionThread = modelExecutionThread; + } + + @Override + public void print(boolean b) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.print(b); + } else { + this.baseStream.print(b); + } + } + + @Override + public void print(char c) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.print(c); + } else { + this.baseStream.print(c); + } + } + + @Override + public void print(int i) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.print(i); + } else { + this.baseStream.print(i); + } + } + + @Override + public void print(long l) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.print(l); + } else { + this.baseStream.print(l); + } + } + + @Override + public void print(float f) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.print(f); + } else { + this.baseStream.print(f); + } + } + + @Override + public void print(double d) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.print(d); + } else { + this.baseStream.print(d); + } + } + + @Override + public void print(char[] s) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.print(s); + } else { + this.baseStream.print(s); + } + } + + @Override + public void print(String s) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.print(s); + } else { + this.baseStream.print(s); + } + } + + @Override + public void print(Object obj) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.print(obj); + } else { + this.baseStream.print(obj); + } + } + + @Override + public void println() { + if (Thread.currentThread() == this.modelExecutionThread) { + super.println(); + } else { + this.baseStream.println(); + } + } + + @Override + public void println(boolean x) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.println(x); + } else { + this.baseStream.println(x); + } + } + + @Override + public void println(char x) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.println(x); + } else { + this.baseStream.println(x); + } + } + + @Override + public void println(int x) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.println(x); + } else { + this.baseStream.println(x); + } + } + + @Override + public void println(long x) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.println(x); + } else { + this.baseStream.println(x); + } + } + + @Override + public void println(float x) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.println(x); + } else { + this.baseStream.println(x); + } + } + + @Override + public void println(double x) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.println(x); + } else { + this.baseStream.println(x); + } + } + + @Override + public void println(char[] x) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.println(x); + } else { + this.baseStream.println(x); + } + } + + @Override + public void println(String x) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.println(x); + } else { + this.baseStream.println(x); + } + } + + @Override + public void println(Object x) { + if (Thread.currentThread() == this.modelExecutionThread) { + super.println(x); + } else { + this.baseStream.println(x); + } + } + + @Override + public PrintStream printf(String format, Object... args) { + if (Thread.currentThread() == this.modelExecutionThread) { + return super.printf(format, args); + } else { + return this.baseStream.printf(format, args); + } + } + + @Override + public PrintStream printf(Locale l, String format, Object... args) { + if (Thread.currentThread() == this.modelExecutionThread) { + return super.printf(l, format, args); + } else { + return this.baseStream.printf(l, format, args); + } + } + + + +} diff --git a/commons/plugins/pom.xml b/commons/plugins/pom.xml index d05824d4e..a906d4608 100644 --- a/commons/plugins/pom.xml +++ b/commons/plugins/pom.xml @@ -34,6 +34,7 @@ org.eclipse.gemoc.commons.eclipse.jdt.autosrcfolder org.eclipse.gemoc.commons.eclipse.ui org.eclipse.gemoc.commons.eclipse.xtext + org.eclipse.gemoc.commons.utils org.eclipse.gemoc.groovy org.eclipse.gemoc.timeline org.eclipse.gemoc.dsl.model diff --git a/commons/pomfirst/org.eclipse.gemoc.commons.eclipse.messagingsystem.api/pom.xml b/commons/pomfirst/org.eclipse.gemoc.commons.eclipse.messagingsystem.api/pom.xml index 51264f961..4962e08cc 100644 --- a/commons/pomfirst/org.eclipse.gemoc.commons.eclipse.messagingsystem.api/pom.xml +++ b/commons/pomfirst/org.eclipse.gemoc.commons.eclipse.messagingsystem.api/pom.xml @@ -46,7 +46,7 @@ 3.0.2 - copy-resource-one + copy-resource-src generate-sources copy-resources diff --git a/commons/pomfirst/org.eclipse.gemoc.dsl.model/pom.xml b/commons/pomfirst/org.eclipse.gemoc.dsl.model/pom.xml index de9617dde..e6bc5de6e 100644 --- a/commons/pomfirst/org.eclipse.gemoc.dsl.model/pom.xml +++ b/commons/pomfirst/org.eclipse.gemoc.dsl.model/pom.xml @@ -22,6 +22,11 @@ + + + target/src/main/resources + + org.codehaus.mojo @@ -46,7 +51,7 @@ 3.0.2 - copy-resource-one + copy-resource-src generate-sources copy-resources @@ -57,6 +62,10 @@ ../../plugins/org.eclipse.gemoc.dsl.model/src + + ${basedir}/target/src/main/resources/model + ../../plugins/org.eclipse.gemoc.dsl.model/model + diff --git a/commons/releng/org.eclipse.gemoc.commons.feature/feature.xml b/commons/releng/org.eclipse.gemoc.commons.feature/feature.xml index 047824fba..0c8b2e208 100644 --- a/commons/releng/org.eclipse.gemoc.commons.feature/feature.xml +++ b/commons/releng/org.eclipse.gemoc.commons.feature/feature.xml @@ -60,4 +60,11 @@ http://www.eclipse.org/legal/epl-v10.html version="0.0.0" unpack="false"/> + + diff --git a/commons/thirdparties_pom_to_p2/.project b/commons/thirdparties_pom_to_p2/.project new file mode 100644 index 000000000..aa03aff79 --- /dev/null +++ b/commons/thirdparties_pom_to_p2/.project @@ -0,0 +1,17 @@ + + + thirdparties_pom_to_p2 + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/commons/thirdparties_pom_to_p2/.settings/org.eclipse.m2e.core.prefs b/commons/thirdparties_pom_to_p2/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 000000000..f897a7f1c --- /dev/null +++ b/commons/thirdparties_pom_to_p2/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/commons/thirdparties_pom_to_p2/README.md b/commons/thirdparties_pom_to_p2/README.md new file mode 100644 index 000000000..26af06cef --- /dev/null +++ b/commons/thirdparties_pom_to_p2/README.md @@ -0,0 +1 @@ +use https://github.com/reficio/p2-maven-plugin diff --git a/commons/thirdparties_pom_to_p2/pom.xml b/commons/thirdparties_pom_to_p2/pom.xml new file mode 100644 index 000000000..77dfc1576 --- /dev/null +++ b/commons/thirdparties_pom_to_p2/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + org.eclipse.gemoc.gemoc-studio-modeldebugging.bundle + thirdparty-p2-site + pom + 1.5.1-SNAPSHOT + + + + + org.reficio + p2-maven-plugin + 1.3.0 + + + generate-p2-site + compile + + site + + + + + + + + org.eclipse.jetty.toolchain:jetty-javax-websocket-api:1.1.2 + true + + org.eclipse.jetty.websocket + + org.eclipse.jetty.websocket:websocket-javax-server:10.0.6 + true + + + + + org.apache.aries.spifly:org.apache.aries.spifly.dynamic.bundle:1.3.4 + false + + + + + + + + org.apache.felix + maven-bundle-plugin + 3.5.0 + + + + + \ No newline at end of file diff --git a/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.classpath b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.classpath new file mode 100644 index 000000000..1ee2ea308 --- /dev/null +++ b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.classpath @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.project b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.project new file mode 100644 index 000000000..fe4b7c1b9 --- /dev/null +++ b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.project @@ -0,0 +1,40 @@ + + + org.eclipse.gemoc.executionframework.addon.eaop.server + + + + + + org.eclipse.xtext.ui.shared.xtextBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.xtext.ui.shared.xtextNature + org.eclipse.m2e.core.maven2Nature + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.settings/org.eclipse.core.resources.prefs b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..99f26c020 --- /dev/null +++ b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/=UTF-8 diff --git a/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.settings/org.eclipse.jdt.core.prefs b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..a58ebdcad --- /dev/null +++ b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,15 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=11 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=11 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning +org.eclipse.jdt.core.compiler.release=enabled +org.eclipse.jdt.core.compiler.source=11 diff --git a/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.settings/org.eclipse.m2e.core.prefs b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 000000000..f897a7f1c --- /dev/null +++ b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.settings/org.eclipse.xtend.core.Xtend.prefs b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.settings/org.eclipse.xtend.core.Xtend.prefs new file mode 100644 index 000000000..9682a4c0a --- /dev/null +++ b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/.settings/org.eclipse.xtend.core.Xtend.prefs @@ -0,0 +1,7 @@ +//outlet.DEFAULT_OUTPUT.sourceFolder.src/main/java.directory=xtend-gen +//outlet.DEFAULT_OUTPUT.sourceFolder.src/test/java.directory=src/test/generated-sources/xtend +BuilderConfiguration.is_project_specific=true +eclipse.preferences.version=1 +outlet.DEFAULT_OUTPUT.hideLocalSyntheticVariables=true +outlet.DEFAULT_OUTPUT.installDslAsPrimarySource=false +outlet.DEFAULT_OUTPUT.userOutputPerSourceFolder=true diff --git a/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/META-INF/MANIFEST.MF b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/META-INF/MANIFEST.MF new file mode 100644 index 000000000..5faf7995b --- /dev/null +++ b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/META-INF/MANIFEST.MF @@ -0,0 +1,30 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: GEMOC Addon-based EAOP Server +Bundle-SymbolicName: org.eclipse.gemoc.executionframework.addon.eaop.server;singleton:=true +Bundle-Version: 1.0.0.qualifier +Bundle-Activator: org.eclipse.gemoc.executionframework.addon.eaop.server.Activator +Require-Bundle: org.eclipse.core.runtime, + org.eclipse.gemoc.protocols.eaop.api;bundle-version="2.3.0", + org.eclipse.gemoc.xdsmlframework.api;bundle-version="4.0.0", + org.eclipse.gemoc.ws.server;bundle-version="1.0.0", + org.eclipse.gemoc.commons.utils;bundle-version="1.0.0", + org.mapstruct;bundle-version="1.4.2", + org.eclipse.gemoc.trace.commons.model, + org.eclipse.gemoc.executionframework.engine;bundle-version="4.0.0", + org.eclipse.gemoc.commons.eclipse.messagingsystem.api +Bundle-RequiredExecutionEnvironment: JavaSE-11 +Automatic-Module-Name: org.eclipse.gemoc.executionframework.addon.eaop.server +Bundle-ActivationPolicy: lazy +Bundle-Vendor: Eclipse GEMOC Project +Import-Package: com.google.gson;version="2.8.8", + javax.websocket;version="1.1.0", + javax.websocket.server;version="1.1.0", + org.eclipse.lsp4j.generator;version="0.12.0.v20210402-1305", + org.eclipse.lsp4j.jsonrpc;version="0.12.0.v20210402-1305", + org.eclipse.lsp4j.jsonrpc.json;version="0.12.0.v20210402-1305", + org.eclipse.lsp4j.jsonrpc.messages;version="0.12.0.v20210402-1305", + org.eclipse.lsp4j.jsonrpc.services;version="0.12.0.v20210402-1305", + org.slf4j +Export-Package: org.eclipse.gemoc.executionframework.addon.eaop.server, + org.eclipse.gemoc.executionframework.addon.eaop.server.rpclaunch diff --git a/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/build.properties b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/build.properties new file mode 100644 index 000000000..e9863e281 --- /dev/null +++ b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/build.properties @@ -0,0 +1,5 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + plugin.xml diff --git a/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/plugin.xml b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/plugin.xml new file mode 100644 index 000000000..4c2faf3b0 --- /dev/null +++ b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/plugin.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + diff --git a/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/Activator.java b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/Activator.java new file mode 100644 index 000000000..08acc6623 --- /dev/null +++ b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/Activator.java @@ -0,0 +1,84 @@ +package org.eclipse.gemoc.executionframework.addon.eaop.server; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.eclipse.gemoc.commons.eclipse.messagingsystem.api.MessagingSystem; +import org.eclipse.gemoc.commons.eclipse.messagingsystem.api.MessagingSystemManager; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + +public class Activator implements BundleActivator { + // The plug-in ID + public static final String PLUGIN_ID = "org.eclipse.gemoc.executionframework.addon.eaop.server"; //$NON-NLS-1$ + public static final String CONSOLE_NAME = "Modeling Workbench Console"; //$NON-NLS-1$ + + // The shared instance + private static Activator plugin; + private static BundleContext context; + + static BundleContext getContext() { + return context; + } + + public static Activator getDefault() { + return plugin; + } + + public void start(BundleContext bundleContext) throws Exception { + plugin = this; + Activator.context = bundleContext; + + // activate ws server + org.eclipse.gemoc.ws.server.Activator.getDefault(); + + } + + public void stop(BundleContext bundleContext) throws Exception { + Activator.context = null; + } + + /** + * set of EaopServers that are connected + */ + Set startedEaopServers = new HashSet(); + + public synchronized Set getStartedEaopServer() { + return startedEaopServers; + } + + + + + protected MessagingSystem messaggingSystem = null; + + public MessagingSystem getMessaggingSystem() { + if (messaggingSystem == null) { + MessagingSystemManager msm = new MessagingSystemManager(); + messaggingSystem = msm.createBestPlatformMessagingSystem("org.eclipse.gemoc.executionframework.engine", CONSOLE_NAME); + } + return messaggingSystem; + } + public static void debug(String msg) { + Activator.getDefault().getMessaggingSystem().debug(msg, PLUGIN_ID); + } + public static void info(String msg) { + Activator.getDefault().getMessaggingSystem().info(msg, PLUGIN_ID); + } + + public static void warn(String msg, Throwable e) { + // Activator.getDefault().getLog().log(new Status(Status.WARNING, PLUGIN_ID, + // Status.OK, msg, e)); + Activator.getDefault().getMessaggingSystem().warn(msg, PLUGIN_ID, e); + } + + public static void error(String msg, Throwable e) { + // Activator.getDefault().getLog().log(new Status(Status.ERROR, PLUGIN_ID, + // Status.OK, msg, e)); + Activator.getDefault().getMessaggingSystem().error(msg, PLUGIN_ID, e); + } + +} diff --git a/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/EaopEngineAddon.java b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/EaopEngineAddon.java new file mode 100644 index 000000000..ac4602407 --- /dev/null +++ b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/EaopEngineAddon.java @@ -0,0 +1,144 @@ +package org.eclipse.gemoc.executionframework.addon.eaop.server; + +import java.util.Collection; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import org.eclipse.gemoc.executionframework.addon.eaop.server.mapper.EngineMapper; +import org.eclipse.gemoc.executionframework.addon.eaop.server.mapper.StepMapper; +import org.eclipse.gemoc.protocols.eaop.api.data.AboutToExecuteStepEventArguments; +import org.eclipse.gemoc.protocols.eaop.api.data.EngineAboutToDisposeEventArguments; +import org.eclipse.gemoc.protocols.eaop.api.data.EngineAboutToStartEventArguments; +import org.eclipse.gemoc.protocols.eaop.api.data.EngineAboutToStopEventArguments; +import org.eclipse.gemoc.protocols.eaop.api.data.EngineInitializedEventArguments; +import org.eclipse.gemoc.protocols.eaop.api.data.EngineStartedEventArguments; +import org.eclipse.gemoc.protocols.eaop.api.data.EngineStoppedEventArguments; +import org.eclipse.gemoc.protocols.eaop.api.data.StepExecutedEventArguments; +import org.eclipse.gemoc.trace.commons.model.trace.Step; +import org.eclipse.gemoc.xdsmlframework.api.core.EngineStatus.RunStatus; +import org.eclipse.gemoc.xdsmlframework.api.core.IExecutionEngine; +import org.eclipse.gemoc.xdsmlframework.api.engine_addon.IEngineAddon; + +public class EaopEngineAddon implements IEngineAddon { + + public EaopEngineAddon() { + // TODO Auto-generated constructor stub + } + + @Override + public void engineAboutToStart(IExecutionEngine engine) { + + // look for EaopServerImpl listening this engine (ie. those with regexp matching this engine name) + Set applicableEaopServers = getApplicableEaopServers(engine); + + for(EaopServerImpl s : applicableEaopServers) { + EngineAboutToStartEventArguments arg = new EngineAboutToStartEventArguments(); + arg.setEngine(EngineMapper.INSTANCE.executionEngineToExecutionEngineDto(engine)); + s.eaopClient.engineAboutToStart(arg); + } + } + + @Override + public void engineStarted(IExecutionEngine engine) { + // look for EaopServerImpl listening this engine (ie. those with regexp matching this engine name) + Set applicableEaopServers = getApplicableEaopServers(engine); + for(EaopServerImpl s : applicableEaopServers) { + EngineStartedEventArguments arg = new EngineStartedEventArguments(); + arg.setEngine(EngineMapper.INSTANCE.executionEngineToExecutionEngineDto(engine)); + s.eaopClient.engineStarted(arg); + } + + } + + @Override + public void engineInitialized(IExecutionEngine engine) { + Set applicableEaopServers = getApplicableEaopServers(engine); + for(EaopServerImpl s : applicableEaopServers) { + EngineInitializedEventArguments arg = new EngineInitializedEventArguments(); + arg.setEngine(EngineMapper.INSTANCE.executionEngineToExecutionEngineDto(engine)); + s.eaopClient.engineInitialized(arg); + } + } + + @Override + public void engineAboutToStop(IExecutionEngine engine) { + Set applicableEaopServers = getApplicableEaopServers(engine); + for(EaopServerImpl s : applicableEaopServers) { + EngineAboutToStopEventArguments arg = new EngineAboutToStopEventArguments(); + arg.setEngine(EngineMapper.INSTANCE.executionEngineToExecutionEngineDto(engine)); + s.eaopClient.engineAboutToStop(arg); + } + } + + @Override + public void engineStopped(IExecutionEngine engine) { + Set applicableEaopServers = getApplicableEaopServers(engine); + for(EaopServerImpl s : applicableEaopServers) { + EngineStoppedEventArguments arg = new EngineStoppedEventArguments(); + arg.setEngine(EngineMapper.INSTANCE.executionEngineToExecutionEngineDto(engine)); + s.eaopClient.engineStopped(arg); + } + } + + @Override + public void engineAboutToDispose(IExecutionEngine engine) { + Set applicableEaopServers = getApplicableEaopServers(engine); + for(EaopServerImpl s : applicableEaopServers) { + EngineAboutToDisposeEventArguments arg = new EngineAboutToDisposeEventArguments(); + arg.setEngine(EngineMapper.INSTANCE.executionEngineToExecutionEngineDto(engine)); + s.eaopClient.engineAboutToDispose(arg); + } + } + + @Override + public void aboutToSelectStep(IExecutionEngine engine, Collection> steps) { + // TODO + } + + @Override + public void proposedStepsChanged(IExecutionEngine engine, Collection> steps) { + // TODO + } + + @Override + public void stepSelected(IExecutionEngine engine, Step selectedStep) { + // TODO + } + + @Override + public void aboutToExecuteStep(IExecutionEngine engine, Step stepToExecute) { + Set applicableEaopServers = getApplicableEaopServers(engine); + for(EaopServerImpl s : applicableEaopServers) { + AboutToExecuteStepEventArguments arg = new AboutToExecuteStepEventArguments(); + arg.setEngine(EngineMapper.INSTANCE.executionEngineToExecutionEngineDto(engine)); + arg.setStepToExecute(StepMapper.INSTANCE.stepToStepDto(stepToExecute)); + s.eaopClient.aboutToExecuteStep(arg); + } + } + + @Override + public void stepExecuted(IExecutionEngine engine, Step stepExecuted) { + Set applicableEaopServers = getApplicableEaopServers(engine); + IEngineAddon.super.stepExecuted(engine, stepExecuted);for(EaopServerImpl s : applicableEaopServers) { + StepExecutedEventArguments arg = new StepExecutedEventArguments(); + arg.setEngine(EngineMapper.INSTANCE.executionEngineToExecutionEngineDto(engine)); + arg.setStepToExecute(StepMapper.INSTANCE.stepToStepDto(stepExecuted)); + s.eaopClient.stepExecuted(arg); + } + } + + @Override + public void engineStatusChanged(IExecutionEngine engine, RunStatus newStatus) { + // TODO + } + + + protected Set getApplicableEaopServers(IExecutionEngine engine) { + Set eaopServers = Activator.getDefault().getStartedEaopServer(); + return eaopServers.stream() + .filter(s -> Pattern.compile(s.engineIdRegExp).matcher(engine.getName()).matches()) + .collect(Collectors.toSet()); + } + +} diff --git a/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/EaopServerEndPoint.java b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/EaopServerEndPoint.java new file mode 100644 index 000000000..1f71a15e1 --- /dev/null +++ b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/EaopServerEndPoint.java @@ -0,0 +1,137 @@ +package org.eclipse.gemoc.executionframework.addon.eaop.server; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.util.HashMap; +import java.util.Map; + +import javax.websocket.CloseReason; +import javax.websocket.OnClose; +import javax.websocket.OnError; +import javax.websocket.OnMessage; +import javax.websocket.OnOpen; +import javax.websocket.Session; +import javax.websocket.server.PathParam; +import javax.websocket.server.ServerEndpoint; + +import org.eclipse.gemoc.commons.utils.ExtensibleInputStream; +import org.eclipse.gemoc.executionframework.addon.eaop.server.rpclaunch.EaopJsonRPCLauncher; +import org.eclipse.gemoc.protocols.eaop.api.services.IEngineAddonProtocolClient; +import org.eclipse.lsp4j.jsonrpc.Launcher; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +//@ServerEndpoint("/eaop/{engineId}")* +@ServerEndpoint("/eaop") +public class EaopServerEndPoint { + + private static final Logger LOGGER = LoggerFactory.getLogger(EaopServerEndPoint.class); + + boolean supportHeader = true; + + /** + * map of streams associated to the websocket sessions + * each stream is in charge of converting the received messages to the stream used by json rcp + */ + Map activeSessions = new HashMap(); + + EaopServerImpl server; + + /** + * + * @param session + */ + @OnOpen + public void onOpen(Session session) { + //public void onOpen(Session session, @PathParam("engineId") String engineIdEncodedString) { + LOGGER.info("Starting connection..."); + //Activator.debug("Starting connection: engineId=\""+ engineIdEncodedString+"\""); + Activator.debug("Starting connection"); + + String engineId = ""; + /*try { + engineId = URLDecoder.decode(engineIdEncodedString, "UTF-8"); + } catch (UnsupportedEncodingException e) { + LOGGER.error(e.getMessage(), e); + }*/ + + // create server + server = new EaopServerImpl(); + Activator.getDefault().getStartedEaopServer().add(server); + + + ExtensibleInputStream in = new ExtensibleInputStream(); + activeSessions.put(session, in); + OutputStream outputstream = new OutputStream() { + + ByteArrayOutputStream internal = new ByteArrayOutputStream(); + + @Override + public void write(int b) throws IOException { + internal.write(b); + } + + @Override + public void flush() throws IOException { + String response = new String(internal.toByteArray(), "UTF-8"); + if(!supportHeader) { //LSP specifies that there is a header but messages from Monaco do not have a header + response = response.substring(response.indexOf("{")); + } + session.getBasicRemote().sendText(response); + internal.reset(); + + LOGGER.debug("Response sent: "+ response); + System.out.println("[DEBUG] Sent: " + response); + } + }; + + Launcher serverSideLauncher = EaopJsonRPCLauncher.createLauncher(server, IEngineAddonProtocolClient.class, in, outputstream); + server.connectClient(serverSideLauncher.getRemoteProxy()); + + serverSideLauncher.startListening(); + } + @OnClose + public void onClose(Session session, CloseReason closeReason) { + activeSessions.remove(session); + Activator.getDefault().getStartedEaopServer().remove(server); + LOGGER.debug("Closing session "+session.getId()+" "+session.getRequestURI()); + } + + @OnMessage + public void onMessage(String message, Session session) { + if(!message.startsWith("Content-Length:")) { //LSP specifies that there is a header but messages from Monaco do not have a header + supportHeader = false; + message = addHeader(message); + } + + System.out.println("[DEBUG] Message: " + message); + + ExtensibleInputStream inputStream = activeSessions.get(session); + if(inputStream != null) { + inputStream.addMessage(message); + } + } + + public String addHeader(String requestContent) { + String header = ""; + try { + int length = requestContent.getBytes("UTF-8").length; + header = "Content-Length: " + length + "\n\n"; + } catch (UnsupportedEncodingException e) { + LOGGER.error(e.getMessage()); + //Activator.logError(e.getMessage(), e); + } + + return header + requestContent; + } + + @OnError + public void onError(Session session, Throwable throwable) { + LOGGER.error("Error "+throwable.getMessage()+" on session "+session.getId()+" "+session.getRequestURI(), throwable); + } + +} diff --git a/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/EaopServerImpl.java b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/EaopServerImpl.java new file mode 100644 index 000000000..19adcdfe7 --- /dev/null +++ b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/EaopServerImpl.java @@ -0,0 +1,140 @@ +package org.eclipse.gemoc.executionframework.addon.eaop.server; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +import org.eclipse.gemoc.protocols.eaop.api.data.GetStateArguments; +import org.eclipse.gemoc.protocols.eaop.api.data.GetStateResponse; +import org.eclipse.gemoc.protocols.eaop.api.data.GetStepArguments; +import org.eclipse.gemoc.protocols.eaop.api.data.GetStepResponse; +import org.eclipse.gemoc.protocols.eaop.api.data.InitializeArguments; +import org.eclipse.gemoc.protocols.eaop.api.data.InitializeResponse; +import org.eclipse.gemoc.protocols.eaop.api.services.IEngineAddonProtocolClient; +import org.eclipse.gemoc.protocols.eaop.api.services.IEngineAddonProtocolServer; +import org.eclipse.gemoc.xdsmlframework.api.core.IExecutionEngine; +import org.eclipse.lsp4j.jsonrpc.json.JsonRpcMethod; +import org.eclipse.lsp4j.jsonrpc.json.JsonRpcMethodProvider; +import org.eclipse.lsp4j.jsonrpc.services.ServiceEndpoints; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class EaopServerImpl implements IEngineAddonProtocolServer, org.eclipse.lsp4j.jsonrpc.Endpoint, JsonRpcMethodProvider{ + + private static final Logger LOG = LoggerFactory.getLogger(EaopServerImpl.class); + + + /** + * id of the engine in the engine manager (ie. + * org.eclipse.gemoc.executionframework.engine.Activator.getDefault().gemocRunningEngineRegistry) + */ + //protected String engineId; + + //protected IExecutionEngine engine; + + /** + * regexp for engines listened by this EaopServer + */ + protected String engineIdRegExp = ".*"; + + protected IEngineAddonProtocolClient eaopClient; + + public EaopServerImpl() { + //this.engineId = engineId; + //initEMFJSON(); + } + + public void connectClient(IEngineAddonProtocolClient client) { + eaopClient = client; + + } + + // ************************************** + // * org.eclipse.lsp4j.jsonrpc.Endpoint * + // ************************************** + /** + * from org.eclipse.lsp4j.jsonrpc.Endpoint jsonrpc request + */ + @Override + public CompletableFuture request(String method, Object parameter) { + throw new UnsupportedOperationException("The json request \'" + method + "\' is unknown."); + } + /** + * jsonrpc notifications + */ + @Override + public void notify(String method, Object parameter) { + LOG.debug("notify " + method); + } + + + // ******************************************************** + // * org.eclipse.lsp4j.jsonrpc.json.JsonRpcMethodProvider * + // ******************************************************** + + private Map supportedMethods; + + @Override + public Map supportedMethods() { + if (supportedMethods != null) { + return supportedMethods; + } + Map supportedMethods = new LinkedHashMap<>(); + supportedMethods.putAll(ServiceEndpoints.getSupportedMethods(getClass())); + + for (JsonRpcMethod supportedMethod : supportedMethods.values()) { + LOG.info("supported method " + supportedMethod.getMethodName() + " " + supportedMethod.getParameterTypes()); + } + this.supportedMethods = supportedMethods; + return supportedMethods; + } + + // **************************************************************************** + // * org.eclipse.gemoc.protocols.eaop.api.services.IEngineAddonProtocolServer * + // **************************************************************************** + @Override + public CompletableFuture initialize(InitializeArguments arguments) { + LOG.info("CompletableFuture initialize()"); + //return IEngineAddonProtocolServer.super.initialize(arguments); + + engineIdRegExp = ".*"; + + CompletableFuture future = CompletableFuture.supplyAsync(new Supplier() { + + @Override + public InitializeResponse get() { + // TODO Auto-generated method stub + InitializeResponse response = new InitializeResponse(); + return response; + } + + }); + return future; + } + + @Override + public CompletableFuture getState(GetStateArguments arguments) { + // TODO Auto-generated method stub + return IEngineAddonProtocolServer.super.getState(arguments); + } + + @Override + public CompletableFuture getStep(GetStepArguments arguments) { + // TODO Auto-generated method stub + return IEngineAddonProtocolServer.super.getStep(arguments); + } + + + // helper methods + + +/* + protected IExecutionEngine getEngine() { + return org.eclipse.gemoc.executionframework.engine.Activator.getDefault().gemocRunningEngineRegistry.getRunningEngines().get(this.engineId); + } + + public static EaopEngineAddon getEaopEngineAddon(IExecutionEngine engine) { + return engine.getAddon(EaopEngineAddon.class); + }*/ +} diff --git a/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/mapper/EngineMapper.java b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/mapper/EngineMapper.java new file mode 100644 index 000000000..5483202e1 --- /dev/null +++ b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/mapper/EngineMapper.java @@ -0,0 +1,16 @@ +package org.eclipse.gemoc.executionframework.addon.eaop.server.mapper; + +import org.eclipse.gemoc.protocols.eaop.api.data.ExecutionEngineDto; +import org.eclipse.gemoc.xdsmlframework.api.core.IExecutionEngine; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public interface EngineMapper { + EngineMapper INSTANCE = Mappers.getMapper( EngineMapper.class ); + + @Mapping(expression = "java(engine.engineKindName())", target = "engineKindName") + @Mapping(source = "name", target = "engineName") + ExecutionEngineDto executionEngineToExecutionEngineDto(IExecutionEngine engine); +} diff --git a/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/mapper/StepMapper.java b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/mapper/StepMapper.java new file mode 100644 index 000000000..980cae698 --- /dev/null +++ b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/mapper/StepMapper.java @@ -0,0 +1,53 @@ +package org.eclipse.gemoc.executionframework.addon.eaop.server.mapper; + +import java.util.stream.Collectors; + +import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gemoc.protocols.eaop.api.data.MSEDto; +import org.eclipse.gemoc.protocols.eaop.api.data.MSEOccurenceDto; +import org.eclipse.gemoc.protocols.eaop.api.data.StepDto; +import org.eclipse.gemoc.trace.commons.model.trace.MSE; +import org.eclipse.gemoc.trace.commons.model.trace.MSEOccurrence; +import org.eclipse.gemoc.trace.commons.model.trace.State; +import org.eclipse.gemoc.trace.commons.model.trace.Step; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.factory.Mappers; + +@Mapper +public abstract class StepMapper { + public static final StepMapper INSTANCE = Mappers.getMapper( StepMapper.class ); + + @Mapping(source = "mseoccurrence", target = "mseOccurence") + @Mapping(source = "startingState", target = "startingStateID") + @Mapping(source = "endingState", target = "endingStateID") + public abstract StepDto stepToStepDto(Step step); + + public abstract MSEOccurenceDto mSEOccurenceToMSEOccurenceDto(MSEOccurrence mseOccurrence); + + + @Mapping(source = "caller", target = "callerEObjectURI") + @Mapping(source = "action", target = "actionID") + public abstract MSEDto mSEToMSEDto(MSE mSE); + + String mapEObjectToURI(EObject eObj) { + if(eObj == null ) return ""; + if(eObj.eResource() != null) { + return eObj.eResource().getURIFragment(eObj).toString(); + } else { + // TODO + return eObj.toString(); + } + } + + String map(EList value) { + // TODO find nicer parameter represention / uri + return value.stream().map(o -> o.toString()).collect(Collectors.joining(",")); + } + + @SuppressWarnings("rawtypes") + String getStateID(State state) { + return mapEObjectToURI(state); + } +} diff --git a/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/rpclaunch/EaopJsonRPCLauncher.java b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/rpclaunch/EaopJsonRPCLauncher.java new file mode 100644 index 000000000..e8a82dac4 --- /dev/null +++ b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/rpclaunch/EaopJsonRPCLauncher.java @@ -0,0 +1,83 @@ +package org.eclipse.gemoc.executionframework.addon.eaop.server.rpclaunch; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Map; + +import org.eclipse.gemoc.protocols.eaop.api.json.EaopMessageJsonHandler; +import org.eclipse.lsp4j.jsonrpc.Endpoint; +import org.eclipse.lsp4j.jsonrpc.Launcher; +import org.eclipse.lsp4j.jsonrpc.MessageConsumer; +import org.eclipse.lsp4j.jsonrpc.RemoteEndpoint; +import org.eclipse.lsp4j.jsonrpc.json.JsonRpcMethod; +import org.eclipse.lsp4j.jsonrpc.json.MessageJsonHandler; +import org.eclipse.lsp4j.jsonrpc.json.StreamMessageConsumer; +import org.eclipse.lsp4j.jsonrpc.services.ServiceEndpoints; + +/** + * Specialized launcher for the EAOP Protocol. + * It binds together: + * - the Implementation of the of the EAOP server + * - input and output streams of the JSONRPC + * - the representation of the remote object (ie. client) + */ +public class EaopJsonRPCLauncher { + + private EaopJsonRPCLauncher() {} + + /** + * Create a new Launcher for a given local service object, a given remote + * interface and an input and output stream. + * + * @param localService - an object on which classes RPC methods are looked up + * @param remoteInterface - an interface on which RPC methods are looked up + * @param in - inputstream to listen for incoming messages + * @param out - outputstream to send outgoing messages + */ + public static Launcher createLauncher(Object localService, Class remoteInterface, InputStream in, + OutputStream out) { + return new Builder().setLocalService(localService).setRemoteInterface(remoteInterface).setInput(in) + .setOutput(out).create(); + } + + /** + * Launcher builder for the debug protocol. Adapts the JSON-RPC message classes + * to the JSON format used by the debug protocol. + */ + public static class Builder extends Launcher.Builder { + + @Override + protected MessageJsonHandler createJsonHandler() { + Map supportedMethods = getSupportedMethods(); + if (configureGson != null) + return new EaopMessageJsonHandler(supportedMethods, configureGson); + else + return new EaopMessageJsonHandler(supportedMethods); + } + + @Override + protected RemoteEndpoint createRemoteEndpoint(MessageJsonHandler jsonHandler) { + try { + MessageConsumer outgoingMessageStream = new StreamMessageConsumer(output, jsonHandler); + outgoingMessageStream = wrapMessageConsumer(outgoingMessageStream); + Endpoint localEndpoint = ServiceEndpoints.toEndpoint(localServices); + RemoteEndpoint remoteEndpoint; + + // !!!! nosuchfieldException that is trapped by quarkus + // check if this is a version issue ? + if (exceptionHandler == null) + remoteEndpoint = new EaopRemoteEndpoint(outgoingMessageStream, localEndpoint); + else + remoteEndpoint = new EaopRemoteEndpoint(outgoingMessageStream, localEndpoint, exceptionHandler); + jsonHandler.setMethodProvider(remoteEndpoint); + return remoteEndpoint; + } catch (Exception e) { + System.out.println(" issue in createRemoteEndpoint" + e); + e.printStackTrace(); + return null; + } + } + + } + +} diff --git a/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/rpclaunch/EaopRemoteEndpoint.java b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/rpclaunch/EaopRemoteEndpoint.java new file mode 100644 index 000000000..a429f2f7c --- /dev/null +++ b/framework/execution_framework/plugins/org.eclipse.gemoc.executionframework.addon.eaop.server/src/org/eclipse/gemoc/executionframework/addon/eaop/server/rpclaunch/EaopRemoteEndpoint.java @@ -0,0 +1,54 @@ +package org.eclipse.gemoc.executionframework.addon.eaop.server.rpclaunch; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; + +import org.eclipse.gemoc.protocols.eaop.api.messages.EaopNotificationMessage; +import org.eclipse.gemoc.protocols.eaop.api.messages.EaopRequestMessage; +import org.eclipse.gemoc.protocols.eaop.api.messages.EaopResponseMessage; +import org.eclipse.lsp4j.jsonrpc.Endpoint; +import org.eclipse.lsp4j.jsonrpc.MessageConsumer; +import org.eclipse.lsp4j.jsonrpc.RemoteEndpoint; +import org.eclipse.lsp4j.jsonrpc.messages.RequestMessage; +import org.eclipse.lsp4j.jsonrpc.messages.ResponseError; + +public class EaopRemoteEndpoint extends RemoteEndpoint { + + private final AtomicInteger nextSeqId = new AtomicInteger(); + + public EaopRemoteEndpoint(MessageConsumer out, Endpoint localEndpoint) { + super(out, localEndpoint); + } + + public EaopRemoteEndpoint(MessageConsumer out, Endpoint localEndpoint, + Function exceptionHandler) { + super(out, localEndpoint, exceptionHandler); + } + @Override + protected EaopRequestMessage createRequestMessage(String method, Object parameter) { + EaopRequestMessage requestMessage = new EaopRequestMessage(); + requestMessage.setId(nextSeqId.incrementAndGet()); + requestMessage.setMethod(method); + requestMessage.setParams(parameter); + return requestMessage; + } + + @Override + protected EaopResponseMessage createResponseMessage(RequestMessage requestMessage) { + EaopResponseMessage responseMessage = new EaopResponseMessage(); + responseMessage.setResponseId(nextSeqId.incrementAndGet()); + responseMessage.setRawId(requestMessage.getRawId()); + responseMessage.setMethod(requestMessage.getMethod()); + return responseMessage; + } + + @Override + protected EaopNotificationMessage createNotificationMessage(String method, Object parameter) { + EaopNotificationMessage notificationMessage = new EaopNotificationMessage(); + notificationMessage.setId(nextSeqId.incrementAndGet()); + notificationMessage.setMethod(method); + notificationMessage.setParams(parameter); + return notificationMessage; + } + +} diff --git a/framework/execution_framework/plugins/pom.xml b/framework/execution_framework/plugins/pom.xml index cb8c50d85..1a972c7f0 100644 --- a/framework/execution_framework/plugins/pom.xml +++ b/framework/execution_framework/plugins/pom.xml @@ -20,6 +20,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xs + org.eclipse.gemoc.executionframework.addon.eaop.server org.eclipse.gemoc.executionframework.behavioralinterface org.eclipse.gemoc.executionframework.behavioralinterface.edit org.eclipse.gemoc.executionframework.behavioralinterface.editor diff --git a/framework/execution_framework/releng/org.eclipse.gemoc.executionframework.feature/feature.xml b/framework/execution_framework/releng/org.eclipse.gemoc.executionframework.feature/feature.xml index 4f7fa9457..9f2084f23 100644 --- a/framework/execution_framework/releng/org.eclipse.gemoc.executionframework.feature/feature.xml +++ b/framework/execution_framework/releng/org.eclipse.gemoc.executionframework.feature/feature.xml @@ -130,4 +130,18 @@ http://www.eclipse.org/legal/epl-v10.html version="0.0.0" unpack="false"/> + + + + diff --git a/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/.classpath b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/.classpath new file mode 100644 index 000000000..e801ebfb4 --- /dev/null +++ b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/.project b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/.project new file mode 100644 index 000000000..941174cea --- /dev/null +++ b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/.project @@ -0,0 +1,28 @@ + + + org.eclipse.gemoc.ws.server + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/.settings/org.eclipse.jdt.core.prefs b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..7adc0fb9a --- /dev/null +++ b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,10 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=11 +org.eclipse.jdt.core.compiler.compliance=11 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning +org.eclipse.jdt.core.compiler.release=enabled +org.eclipse.jdt.core.compiler.source=11 diff --git a/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/META-INF/MANIFEST.MF b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/META-INF/MANIFEST.MF new file mode 100644 index 000000000..7a9314655 --- /dev/null +++ b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/META-INF/MANIFEST.MF @@ -0,0 +1,25 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: GEMOC Websocket Server +Bundle-SymbolicName: org.eclipse.gemoc.ws.server;singleton:=true +Bundle-Version: 1.0.0.qualifier +Bundle-Activator: org.eclipse.gemoc.ws.server.Activator +Require-Bundle: org.eclipse.core.runtime, + org.eclipse.equinox.registry, + org.apache.aries.spifly.dynamic.bundle;bundle-version="1.3.4", + org.eclipse.gemoc.commons.eclipse.messagingsystem.api +Bundle-RequiredExecutionEnvironment: JavaSE-11 +Automatic-Module-Name: org.eclipse.gemoc.ws.server +Bundle-ActivationPolicy: lazy +Bundle-Vendor: Eclipse +Export-Package: org.eclipse.gemoc.ws.server +Import-Package: javax.servlet;version="4.0.0", + javax.websocket;version="1.1.0", + javax.websocket.server;version="1.1.0", + org.eclipse.jetty.server;version="10.0.6", + org.eclipse.jetty.server.handler;version="10.0.6", + org.eclipse.jetty.servlet;version="10.0.6", + org.eclipse.jetty.util;version="10.0.6", + org.eclipse.jetty.util.component;version="10.0.6", + org.eclipse.jetty.websocket.javax.server.config;version="10.0.6", + org.eclipse.jetty.websocket.javax.server.internal;version="10.0.6" diff --git a/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/build.properties b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/build.properties new file mode 100644 index 000000000..3595411e8 --- /dev/null +++ b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/build.properties @@ -0,0 +1,6 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + plugin.xml,\ + schema/ diff --git a/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/plugin.xml b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/plugin.xml new file mode 100644 index 000000000..63cbf1d65 --- /dev/null +++ b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/plugin.xml @@ -0,0 +1,13 @@ + + + + + + + + + + diff --git a/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/schema/org.eclipse.gemoc.ws.server.endpoint.exsd b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/schema/org.eclipse.gemoc.ws.server.endpoint.exsd new file mode 100644 index 000000000..cc3381911 --- /dev/null +++ b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/schema/org.eclipse.gemoc.ws.server.endpoint.exsd @@ -0,0 +1,117 @@ + + + + + + + + + [Enter description of this extension point.] + + + + + + + + + + Contribute a new @ServerEndpoint or @ClientEndpoint to the server hosted by the org.eclipse.gemoc.ws.server + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Contribute a new @ServerEndpoint or @ClientEndpoint to the server hosted by the org.eclipse.gemoc.ws.server + + + + + + + Id in order to help retreive this contribution + + + + + + + class implementing the JSR356 API with an @ServerEndpoint or @ClientEndpoint annotation tha will be added to the WebSocket server + + + + + + + + + + + + + + + [Enter the first release in which this extension point appears.] + + + + + + + + + [Enter extension point usage example here.] + + + + + + + + + [Enter API information here.] + + + + + + + + + [Enter information about supplied implementation of this extension point.] + + + + + diff --git a/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/src/org/eclipse/gemoc/ws/server/Activator.java b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/src/org/eclipse/gemoc/ws/server/Activator.java new file mode 100644 index 000000000..652ded7ea --- /dev/null +++ b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/src/org/eclipse/gemoc/ws/server/Activator.java @@ -0,0 +1,182 @@ +/******************************************************************************* + * Copyright (c) 2020 Inria and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Inria - initial API and implementation + *******************************************************************************/ +package org.eclipse.gemoc.ws.server; + +import javax.servlet.ServletContext; +import javax.websocket.DeploymentException; +import javax.websocket.server.ServerContainer; +import javax.websocket.server.ServerEndpoint; +import javax.websocket.server.ServerEndpointConfig; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Plugin; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.gemoc.commons.eclipse.messagingsystem.api.MessagingSystem; +import org.eclipse.gemoc.commons.eclipse.messagingsystem.api.MessagingSystemManager; +import org.eclipse.gemoc.ws.server.endpoint.EndPointExtensionPointHelper; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.websocket.javax.server.config.JavaxWebSocketServletContainerInitializer; +import org.osgi.framework.BundleContext; + +public class Activator extends Plugin { + + // The plug-in ID + public static final String PLUGIN_ID = "org.eclipse.gemoc.ws.server"; //$NON-NLS-1$ + public static final String CONSOLE_NAME = "GEMOC websocket server"; //$NON-NLS-1$ + + // The shared instance + private static Activator plugin; + private BundleContext context; + + public static BundleContext getBundleContext() { + return getDefault().context; + } + + public static Activator getDefault() { + return plugin; + } + + public static synchronized void logError(String message, Throwable ex) { + if (message == null) { + message = ""; //$NON-NLS-1$ + } + Status errorStatus = new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, message, ex); + Activator.getDefault().getLog().log(errorStatus); + } + + public static synchronized void logStatus(IStatus errorStatus) { + Activator.getDefault().getLog().log(errorStatus); + } + + protected Server server; + protected ServerContainer wsContainer; + protected int assignedPort; + + @Override + public void start(BundleContext context) throws Exception { + super.start(context); + plugin = this; + this.context = context; + + // starts the server later in order to be able to load the classes of the + // contributing EndPoints + Job job = new Job("Start GEMOC WebSocket Server") { + protected IStatus run(IProgressMonitor monitor) { + try { + Activator.getDefault().startWSServer(); + } catch (Exception e) { + logError(e.getMessage(), e); + } + return Status.OK_STATUS; + } + }; + job.setPriority(Job.SHORT); + job.schedule(); + } + + @Override + public void stop(BundleContext context) throws Exception { + stopWSServer(); + this.context = null; + plugin = null; + super.stop(context); + } + + /** + * Starts a standard API websocket server using jetty 10 + * + * https://www.eclipse.org/jetty/documentation/jetty-10/programming-guide/index.html#pg-server-websocket-standard + * + * @throws Exception + */ + public synchronized void startWSServer() throws Exception { + // Create a Server with a ServerConnector listening on random port. + server = new Server(0); + + // Create a ServletContextHandler with the given context path. + ServletContextHandler handler = new ServletContextHandler(server, "/"); + server.setHandler(handler); + + // Setup the ServerContainer and the WebSocket endpoints for this web + + + JavaxWebSocketServletContainerInitializer.configure(handler, (servletContext, container) -> { + // Configure the ServerContainer. + container.setDefaultMaxTextMessageBufferSize(128 * 1024); + // Simple registration of your WebSocket endpoints. + for (Class endPointClass : EndPointExtensionPointHelper.getAllEndPointClasses()) { + try { + ServerEndpoint endPointAnnotation = endPointClass + .getDeclaredAnnotation(javax.websocket.server.ServerEndpoint.class); + if (endPointAnnotation != null) { + String path = endPointAnnotation.value(); + info("Adding Endpoint class: " + endPointClass.getCanonicalName() + " on " + path); + // Simple registration of WebSocket endpoints. + container.addEndpoint(endPointClass); + // doesn't work yet, -> Cannot load platform configurator, probably a classpath/osgi issue + //container.addEndpoint(ServerEndpointConfig.Builder.create(endPointClass, path).build()); + } + } catch (Exception e) { + error("Failed to add Enpoint class: " + endPointClass.getCanonicalName(), e); + } + } + + }); + + server.start(); + assignedPort = server.getURI().getPort(); + info("Assigned port: " + server.getURI().getPort()); + server.dump(System.err); + } + + public synchronized void stopWSServer() throws Exception { + if (server != null) + server.stop(); + } + + public Server getServer() { + return server; + } + + public int getAssignedPort() { + return assignedPort; + } + + protected MessagingSystem messaggingSystem = null; + + public MessagingSystem getMessaggingSystem() { + if (messaggingSystem == null) { + MessagingSystemManager msm = new MessagingSystemManager(); + messaggingSystem = msm.createBestPlatformMessagingSystem(PLUGIN_ID, CONSOLE_NAME); + } + return messaggingSystem; + } + + public static void info(String msg) { + Activator.getDefault().getMessaggingSystem().info(msg, PLUGIN_ID); + } + + public static void warn(String msg, Throwable e) { + // Activator.getDefault().getLog().log(new Status(Status.WARNING, PLUGIN_ID, + // Status.OK, msg, e)); + Activator.getDefault().getMessaggingSystem().warn(msg, PLUGIN_ID, e); + } + + public static void error(String msg, Throwable e) { + // Activator.getDefault().getLog().log(new Status(Status.ERROR, PLUGIN_ID, + // Status.OK, msg, e)); + Activator.getDefault().getMessaggingSystem().error(msg, PLUGIN_ID, e); + } + +} diff --git a/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/src/org/eclipse/gemoc/ws/server/endpoint/EndPointExtensionPointHelper.java b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/src/org/eclipse/gemoc/ws/server/endpoint/EndPointExtensionPointHelper.java new file mode 100644 index 000000000..7eee1fdff --- /dev/null +++ b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/src/org/eclipse/gemoc/ws/server/endpoint/EndPointExtensionPointHelper.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (c) 2020 Inria and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Inria - initial API and implementation + *******************************************************************************/ +package org.eclipse.gemoc.ws.server.endpoint; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.Platform; +import org.eclipse.gemoc.ws.server.Activator; + +public class EndPointExtensionPointHelper { + + public static String ENDPOINT_EXTENSIONPOINT_ID = "org.eclipse.gemoc.ws.server.endpoint"; + public static String ENDPOINT_EXTENSIONPOINT_ID_ATT = "id"; + public static String ENDPOINT_EXTENSIONPOINT_CLASS_ATT = "class"; + + public static IConfigurationElement[] getEndPointExtensionConfiguration() { + return Platform.getExtensionRegistry().getConfigurationElementsFor(ENDPOINT_EXTENSIONPOINT_ID); + } + + public static Object createEndPointObject(IConfigurationElement endPointExtensionConfiguration) throws CoreException { + return endPointExtensionConfiguration.createExecutableExtension(ENDPOINT_EXTENSIONPOINT_CLASS_ATT); + } + + public static String getEndPointId(IConfigurationElement endPointExtensionConfiguration) throws CoreException { + return endPointExtensionConfiguration.getAttribute(ENDPOINT_EXTENSIONPOINT_ID_ATT); + } + + public static List> getAllEndPointClasses() { + ArrayList> result = new ArrayList>(); + for(IConfigurationElement conf : getEndPointExtensionConfiguration()) { + try { + result.add(createEndPointObject(conf).getClass()); + } catch (CoreException e) { + Activator.logError("Failed to get EndPoint class "+e.getMessage(), e); + } + } + return result; + } +} diff --git a/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/src/org/eclipse/gemoc/ws/server/endpoint/TestEndPoint.java b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/src/org/eclipse/gemoc/ws/server/endpoint/TestEndPoint.java new file mode 100644 index 000000000..537741a39 --- /dev/null +++ b/framework/framework_commons/plugins/org.eclipse.gemoc.ws.server/src/org/eclipse/gemoc/ws/server/endpoint/TestEndPoint.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2020 Inria and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Inria - initial API and implementation + *******************************************************************************/ +package org.eclipse.gemoc.ws.server.endpoint; + +import javax.websocket.OnMessage; +import javax.websocket.server.ServerEndpoint; + +@ServerEndpoint("/test") +public class TestEndPoint { + + + @OnMessage + public void handleOnMessage(String message) { + System.out.println("Message received by WebSocket : "+message); + } +} diff --git a/framework/framework_commons/plugins/pom.xml b/framework/framework_commons/plugins/pom.xml index 629159172..8a148a038 100644 --- a/framework/framework_commons/plugins/pom.xml +++ b/framework/framework_commons/plugins/pom.xml @@ -21,6 +21,7 @@ org.eclipse.gemoc.opsemanticsview.gen org.eclipse.gemoc.opsemanticsview.gen.k3 org.eclipse.gemoc.opsemanticsview.model + org.eclipse.gemoc.ws.server org.eclipse.gemoc.xdsmlframework.api org.eclipse.gemoc.xdsmlframework.commons org.eclipse.gemoc.xdsmlframework.commons.ui.k3 diff --git a/framework/framework_commons/releng/org.eclipse.gemoc.modeldebugging.framework.commons.feature/feature.xml b/framework/framework_commons/releng/org.eclipse.gemoc.modeldebugging.framework.commons.feature/feature.xml index 5fa51d456..391492142 100644 --- a/framework/framework_commons/releng/org.eclipse.gemoc.modeldebugging.framework.commons.feature/feature.xml +++ b/framework/framework_commons/releng/org.eclipse.gemoc.modeldebugging.framework.commons.feature/feature.xml @@ -9,7 +9,6 @@ Contributors: Inria - initial API and implementation --> - + diff --git a/framework/pom.xml b/framework/pom.xml index 8d61539ec..c884e70ee 100644 --- a/framework/pom.xml +++ b/framework/pom.xml @@ -17,6 +17,35 @@ xdsml_framework + + + + + + + + org.apache.maven.plugins + maven-antrun-plugin + 1.1 + + + initialize + + run + + + + Displaying value of 'mypath' property + [mypath] ${mypath} + [mypath2] ${mypath2} + + + + + + + + diff --git a/pom.xml b/pom.xml index 950ec5f10..0db156578 100644 --- a/pom.xml +++ b/pom.xml @@ -31,6 +31,12 @@ + protocols/engine_addon_protocol/pom.xml + commons/pom.xml + simulationmodelanimation/pom.xml + trace/pom.xml + framework/pom.xml + releng @@ -39,7 +45,7 @@ 11 11 - + 1.4.2.Final false @@ -70,6 +76,11 @@ ${env.JAVAFX_HOME}/lib/javafx-swt.jar system + + org.mapstruct + mapstruct-processor + ${org.mapstruct.version} + @@ -134,25 +145,6 @@ - org.eclipse.tycho target-platform-configuration @@ -173,16 +165,6 @@ gtk x86_64 - - linux - gtk - x86 - - - win32 - win32 - x86 - win32 win32 @@ -227,9 +209,16 @@ maven-compiler-plugin 3.8.0 - 11 - 11 + ${maven.compiler.source} + ${maven.compiler.target} ${project.build.sourceEncoding} + + + org.mapstruct + mapstruct-processor + ${org.mapstruct.version} + + @@ -290,44 +279,6 @@ - - - - commons - - true - - - commons/pom.xml - - - modelanimation - - true - - - simulationmodelanimation/pom.xml - - - - trace_and_framework - - true - - - trace/pom.xml - framework/pom.xml - - - - releng - - true - - - releng - - quality diff --git a/pomfirst/pom.xml b/pomfirst/pom.xml index 61840563f..900f79557 100644 --- a/pomfirst/pom.xml +++ b/pomfirst/pom.xml @@ -56,6 +56,7 @@ ../framework/framework_commons/plugins/org.eclipse.gemoc.executionframework.reflectivetrace.model/pomfirst --> ../framework/framework_commons/pomfirst/org.eclipse.gemoc.xdsmlframework.api + ../protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api ../simulationmodelanimation/pomfirst/org.eclipse.gemoc.dsl.debug ../simulationmodelanimation/pomfirst/org.eclipse.gemoc.dsl.debug.edit ../simulationmodelanimation/pomfirst/org.eclipse.gemoc.dsl.debug.ide diff --git a/protocols/dap/specification/debugAdapterProtocol.json b/protocols/dap/specification/debugAdapterProtocol.json new file mode 100644 index 000000000..139f36402 --- /dev/null +++ b/protocols/dap/specification/debugAdapterProtocol.json @@ -0,0 +1,3897 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "title": "Debug Adapter Protocol", + "description": "The Debug Adapter Protocol defines the protocol used between an editor or IDE and a debugger or runtime.", + "type": "object", + + + "definitions": { + + "ProtocolMessage": { + "type": "object", + "title": "Base Protocol", + "description": "Base class of requests, responses, and events.", + "properties": { + "seq": { + "type": "integer", + "description": "Sequence number (also known as message ID). For protocol messages of type 'request' this ID can be used to cancel the request." + }, + "type": { + "type": "string", + "description": "Message type.", + "_enum": [ "request", "response", "event" ] + } + }, + "required": [ "seq", "type" ] + }, + + "Request": { + "allOf": [ { "$ref": "#/definitions/ProtocolMessage" }, { + "type": "object", + "description": "A client or debug adapter initiated request.", + "properties": { + "type": { + "type": "string", + "enum": [ "request" ] + }, + "command": { + "type": "string", + "description": "The command to execute." + }, + "arguments": { + "type": [ "array", "boolean", "integer", "null", "number" , "object", "string" ], + "description": "Object containing arguments for the command." + } + }, + "required": [ "type", "command" ] + }] + }, + + "Event": { + "allOf": [ { "$ref": "#/definitions/ProtocolMessage" }, { + "type": "object", + "description": "A debug adapter initiated event.", + "properties": { + "type": { + "type": "string", + "enum": [ "event" ] + }, + "event": { + "type": "string", + "description": "Type of event." + }, + "body": { + "type": [ "array", "boolean", "integer", "null", "number" , "object", "string" ], + "description": "Event-specific information." + } + }, + "required": [ "type", "event" ] + }] + }, + + "Response": { + "allOf": [ { "$ref": "#/definitions/ProtocolMessage" }, { + "type": "object", + "description": "Response for a request.", + "properties": { + "type": { + "type": "string", + "enum": [ "response" ] + }, + "request_seq": { + "type": "integer", + "description": "Sequence number of the corresponding request." + }, + "success": { + "type": "boolean", + "description": "Outcome of the request.\nIf true, the request was successful and the 'body' attribute may contain the result of the request.\nIf the value is false, the attribute 'message' contains the error in short form and the 'body' may contain additional information (see 'ErrorResponse.body.error')." + }, + "command": { + "type": "string", + "description": "The command requested." + }, + "message": { + "type": "string", + "description": "Contains the raw error in short form if 'success' is false.\nThis raw error might be interpreted by the frontend and is not shown in the UI.\nSome predefined values exist.", + "_enum": [ "cancelled" ], + "enumDescriptions": [ + "request was cancelled." + ] + }, + "body": { + "type": [ "array", "boolean", "integer", "null", "number" , "object", "string" ], + "description": "Contains request result if success is true and optional error details if success is false." + } + }, + "required": [ "type", "request_seq", "success", "command" ] + }] + }, + + "ErrorResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "On error (whenever 'success' is false), the body can provide more details.", + "properties": { + "body": { + "type": "object", + "properties": { + "error": { + "$ref": "#/definitions/Message", + "description": "An optional, structured error message." + } + } + } + }, + "required": [ "body" ] + }] + }, + + "CancelRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The 'cancel' request is used by the frontend in two situations:\n- to indicate that it is no longer interested in the result produced by a specific request issued earlier\n- to cancel a progress sequence. Clients should only call this request if the capability 'supportsCancelRequest' is true.\nThis request has a hint characteristic: a debug adapter can only be expected to make a 'best effort' in honouring this request but there are no guarantees.\nThe 'cancel' request may return an error if it could not cancel an operation but a frontend should refrain from presenting this error to end users.\nA frontend client should only call this request if the capability 'supportsCancelRequest' is true.\nThe request that got canceled still needs to send a response back. This can either be a normal result ('success' attribute true)\nor an error response ('success' attribute false and the 'message' set to 'cancelled').\nReturning partial results from a cancelled request is possible but please note that a frontend client has no generic way for detecting that a response is partial or not.\n The progress that got cancelled still needs to send a 'progressEnd' event back.\n A client should not assume that progress just got cancelled after sending the 'cancel' request.", + "properties": { + "command": { + "type": "string", + "enum": [ "cancel" ] + }, + "arguments": { + "$ref": "#/definitions/CancelArguments" + } + }, + "required": [ "command" ] + }] + }, + "CancelArguments": { + "type": "object", + "description": "Arguments for 'cancel' request.", + "properties": { + "requestId": { + "type": "integer", + "description": "The ID (attribute 'seq') of the request to cancel. If missing no request is cancelled.\nBoth a 'requestId' and a 'progressId' can be specified in one request." + }, + "progressId": { + "type": "string", + "description": "The ID (attribute 'progressId') of the progress to cancel. If missing no progress is cancelled.\nBoth a 'requestId' and a 'progressId' can be specified in one request." + } + } + }, + "CancelResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'cancel' request. This is just an acknowledgement, so no body field is required." + }] + }, + + "InitializedEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "title": "Events", + "description": "This event indicates that the debug adapter is ready to accept configuration requests (e.g. SetBreakpointsRequest, SetExceptionBreakpointsRequest).\nA debug adapter is expected to send this event when it is ready to accept configuration requests (but not before the 'initialize' request has finished).\nThe sequence of events/requests is as follows:\n- adapters sends 'initialized' event (after the 'initialize' request has returned)\n- frontend sends zero or more 'setBreakpoints' requests\n- frontend sends one 'setFunctionBreakpoints' request (if capability 'supportsFunctionBreakpoints' is true)\n- frontend sends a 'setExceptionBreakpoints' request if one or more 'exceptionBreakpointFilters' have been defined (or if 'supportsConfigurationDoneRequest' is not defined or false)\n- frontend sends other future configuration requests\n- frontend sends one 'configurationDone' request to indicate the end of the configuration.", + "properties": { + "event": { + "type": "string", + "enum": [ "initialized" ] + } + }, + "required": [ "event" ] + }] + }, + + "StoppedEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event indicates that the execution of the debuggee has stopped due to some condition.\nThis can be caused by a break point previously set, a stepping request has completed, by executing a debugger statement etc.", + "properties": { + "event": { + "type": "string", + "enum": [ "stopped" ] + }, + "body": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "description": "The reason for the event.\nFor backward compatibility this string is shown in the UI if the 'description' attribute is missing (but it must not be translated).", + "_enum": [ "step", "breakpoint", "exception", "pause", "entry", "goto", "function breakpoint", "data breakpoint", "instruction breakpoint" ] + }, + "description": { + "type": "string", + "description": "The full reason for the event, e.g. 'Paused on exception'. This string is shown in the UI as is and must be translated." + }, + "threadId": { + "type": "integer", + "description": "The thread which was stopped." + }, + "preserveFocusHint": { + "type": "boolean", + "description": "A value of true hints to the frontend that this event should not change the focus." + }, + "text": { + "type": "string", + "description": "Additional information. E.g. if reason is 'exception', text contains the exception name. This string is shown in the UI." + }, + "allThreadsStopped": { + "type": "boolean", + "description": "If 'allThreadsStopped' is true, a debug adapter can announce that all threads have stopped.\n- The client should use this information to enable that all threads can be expanded to access their stacktraces.\n- If the attribute is missing or false, only the thread with the given threadId can be expanded." + } + }, + "required": [ "reason" ] + } + }, + "required": [ "event", "body" ] + }] + }, + + "ContinuedEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event indicates that the execution of the debuggee has continued.\nPlease note: a debug adapter is not expected to send this event in response to a request that implies that execution continues, e.g. 'launch' or 'continue'.\nIt is only necessary to send a 'continued' event if there was no previous request that implied this.", + "properties": { + "event": { + "type": "string", + "enum": [ "continued" ] + }, + "body": { + "type": "object", + "properties": { + "threadId": { + "type": "integer", + "description": "The thread which was continued." + }, + "allThreadsContinued": { + "type": "boolean", + "description": "If 'allThreadsContinued' is true, a debug adapter can announce that all threads have continued." + } + }, + "required": [ "threadId" ] + } + }, + "required": [ "event", "body" ] + }] + }, + + "ExitedEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event indicates that the debuggee has exited and returns its exit code.", + "properties": { + "event": { + "type": "string", + "enum": [ "exited" ] + }, + "body": { + "type": "object", + "properties": { + "exitCode": { + "type": "integer", + "description": "The exit code returned from the debuggee." + } + }, + "required": [ "exitCode" ] + } + }, + "required": [ "event", "body" ] + }] + }, + + "TerminatedEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event indicates that debugging of the debuggee has terminated. This does **not** mean that the debuggee itself has exited.", + "properties": { + "event": { + "type": "string", + "enum": [ "terminated" ] + }, + "body": { + "type": "object", + "properties": { + "restart": { + "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], + "description": "A debug adapter may set 'restart' to true (or to an arbitrary object) to request that the front end restarts the session.\nThe value is not interpreted by the client and passed unmodified as an attribute '__restart' to the 'launch' and 'attach' requests." + } + } + } + }, + "required": [ "event" ] + }] + }, + + "ThreadEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event indicates that a thread has started or exited.", + "properties": { + "event": { + "type": "string", + "enum": [ "thread" ] + }, + "body": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "description": "The reason for the event.", + "_enum": [ "started", "exited" ] + }, + "threadId": { + "type": "integer", + "description": "The identifier of the thread." + } + }, + "required": ["reason", "threadId"] + } + }, + "required": [ "event", "body" ] + }] + }, + + "OutputEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event indicates that the target has produced some output.", + "properties": { + "event": { + "type": "string", + "enum": [ "output" ] + }, + "body": { + "type": "object", + "properties": { + "category": { + "type": "string", + "description": "The output category. If not specified, 'console' is assumed.", + "_enum": [ "console", "stdout", "stderr", "telemetry" ] + }, + "output": { + "type": "string", + "description": "The output to report." + }, + "group": { + "type": "string", + "description": "Support for keeping an output log organized by grouping related messages.", + "enum": [ "start", "startCollapsed", "end" ], + "enumDescriptions": [ + "Start a new group in expanded mode. Subsequent output events are members of the group and should be shown indented.\nThe 'output' attribute becomes the name of the group and is not indented.", + "Start a new group in collapsed mode. Subsequent output events are members of the group and should be shown indented (as soon as the group is expanded).\nThe 'output' attribute becomes the name of the group and is not indented.", + "End the current group and decreases the indentation of subsequent output events.\nA non empty 'output' attribute is shown as the unindented end of the group." + ] + }, + "variablesReference": { + "type": "integer", + "description": "If an attribute 'variablesReference' exists and its value is > 0, the output contains objects which can be retrieved by passing 'variablesReference' to the 'variables' request. The value should be less than or equal to 2147483647 (2^31-1)." + }, + "source": { + "$ref": "#/definitions/Source", + "description": "An optional source location where the output was produced." + }, + "line": { + "type": "integer", + "description": "An optional source location line where the output was produced." + }, + "column": { + "type": "integer", + "description": "An optional source location column where the output was produced." + }, + "data": { + "type": [ "array", "boolean", "integer", "null", "number" , "object", "string" ], + "description": "Optional data to report. For the 'telemetry' category the data will be sent to telemetry, for the other categories the data is shown in JSON format." + } + }, + "required": ["output"] + } + }, + "required": [ "event", "body" ] + }] + }, + + "BreakpointEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event indicates that some information about a breakpoint has changed.", + "properties": { + "event": { + "type": "string", + "enum": [ "breakpoint" ] + }, + "body": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "description": "The reason for the event.", + "_enum": [ "changed", "new", "removed" ] + }, + "breakpoint": { + "$ref": "#/definitions/Breakpoint", + "description": "The 'id' attribute is used to find the target breakpoint and the other attributes are used as the new values." + } + }, + "required": [ "reason", "breakpoint" ] + } + }, + "required": [ "event", "body" ] + }] + }, + + "ModuleEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event indicates that some information about a module has changed.", + "properties": { + "event": { + "type": "string", + "enum": [ "module" ] + }, + "body": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "description": "The reason for the event.", + "enum": [ "new", "changed", "removed" ] + }, + "module": { + "$ref": "#/definitions/Module", + "description": "The new, changed, or removed module. In case of 'removed' only the module id is used." + } + }, + "required": [ "reason", "module" ] + } + }, + "required": [ "event", "body" ] + }] + }, + + "LoadedSourceEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event indicates that some source has been added, changed, or removed from the set of all loaded sources.", + "properties": { + "event": { + "type": "string", + "enum": [ "loadedSource" ] + }, + "body": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "description": "The reason for the event.", + "enum": [ "new", "changed", "removed" ] + }, + "source": { + "$ref": "#/definitions/Source", + "description": "The new, changed, or removed source." + } + }, + "required": [ "reason", "source" ] + } + }, + "required": [ "event", "body" ] + }] + }, + + "ProcessEvent": { + "allOf": [ + { "$ref": "#/definitions/Event" }, + { + "type": "object", + "description": "The event indicates that the debugger has begun debugging a new process. Either one that it has launched, or one that it has attached to.", + "properties": { + "event": { + "type": "string", + "enum": [ "process" ] + }, + "body": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The logical name of the process. This is usually the full path to process's executable file. Example: /home/example/myproj/program.js." + }, + "systemProcessId": { + "type": "integer", + "description": "The system process id of the debugged process. This property will be missing for non-system processes." + }, + "isLocalProcess": { + "type": "boolean", + "description": "If true, the process is running on the same computer as the debug adapter." + }, + "startMethod": { + "type": "string", + "enum": [ "launch", "attach", "attachForSuspendedLaunch" ], + "description": "Describes how the debug engine started debugging this process.", + "enumDescriptions": [ + "Process was launched under the debugger.", + "Debugger attached to an existing process.", + "A project launcher component has launched a new process in a suspended state and then asked the debugger to attach." + ] + }, + "pointerSize": { + "type": "integer", + "description": "The size of a pointer or address for this process, in bits. This value may be used by clients when formatting addresses for display." + } + }, + "required": [ "name" ] + } + }, + "required": [ "event", "body" ] + } + ] + }, + + "CapabilitiesEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event indicates that one or more capabilities have changed.\nSince the capabilities are dependent on the frontend and its UI, it might not be possible to change that at random times (or too late).\nConsequently this event has a hint characteristic: a frontend can only be expected to make a 'best effort' in honouring individual capabilities but there are no guarantees.\nOnly changed capabilities need to be included, all other capabilities keep their values.", + "properties": { + "event": { + "type": "string", + "enum": [ "capabilities" ] + }, + "body": { + "type": "object", + "properties": { + "capabilities": { + "$ref": "#/definitions/Capabilities", + "description": "The set of updated capabilities." + } + }, + "required": [ "capabilities" ] + } + }, + "required": [ "event", "body" ] + }] + }, + + "ProgressStartEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event signals that a long running operation is about to start and\nprovides additional information for the client to set up a corresponding progress and cancellation UI.\nThe client is free to delay the showing of the UI in order to reduce flicker.\nThis event should only be sent if the client has passed the value true for the 'supportsProgressReporting' capability of the 'initialize' request.", + "properties": { + "event": { + "type": "string", + "enum": [ "progressStart" ] + }, + "body": { + "type": "object", + "properties": { + "progressId": { + "type": "string", + "description": "An ID that must be used in subsequent 'progressUpdate' and 'progressEnd' events to make them refer to the same progress reporting.\nIDs must be unique within a debug session." + }, + "title": { + "type": "string", + "description": "Mandatory (short) title of the progress reporting. Shown in the UI to describe the long running operation." + }, + "requestId": { + "type": "integer", + "description": "The request ID that this progress report is related to. If specified a debug adapter is expected to emit\nprogress events for the long running request until the request has been either completed or cancelled.\nIf the request ID is omitted, the progress report is assumed to be related to some general activity of the debug adapter." + }, + "cancellable": { + "type": "boolean", + "description": "If true, the request that reports progress may be canceled with a 'cancel' request.\nSo this property basically controls whether the client should use UX that supports cancellation.\nClients that don't support cancellation are allowed to ignore the setting." + }, + "message": { + "type": "string", + "description": "Optional, more detailed progress message." + }, + "percentage": { + "type": "number", + "description": "Optional progress percentage to display (value range: 0 to 100). If omitted no percentage will be shown." + } + }, + "required": [ "progressId", "title" ] + } + }, + "required": [ "event", "body" ] + }] + }, + + "ProgressUpdateEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event signals that the progress reporting needs to updated with a new message and/or percentage.\nThe client does not have to update the UI immediately, but the clients needs to keep track of the message and/or percentage values.\nThis event should only be sent if the client has passed the value true for the 'supportsProgressReporting' capability of the 'initialize' request.", + "properties": { + "event": { + "type": "string", + "enum": [ "progressUpdate" ] + }, + "body": { + "type": "object", + "properties": { + "progressId": { + "type": "string", + "description": "The ID that was introduced in the initial 'progressStart' event." + }, + "message": { + "type": "string", + "description": "Optional, more detailed progress message. If omitted, the previous message (if any) is used." + }, + "percentage": { + "type": "number", + "description": "Optional progress percentage to display (value range: 0 to 100). If omitted no percentage will be shown." + } + }, + "required": [ "progressId" ] + } + }, + "required": [ "event", "body" ] + }] + }, + + "ProgressEndEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event signals the end of the progress reporting with an optional final message.\nThis event should only be sent if the client has passed the value true for the 'supportsProgressReporting' capability of the 'initialize' request.", + "properties": { + "event": { + "type": "string", + "enum": [ "progressEnd" ] + }, + "body": { + "type": "object", + "properties": { + "progressId": { + "type": "string", + "description": "The ID that was introduced in the initial 'ProgressStartEvent'." + }, + "message": { + "type": "string", + "description": "Optional, more detailed progress message. If omitted, the previous message (if any) is used." + } + }, + "required": [ "progressId" ] + } + }, + "required": [ "event", "body" ] + }] + }, + + "InvalidatedEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "This event signals that some state in the debug adapter has changed and requires that the client needs to re-render the data snapshot previously requested.\nDebug adapters do not have to emit this event for runtime changes like stopped or thread events because in that case the client refetches the new state anyway. But the event can be used for example to refresh the UI after rendering formatting has changed in the debug adapter.\nThis event should only be sent if the debug adapter has received a value true for the 'supportsInvalidatedEvent' capability of the 'initialize' request.", + "properties": { + "event": { + "type": "string", + "enum": [ "invalidated" ] + }, + "body": { + "type": "object", + "properties": { + "areas": { + "type": "array", + "description": "Optional set of logical areas that got invalidated. This property has a hint characteristic: a client can only be expected to make a 'best effort' in honouring the areas but there are no guarantees. If this property is missing, empty, or if values are not understand the client should assume a single value 'all'.", + "items": { + "$ref": "#/definitions/InvalidatedAreas" + } + }, + "threadId": { + "type": "integer", + "description": "If specified, the client only needs to refetch data related to this thread." + }, + "stackFrameId": { + "type": "integer", + "description": "If specified, the client only needs to refetch data related to this stack frame (and the 'threadId' is ignored)." + } + } + } + }, + "required": [ "event", "body" ] + }] + }, + + "RunInTerminalRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "title": "Reverse Requests", + "description": "This optional request is sent from the debug adapter to the client to run a command in a terminal.\nThis is typically used to launch the debuggee in a terminal provided by the client.\nThis request should only be called if the client has passed the value true for the 'supportsRunInTerminalRequest' capability of the 'initialize' request.", + "properties": { + "command": { + "type": "string", + "enum": [ "runInTerminal" ] + }, + "arguments": { + "$ref": "#/definitions/RunInTerminalRequestArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "RunInTerminalRequestArguments": { + "type": "object", + "description": "Arguments for 'runInTerminal' request.", + "properties": { + "kind": { + "type": "string", + "enum": [ "integrated", "external" ], + "description": "What kind of terminal to launch." + }, + "title": { + "type": "string", + "description": "Optional title of the terminal." + }, + "cwd": { + "type": "string", + "description": "Working directory for the command. For non-empty, valid paths this typically results in execution of a change directory command." + }, + "args": { + "type": "array", + "items": { + "type": "string" + }, + "description": "List of arguments. The first argument is the command to run." + }, + "env": { + "type": "object", + "description": "Environment key-value pairs that are added to or removed from the default environment.", + "additionalProperties": { + "type": [ "string", "null" ], + "description": "Proper values must be strings. A value of 'null' removes the variable from the environment." + } + } + }, + "required": [ "args", "cwd" ] + }, + "RunInTerminalResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'runInTerminal' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "processId": { + "type": "integer", + "description": "The process ID. The value should be less than or equal to 2147483647 (2^31-1)." + }, + "shellProcessId": { + "type": "integer", + "description": "The process ID of the terminal shell. The value should be less than or equal to 2147483647 (2^31-1)." + } + } + } + }, + "required": [ "body" ] + }] + }, + + "InitializeRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "title": "Requests", + "description": "The 'initialize' request is sent as the first request from the client to the debug adapter\nin order to configure it with client capabilities and to retrieve capabilities from the debug adapter.\nUntil the debug adapter has responded to with an 'initialize' response, the client must not send any additional requests or events to the debug adapter.\nIn addition the debug adapter is not allowed to send any requests or events to the client until it has responded with an 'initialize' response.\nThe 'initialize' request may only be sent once.", + "properties": { + "command": { + "type": "string", + "enum": [ "initialize" ] + }, + "arguments": { + "$ref": "#/definitions/InitializeRequestArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "InitializeRequestArguments": { + "type": "object", + "description": "Arguments for 'initialize' request.", + "properties": { + "clientID": { + "type": "string", + "description": "The ID of the (frontend) client using this adapter." + }, + "clientName": { + "type": "string", + "description": "The human readable name of the (frontend) client using this adapter." + }, + "adapterID": { + "type": "string", + "description": "The ID of the debug adapter." + }, + "locale": { + "type": "string", + "description": "The ISO-639 locale of the (frontend) client using this adapter, e.g. en-US or de-CH." + }, + "linesStartAt1": { + "type": "boolean", + "description": "If true all line numbers are 1-based (default)." + }, + "columnsStartAt1": { + "type": "boolean", + "description": "If true all column numbers are 1-based (default)." + }, + "pathFormat": { + "type": "string", + "_enum": [ "path", "uri" ], + "description": "Determines in what format paths are specified. The default is 'path', which is the native format." + }, + "supportsVariableType": { + "type": "boolean", + "description": "Client supports the optional type attribute for variables." + }, + "supportsVariablePaging": { + "type": "boolean", + "description": "Client supports the paging of variables." + }, + "supportsRunInTerminalRequest": { + "type": "boolean", + "description": "Client supports the runInTerminal request." + }, + "supportsMemoryReferences": { + "type": "boolean", + "description": "Client supports memory references." + }, + "supportsProgressReporting": { + "type": "boolean", + "description": "Client supports progress reporting." + }, + "supportsInvalidatedEvent": { + "type": "boolean", + "description": "Client supports the invalidated event." + } + }, + "required": [ "adapterID" ] + }, + "InitializeResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'initialize' request.", + "properties": { + "body": { + "$ref": "#/definitions/Capabilities", + "description": "The capabilities of this debug adapter." + } + } + }] + }, + + "ConfigurationDoneRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "This optional request indicates that the client has finished initialization of the debug adapter.\nSo it is the last request in the sequence of configuration requests (which was started by the 'initialized' event).\nClients should only call this request if the capability 'supportsConfigurationDoneRequest' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "configurationDone" ] + }, + "arguments": { + "$ref": "#/definitions/ConfigurationDoneArguments" + } + }, + "required": [ "command" ] + }] + }, + "ConfigurationDoneArguments": { + "type": "object", + "description": "Arguments for 'configurationDone' request." + }, + "ConfigurationDoneResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'configurationDone' request. This is just an acknowledgement, so no body field is required." + }] + }, + + "LaunchRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "This launch request is sent from the client to the debug adapter to start the debuggee with or without debugging (if 'noDebug' is true).\nSince launching is debugger/runtime specific, the arguments for this request are not part of this specification.", + "properties": { + "command": { + "type": "string", + "enum": [ "launch" ] + }, + "arguments": { + "$ref": "#/definitions/LaunchRequestArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "LaunchRequestArguments": { + "type": "object", + "description": "Arguments for 'launch' request. Additional attributes are implementation specific.", + "properties": { + "noDebug": { + "type": "boolean", + "description": "If noDebug is true the launch request should launch the program without enabling debugging." + }, + "__restart": { + "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], + "description": "Optional data from the previous, restarted session.\nThe data is sent as the 'restart' attribute of the 'terminated' event.\nThe client should leave the data intact." + } + } + }, + "LaunchResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'launch' request. This is just an acknowledgement, so no body field is required." + }] + }, + + "AttachRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The attach request is sent from the client to the debug adapter to attach to a debuggee that is already running.\nSince attaching is debugger/runtime specific, the arguments for this request are not part of this specification.", + "properties": { + "command": { + "type": "string", + "enum": [ "attach" ] + }, + "arguments": { + "$ref": "#/definitions/AttachRequestArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "AttachRequestArguments": { + "type": "object", + "description": "Arguments for 'attach' request. Additional attributes are implementation specific.", + "properties": { + "__restart": { + "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], + "description": "Optional data from the previous, restarted session.\nThe data is sent as the 'restart' attribute of the 'terminated' event.\nThe client should leave the data intact." + } + } + }, + "AttachResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'attach' request. This is just an acknowledgement, so no body field is required." + }] + }, + + "RestartRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "Restarts a debug session. Clients should only call this request if the capability 'supportsRestartRequest' is true.\nIf the capability is missing or has the value false, a typical client will emulate 'restart' by terminating the debug adapter first and then launching it anew.", + "properties": { + "command": { + "type": "string", + "enum": [ "restart" ] + }, + "arguments": { + "$ref": "#/definitions/RestartArguments" + } + }, + "required": [ "command" ] + }] + }, + "RestartArguments": { + "type": "object", + "description": "Arguments for 'restart' request." + }, + "RestartResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'restart' request. This is just an acknowledgement, so no body field is required." + }] + }, + + "DisconnectRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The 'disconnect' request is sent from the client to the debug adapter in order to stop debugging.\nIt asks the debug adapter to disconnect from the debuggee and to terminate the debug adapter.\nIf the debuggee has been started with the 'launch' request, the 'disconnect' request terminates the debuggee.\nIf the 'attach' request was used to connect to the debuggee, 'disconnect' does not terminate the debuggee.\nThis behavior can be controlled with the 'terminateDebuggee' argument (if supported by the debug adapter).", + "properties": { + "command": { + "type": "string", + "enum": [ "disconnect" ] + }, + "arguments": { + "$ref": "#/definitions/DisconnectArguments" + } + }, + "required": [ "command" ] + }] + }, + "DisconnectArguments": { + "type": "object", + "description": "Arguments for 'disconnect' request.", + "properties": { + "restart": { + "type": "boolean", + "description": "A value of true indicates that this 'disconnect' request is part of a restart sequence." + }, + "terminateDebuggee": { + "type": "boolean", + "description": "Indicates whether the debuggee should be terminated when the debugger is disconnected.\nIf unspecified, the debug adapter is free to do whatever it thinks is best.\nThe attribute is only honored by a debug adapter if the capability 'supportTerminateDebuggee' is true." + } + } + }, + "DisconnectResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'disconnect' request. This is just an acknowledgement, so no body field is required." + }] + }, + + "TerminateRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The 'terminate' request is sent from the client to the debug adapter in order to give the debuggee a chance for terminating itself.\nClients should only call this request if the capability 'supportsTerminateRequest' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "terminate" ] + }, + "arguments": { + "$ref": "#/definitions/TerminateArguments" + } + }, + "required": [ "command" ] + }] + }, + "TerminateArguments": { + "type": "object", + "description": "Arguments for 'terminate' request.", + "properties": { + "restart": { + "type": "boolean", + "description": "A value of true indicates that this 'terminate' request is part of a restart sequence." + } + } + }, + "TerminateResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'terminate' request. This is just an acknowledgement, so no body field is required." + }] + }, + + "BreakpointLocationsRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The 'breakpointLocations' request returns all possible locations for source breakpoints in a given range.\nClients should only call this request if the capability 'supportsBreakpointLocationsRequest' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "breakpointLocations" ] + }, + "arguments": { + "$ref": "#/definitions/BreakpointLocationsArguments" + } + }, + "required": [ "command" ] + }] + + }, + "BreakpointLocationsArguments": { + "type": "object", + "description": "Arguments for 'breakpointLocations' request.", + "properties": { + "source": { + "$ref": "#/definitions/Source", + "description": "The source location of the breakpoints; either 'source.path' or 'source.reference' must be specified." + }, + "line": { + "type": "integer", + "description": "Start line of range to search possible breakpoint locations in. If only the line is specified, the request returns all possible locations in that line." + }, + "column": { + "type": "integer", + "description": "Optional start column of range to search possible breakpoint locations in. If no start column is given, the first column in the start line is assumed." + }, + "endLine": { + "type": "integer", + "description": "Optional end line of range to search possible breakpoint locations in. If no end line is given, then the end line is assumed to be the start line." + }, + "endColumn": { + "type": "integer", + "description": "Optional end column of range to search possible breakpoint locations in. If no end column is given, then it is assumed to be in the last column of the end line." + } + }, + "required": [ "source", "line" ] + }, + "BreakpointLocationsResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'breakpointLocations' request.\nContains possible locations for source breakpoints.", + "properties": { + "body": { + "type": "object", + "properties": { + "breakpoints": { + "type": "array", + "items": { + "$ref": "#/definitions/BreakpointLocation" + }, + "description": "Sorted set of possible breakpoint locations." + } + }, + "required": [ "breakpoints" ] + } + }, + "required": [ "body" ] + }] + }, + + "SetBreakpointsRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "Sets multiple breakpoints for a single source and clears all previous breakpoints in that source.\nTo clear all breakpoint for a source, specify an empty array.\nWhen a breakpoint is hit, a 'stopped' event (with reason 'breakpoint') is generated.", + "properties": { + "command": { + "type": "string", + "enum": [ "setBreakpoints" ] + }, + "arguments": { + "$ref": "#/definitions/SetBreakpointsArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "SetBreakpointsArguments": { + "type": "object", + "description": "Arguments for 'setBreakpoints' request.", + "properties": { + "source": { + "$ref": "#/definitions/Source", + "description": "The source location of the breakpoints; either 'source.path' or 'source.reference' must be specified." + }, + "breakpoints": { + "type": "array", + "items": { + "$ref": "#/definitions/SourceBreakpoint" + }, + "description": "The code locations of the breakpoints." + }, + "lines": { + "type": "array", + "items": { + "type": "integer" + }, + "description": "Deprecated: The code locations of the breakpoints." + }, + "sourceModified": { + "type": "boolean", + "description": "A value of true indicates that the underlying source has been modified which results in new breakpoint locations." + } + }, + "required": [ "source" ] + }, + "SetBreakpointsResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'setBreakpoints' request.\nReturned is information about each breakpoint created by this request.\nThis includes the actual code location and whether the breakpoint could be verified.\nThe breakpoints returned are in the same order as the elements of the 'breakpoints'\n(or the deprecated 'lines') array in the arguments.", + "properties": { + "body": { + "type": "object", + "properties": { + "breakpoints": { + "type": "array", + "items": { + "$ref": "#/definitions/Breakpoint" + }, + "description": "Information about the breakpoints.\nThe array elements are in the same order as the elements of the 'breakpoints' (or the deprecated 'lines') array in the arguments." + } + }, + "required": [ "breakpoints" ] + } + }, + "required": [ "body" ] + }] + }, + + "SetFunctionBreakpointsRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "Replaces all existing function breakpoints with new function breakpoints.\nTo clear all function breakpoints, specify an empty array.\nWhen a function breakpoint is hit, a 'stopped' event (with reason 'function breakpoint') is generated.\nClients should only call this request if the capability 'supportsFunctionBreakpoints' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "setFunctionBreakpoints" ] + }, + "arguments": { + "$ref": "#/definitions/SetFunctionBreakpointsArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "SetFunctionBreakpointsArguments": { + "type": "object", + "description": "Arguments for 'setFunctionBreakpoints' request.", + "properties": { + "breakpoints": { + "type": "array", + "items": { + "$ref": "#/definitions/FunctionBreakpoint" + }, + "description": "The function names of the breakpoints." + } + }, + "required": [ "breakpoints" ] + }, + "SetFunctionBreakpointsResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'setFunctionBreakpoints' request.\nReturned is information about each breakpoint created by this request.", + "properties": { + "body": { + "type": "object", + "properties": { + "breakpoints": { + "type": "array", + "items": { + "$ref": "#/definitions/Breakpoint" + }, + "description": "Information about the breakpoints. The array elements correspond to the elements of the 'breakpoints' array." + } + }, + "required": [ "breakpoints" ] + } + }, + "required": [ "body" ] + }] + }, + + "SetExceptionBreakpointsRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The request configures the debuggers response to thrown exceptions.\nIf an exception is configured to break, a 'stopped' event is fired (with reason 'exception').\nClients should only call this request if the capability 'exceptionBreakpointFilters' returns one or more filters.", + "properties": { + "command": { + "type": "string", + "enum": [ "setExceptionBreakpoints" ] + }, + "arguments": { + "$ref": "#/definitions/SetExceptionBreakpointsArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "SetExceptionBreakpointsArguments": { + "type": "object", + "description": "Arguments for 'setExceptionBreakpoints' request.", + "properties": { + "filters": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Set of exception filters specified by their ID. The set of all possible exception filters is defined by the 'exceptionBreakpointFilters' capability. The 'filter' and 'filterOptions' sets are additive." + }, + "filterOptions": { + "type": "array", + "items": { + "$ref": "#/definitions/ExceptionFilterOptions" + }, + "description": "Set of exception filters and their options. The set of all possible exception filters is defined by the 'exceptionBreakpointFilters' capability. This attribute is only honored by a debug adapter if the capability 'supportsExceptionFilterOptions' is true. The 'filter' and 'filterOptions' sets are additive." + }, + "exceptionOptions": { + "type": "array", + "items": { + "$ref": "#/definitions/ExceptionOptions" + }, + "description": "Configuration options for selected exceptions.\nThe attribute is only honored by a debug adapter if the capability 'supportsExceptionOptions' is true." + } + }, + "required": [ "filters" ] + }, + "SetExceptionBreakpointsResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'setExceptionBreakpoints' request. This is just an acknowledgement, so no body field is required." + }] + }, + + "DataBreakpointInfoRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "Obtains information on a possible data breakpoint that could be set on an expression or variable.\nClients should only call this request if the capability 'supportsDataBreakpoints' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "dataBreakpointInfo" ] + }, + "arguments": { + "$ref": "#/definitions/DataBreakpointInfoArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "DataBreakpointInfoArguments": { + "type": "object", + "description": "Arguments for 'dataBreakpointInfo' request.", + "properties": { + "variablesReference": { + "type": "integer", + "description": "Reference to the Variable container if the data breakpoint is requested for a child of the container." + }, + "name": { + "type": "string", + "description": "The name of the Variable's child to obtain data breakpoint information for.\nIf variablesReference isn’t provided, this can be an expression." + } + }, + "required": [ "name" ] + }, + "DataBreakpointInfoResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'dataBreakpointInfo' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "dataId": { + "type": [ "string", "null" ], + "description": "An identifier for the data on which a data breakpoint can be registered with the setDataBreakpoints request or null if no data breakpoint is available." + }, + "description": { + "type": "string", + "description": "UI string that describes on what data the breakpoint is set on or why a data breakpoint is not available." + }, + "accessTypes": { + "type": "array", + "items": { + "$ref": "#/definitions/DataBreakpointAccessType" + }, + "description": "Optional attribute listing the available access types for a potential data breakpoint. A UI frontend could surface this information." + }, + "canPersist": { + "type": "boolean", + "description": "Optional attribute indicating that a potential data breakpoint could be persisted across sessions." + } + }, + "required": [ "dataId", "description" ] + } + }, + "required": [ "body" ] + }] + }, + + "SetDataBreakpointsRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "Replaces all existing data breakpoints with new data breakpoints.\nTo clear all data breakpoints, specify an empty array.\nWhen a data breakpoint is hit, a 'stopped' event (with reason 'data breakpoint') is generated.\nClients should only call this request if the capability 'supportsDataBreakpoints' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "setDataBreakpoints" ] + }, + "arguments": { + "$ref": "#/definitions/SetDataBreakpointsArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "SetDataBreakpointsArguments": { + "type": "object", + "description": "Arguments for 'setDataBreakpoints' request.", + "properties": { + "breakpoints": { + "type": "array", + "items": { + "$ref": "#/definitions/DataBreakpoint" + }, + "description": "The contents of this array replaces all existing data breakpoints. An empty array clears all data breakpoints." + } + }, + "required": [ "breakpoints" ] + }, + "SetDataBreakpointsResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'setDataBreakpoints' request.\nReturned is information about each breakpoint created by this request.", + "properties": { + "body": { + "type": "object", + "properties": { + "breakpoints": { + "type": "array", + "items": { + "$ref": "#/definitions/Breakpoint" + }, + "description": "Information about the data breakpoints. The array elements correspond to the elements of the input argument 'breakpoints' array." + } + }, + "required": [ "breakpoints" ] + } + }, + "required": [ "body" ] + }] + }, + + "SetInstructionBreakpointsRequest": { + "allOf": [ + { "$ref": "#/definitions/Request" }, + { + "type": "object", + "description": "Replaces all existing instruction breakpoints. Typically, instruction breakpoints would be set from a diassembly window. \nTo clear all instruction breakpoints, specify an empty array.\nWhen an instruction breakpoint is hit, a 'stopped' event (with reason 'instruction breakpoint') is generated.\nClients should only call this request if the capability 'supportsInstructionBreakpoints' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "setInstructionBreakpoints" ] + }, + "arguments": { + "$ref": "#/definitions/SetInstructionBreakpointsArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "SetInstructionBreakpointsArguments": { + "type": "object", + "description": "Arguments for 'setInstructionBreakpoints' request", + "properties": { + "breakpoints": { + "type": "array", + "items": { + "$ref": "#/definitions/InstructionBreakpoint" + }, + "description": "The instruction references of the breakpoints" + } + }, + "required": ["breakpoints"] + }, + "SetInstructionBreakpointsResponse": { + "allOf": [ + { "$ref": "#/definitions/Response" }, + { + "type": "object", + "description": "Response to 'setInstructionBreakpoints' request", + "properties": { + "body": { + "type": "object", + "properties": { + "breakpoints": { + "type": "array", + "items": { + "$ref": "#/definitions/Breakpoint" + }, + "description": "Information about the breakpoints. The array elements correspond to the elements of the 'breakpoints' array." + } + }, + "required": [ "breakpoints" ] + } + }, + "required": [ "body" ] + }] + }, + + "ContinueRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The request starts the debuggee to run again.", + "properties": { + "command": { + "type": "string", + "enum": [ "continue" ] + }, + "arguments": { + "$ref": "#/definitions/ContinueArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "ContinueArguments": { + "type": "object", + "description": "Arguments for 'continue' request.", + "properties": { + "threadId": { + "type": "integer", + "description": "Continue execution for the specified thread (if possible).\nIf the backend cannot continue on a single thread but will continue on all threads, it should set the 'allThreadsContinued' attribute in the response to true." + } + }, + "required": [ "threadId" ] + }, + "ContinueResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'continue' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "allThreadsContinued": { + "type": "boolean", + "description": "If true, the 'continue' request has ignored the specified thread and continued all threads instead.\nIf this attribute is missing a value of 'true' is assumed for backward compatibility." + } + } + } + }, + "required": [ "body" ] + }] + }, + + "NextRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The request starts the debuggee to run again for one step.\nThe debug adapter first sends the response and then a 'stopped' event (with reason 'step') after the step has completed.", + "properties": { + "command": { + "type": "string", + "enum": [ "next" ] + }, + "arguments": { + "$ref": "#/definitions/NextArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "NextArguments": { + "type": "object", + "description": "Arguments for 'next' request.", + "properties": { + "threadId": { + "type": "integer", + "description": "Execute 'next' for this thread." + }, + "granularity": { + "$ref": "#/definitions/SteppingGranularity", + "description": "Optional granularity to step. If no granularity is specified, a granularity of 'statement' is assumed." + } + }, + "required": [ "threadId" ] + }, + "NextResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'next' request. This is just an acknowledgement, so no body field is required." + }] + }, + + "StepInRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The request starts the debuggee to step into a function/method if possible.\nIf it cannot step into a target, 'stepIn' behaves like 'next'.\nThe debug adapter first sends the response and then a 'stopped' event (with reason 'step') after the step has completed.\nIf there are multiple function/method calls (or other targets) on the source line,\nthe optional argument 'targetId' can be used to control into which target the 'stepIn' should occur.\nThe list of possible targets for a given source line can be retrieved via the 'stepInTargets' request.", + "properties": { + "command": { + "type": "string", + "enum": [ "stepIn" ] + }, + "arguments": { + "$ref": "#/definitions/StepInArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "StepInArguments": { + "type": "object", + "description": "Arguments for 'stepIn' request.", + "properties": { + "threadId": { + "type": "integer", + "description": "Execute 'stepIn' for this thread." + }, + "targetId": { + "type": "integer", + "description": "Optional id of the target to step into." + }, + "granularity": { + "$ref": "#/definitions/SteppingGranularity", + "description": "Optional granularity to step. If no granularity is specified, a granularity of 'statement' is assumed." + } + }, + "required": [ "threadId" ] + }, + "StepInResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'stepIn' request. This is just an acknowledgement, so no body field is required." + }] + }, + + "StepOutRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The request starts the debuggee to run again for one step.\nThe debug adapter first sends the response and then a 'stopped' event (with reason 'step') after the step has completed.", + "properties": { + "command": { + "type": "string", + "enum": [ "stepOut" ] + }, + "arguments": { + "$ref": "#/definitions/StepOutArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "StepOutArguments": { + "type": "object", + "description": "Arguments for 'stepOut' request.", + "properties": { + "threadId": { + "type": "integer", + "description": "Execute 'stepOut' for this thread." + }, + "granularity": { + "$ref": "#/definitions/SteppingGranularity", + "description": "Optional granularity to step. If no granularity is specified, a granularity of 'statement' is assumed." + } + }, + "required": [ "threadId" ] + }, + "StepOutResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'stepOut' request. This is just an acknowledgement, so no body field is required." + }] + }, + + "StepBackRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The request starts the debuggee to run one step backwards.\nThe debug adapter first sends the response and then a 'stopped' event (with reason 'step') after the step has completed.\nClients should only call this request if the capability 'supportsStepBack' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "stepBack" ] + }, + "arguments": { + "$ref": "#/definitions/StepBackArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "StepBackArguments": { + "type": "object", + "description": "Arguments for 'stepBack' request.", + "properties": { + "threadId": { + "type": "integer", + "description": "Execute 'stepBack' for this thread." + }, + "granularity": { + "$ref": "#/definitions/SteppingGranularity", + "description": "Optional granularity to step. If no granularity is specified, a granularity of 'statement' is assumed." + } + }, + "required": [ "threadId" ] + }, + "StepBackResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'stepBack' request. This is just an acknowledgement, so no body field is required." + }] + }, + + "ReverseContinueRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The request starts the debuggee to run backward.\nClients should only call this request if the capability 'supportsStepBack' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "reverseContinue" ] + }, + "arguments": { + "$ref": "#/definitions/ReverseContinueArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "ReverseContinueArguments": { + "type": "object", + "description": "Arguments for 'reverseContinue' request.", + "properties": { + "threadId": { + "type": "integer", + "description": "Execute 'reverseContinue' for this thread." + } + }, + "required": [ "threadId" ] + }, + "ReverseContinueResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'reverseContinue' request. This is just an acknowledgement, so no body field is required." + }] + }, + + "RestartFrameRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The request restarts execution of the specified stackframe.\nThe debug adapter first sends the response and then a 'stopped' event (with reason 'restart') after the restart has completed.\nClients should only call this request if the capability 'supportsRestartFrame' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "restartFrame" ] + }, + "arguments": { + "$ref": "#/definitions/RestartFrameArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "RestartFrameArguments": { + "type": "object", + "description": "Arguments for 'restartFrame' request.", + "properties": { + "frameId": { + "type": "integer", + "description": "Restart this stackframe." + } + }, + "required": [ "frameId" ] + }, + "RestartFrameResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'restartFrame' request. This is just an acknowledgement, so no body field is required." + }] + }, + + "GotoRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The request sets the location where the debuggee will continue to run.\nThis makes it possible to skip the execution of code or to executed code again.\nThe code between the current location and the goto target is not executed but skipped.\nThe debug adapter first sends the response and then a 'stopped' event with reason 'goto'.\nClients should only call this request if the capability 'supportsGotoTargetsRequest' is true (because only then goto targets exist that can be passed as arguments).", + "properties": { + "command": { + "type": "string", + "enum": [ "goto" ] + }, + "arguments": { + "$ref": "#/definitions/GotoArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "GotoArguments": { + "type": "object", + "description": "Arguments for 'goto' request.", + "properties": { + "threadId": { + "type": "integer", + "description": "Set the goto target for this thread." + }, + "targetId": { + "type": "integer", + "description": "The location where the debuggee will continue to run." + } + }, + "required": [ "threadId", "targetId" ] + }, + "GotoResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'goto' request. This is just an acknowledgement, so no body field is required." + }] + }, + + "PauseRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The request suspends the debuggee.\nThe debug adapter first sends the response and then a 'stopped' event (with reason 'pause') after the thread has been paused successfully.", + "properties": { + "command": { + "type": "string", + "enum": [ "pause" ] + }, + "arguments": { + "$ref": "#/definitions/PauseArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "PauseArguments": { + "type": "object", + "description": "Arguments for 'pause' request.", + "properties": { + "threadId": { + "type": "integer", + "description": "Pause execution for this thread." + } + }, + "required": [ "threadId" ] + }, + "PauseResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'pause' request. This is just an acknowledgement, so no body field is required." + }] + }, + + "StackTraceRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The request returns a stacktrace from the current execution state of a given thread.\nA client can request all stack frames by omitting the startFrame and levels arguments. For performance conscious clients and if the debug adapter's 'supportsDelayedStackTraceLoading' capability is true, stack frames can be retrieved in a piecemeal way with the startFrame and levels arguments. The response of the stackTrace request may contain a totalFrames property that hints at the total number of frames in the stack. If a client needs this total number upfront, it can issue a request for a single (first) frame and depending on the value of totalFrames decide how to proceed. In any case a client should be prepared to receive less frames than requested, which is an indication that the end of the stack has been reached.", + "properties": { + "command": { + "type": "string", + "enum": [ "stackTrace" ] + }, + "arguments": { + "$ref": "#/definitions/StackTraceArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "StackTraceArguments": { + "type": "object", + "description": "Arguments for 'stackTrace' request.", + "properties": { + "threadId": { + "type": "integer", + "description": "Retrieve the stacktrace for this thread." + }, + "startFrame": { + "type": "integer", + "description": "The index of the first frame to return; if omitted frames start at 0." + }, + "levels": { + "type": "integer", + "description": "The maximum number of frames to return. If levels is not specified or 0, all frames are returned." + }, + "format": { + "$ref": "#/definitions/StackFrameFormat", + "description": "Specifies details on how to format the stack frames.\nThe attribute is only honored by a debug adapter if the capability 'supportsValueFormattingOptions' is true." + } + }, + "required": [ "threadId" ] + }, + "StackTraceResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'stackTrace' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "stackFrames": { + "type": "array", + "items": { + "$ref": "#/definitions/StackFrame" + }, + "description": "The frames of the stackframe. If the array has length zero, there are no stackframes available.\nThis means that there is no location information available." + }, + "totalFrames": { + "type": "integer", + "description": "The total number of frames available in the stack. If omitted or if totalFrames is larger than the available frames, a client is expected to request frames until a request returns less frames than requested (which indicates the end of the stack). Returning monotonically increasing totalFrames values for subsequent requests can be used to enforce paging in the client." + } + }, + "required": [ "stackFrames" ] + } + }, + "required": [ "body" ] + }] + }, + + "ScopesRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The request returns the variable scopes for a given stackframe ID.", + "properties": { + "command": { + "type": "string", + "enum": [ "scopes" ] + }, + "arguments": { + "$ref": "#/definitions/ScopesArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "ScopesArguments": { + "type": "object", + "description": "Arguments for 'scopes' request.", + "properties": { + "frameId": { + "type": "integer", + "description": "Retrieve the scopes for this stackframe." + } + }, + "required": [ "frameId" ] + }, + "ScopesResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'scopes' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "scopes": { + "type": "array", + "items": { + "$ref": "#/definitions/Scope" + }, + "description": "The scopes of the stackframe. If the array has length zero, there are no scopes available." + } + }, + "required": [ "scopes" ] + } + }, + "required": [ "body" ] + }] + }, + + "VariablesRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "Retrieves all child variables for the given variable reference.\nAn optional filter can be used to limit the fetched children to either named or indexed children.", + "properties": { + "command": { + "type": "string", + "enum": [ "variables" ] + }, + "arguments": { + "$ref": "#/definitions/VariablesArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "VariablesArguments": { + "type": "object", + "description": "Arguments for 'variables' request.", + "properties": { + "variablesReference": { + "type": "integer", + "description": "The Variable reference." + }, + "filter": { + "type": "string", + "enum": [ "indexed", "named" ], + "description": "Optional filter to limit the child variables to either named or indexed. If omitted, both types are fetched." + }, + "start": { + "type": "integer", + "description": "The index of the first variable to return; if omitted children start at 0." + }, + "count": { + "type": "integer", + "description": "The number of variables to return. If count is missing or 0, all variables are returned." + }, + "format": { + "$ref": "#/definitions/ValueFormat", + "description": "Specifies details on how to format the Variable values.\nThe attribute is only honored by a debug adapter if the capability 'supportsValueFormattingOptions' is true." + } + }, + "required": [ "variablesReference" ] + }, + "VariablesResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'variables' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "variables": { + "type": "array", + "items": { + "$ref": "#/definitions/Variable" + }, + "description": "All (or a range) of variables for the given variable reference." + } + }, + "required": [ "variables" ] + } + }, + "required": [ "body" ] + }] + }, + + "SetVariableRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "Set the variable with the given name in the variable container to a new value. Clients should only call this request if the capability 'supportsSetVariable' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "setVariable" ] + }, + "arguments": { + "$ref": "#/definitions/SetVariableArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "SetVariableArguments": { + "type": "object", + "description": "Arguments for 'setVariable' request.", + "properties": { + "variablesReference": { + "type": "integer", + "description": "The reference of the variable container." + }, + "name": { + "type": "string", + "description": "The name of the variable in the container." + }, + "value": { + "type": "string", + "description": "The value of the variable." + }, + "format": { + "$ref": "#/definitions/ValueFormat", + "description": "Specifies details on how to format the response value." + } + }, + "required": [ "variablesReference", "name", "value" ] + }, + "SetVariableResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'setVariable' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "value": { + "type": "string", + "description": "The new value of the variable." + }, + "type": { + "type": "string", + "description": "The type of the new value. Typically shown in the UI when hovering over the value." + }, + "variablesReference": { + "type": "integer", + "description": "If variablesReference is > 0, the new value is structured and its children can be retrieved by passing variablesReference to the VariablesRequest.\nThe value should be less than or equal to 2147483647 (2^31-1)." + }, + "namedVariables": { + "type": "integer", + "description": "The number of named child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks.\nThe value should be less than or equal to 2147483647 (2^31-1)." + }, + "indexedVariables": { + "type": "integer", + "description": "The number of indexed child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks.\nThe value should be less than or equal to 2147483647 (2^31-1)." + } + }, + "required": [ "value" ] + } + }, + "required": [ "body" ] + }] + }, + + "SourceRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The request retrieves the source code for a given source reference.", + "properties": { + "command": { + "type": "string", + "enum": [ "source" ] + }, + "arguments": { + "$ref": "#/definitions/SourceArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "SourceArguments": { + "type": "object", + "description": "Arguments for 'source' request.", + "properties": { + "source": { + "$ref": "#/definitions/Source", + "description": "Specifies the source content to load. Either source.path or source.sourceReference must be specified." + }, + "sourceReference": { + "type": "integer", + "description": "The reference to the source. This is the same as source.sourceReference.\nThis is provided for backward compatibility since old backends do not understand the 'source' attribute." + } + }, + "required": [ "sourceReference" ] + }, + "SourceResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'source' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "content": { + "type": "string", + "description": "Content of the source reference." + }, + "mimeType": { + "type": "string", + "description": "Optional content type (mime type) of the source." + } + }, + "required": [ "content" ] + } + }, + "required": [ "body" ] + }] + }, + + "ThreadsRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The request retrieves a list of all threads.", + "properties": { + "command": { + "type": "string", + "enum": [ "threads" ] + } + }, + "required": [ "command" ] + }] + }, + "ThreadsResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'threads' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "threads": { + "type": "array", + "items": { + "$ref": "#/definitions/Thread" + }, + "description": "All threads." + } + }, + "required": [ "threads" ] + } + }, + "required": [ "body" ] + }] + }, + + "TerminateThreadsRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The request terminates the threads with the given ids.\nClients should only call this request if the capability 'supportsTerminateThreadsRequest' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "terminateThreads" ] + }, + "arguments": { + "$ref": "#/definitions/TerminateThreadsArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "TerminateThreadsArguments": { + "type": "object", + "description": "Arguments for 'terminateThreads' request.", + "properties": { + "threadIds": { + "type": "array", + "items": { + "type": "integer" + }, + "description": "Ids of threads to be terminated." + } + } + }, + "TerminateThreadsResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'terminateThreads' request. This is just an acknowledgement, so no body field is required." + }] + }, + + "ModulesRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "Modules can be retrieved from the debug adapter with this request which can either return all modules or a range of modules to support paging.\nClients should only call this request if the capability 'supportsModulesRequest' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "modules" ] + }, + "arguments": { + "$ref": "#/definitions/ModulesArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "ModulesArguments": { + "type": "object", + "description": "Arguments for 'modules' request.", + "properties": { + "startModule": { + "type": "integer", + "description": "The index of the first module to return; if omitted modules start at 0." + }, + "moduleCount": { + "type": "integer", + "description": "The number of modules to return. If moduleCount is not specified or 0, all modules are returned." + } + } + }, + "ModulesResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'modules' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "modules": { + "type": "array", + "items": { + "$ref": "#/definitions/Module" + }, + "description": "All modules or range of modules." + }, + "totalModules": { + "type": "integer", + "description": "The total number of modules available." + } + }, + "required": [ "modules" ] + } + }, + "required": [ "body" ] + }] + }, + + "LoadedSourcesRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "Retrieves the set of all sources currently loaded by the debugged process.\nClients should only call this request if the capability 'supportsLoadedSourcesRequest' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "loadedSources" ] + }, + "arguments": { + "$ref": "#/definitions/LoadedSourcesArguments" + } + }, + "required": [ "command" ] + }] + }, + "LoadedSourcesArguments": { + "type": "object", + "description": "Arguments for 'loadedSources' request." + }, + "LoadedSourcesResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'loadedSources' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "sources": { + "type": "array", + "items": { + "$ref": "#/definitions/Source" + }, + "description": "Set of loaded sources." + } + }, + "required": [ "sources" ] + } + }, + "required": [ "body" ] + }] + }, + + "EvaluateRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "Evaluates the given expression in the context of the top most stack frame.\nThe expression has access to any variables and arguments that are in scope.", + "properties": { + "command": { + "type": "string", + "enum": [ "evaluate" ] + }, + "arguments": { + "$ref": "#/definitions/EvaluateArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "EvaluateArguments": { + "type": "object", + "description": "Arguments for 'evaluate' request.", + "properties": { + "expression": { + "type": "string", + "description": "The expression to evaluate." + }, + "frameId": { + "type": "integer", + "description": "Evaluate the expression in the scope of this stack frame. If not specified, the expression is evaluated in the global scope." + }, + "context": { + "type": "string", + "_enum": [ "watch", "repl", "hover", "clipboard" ], + "enumDescriptions": [ + "evaluate is run in a watch.", + "evaluate is run from REPL console.", + "evaluate is run from a data hover.", + "evaluate is run to generate the value that will be stored in the clipboard.\nThe attribute is only honored by a debug adapter if the capability 'supportsClipboardContext' is true." + ], + "description": "The context in which the evaluate request is run." + }, + "format": { + "$ref": "#/definitions/ValueFormat", + "description": "Specifies details on how to format the Evaluate result.\nThe attribute is only honored by a debug adapter if the capability 'supportsValueFormattingOptions' is true." + } + }, + "required": [ "expression" ] + }, + "EvaluateResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'evaluate' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "result": { + "type": "string", + "description": "The result of the evaluate request." + }, + "type": { + "type": "string", + "description": "The optional type of the evaluate result.\nThis attribute should only be returned by a debug adapter if the client has passed the value true for the 'supportsVariableType' capability of the 'initialize' request." + }, + "presentationHint": { + "$ref": "#/definitions/VariablePresentationHint", + "description": "Properties of a evaluate result that can be used to determine how to render the result in the UI." + }, + "variablesReference": { + "type": "integer", + "description": "If variablesReference is > 0, the evaluate result is structured and its children can be retrieved by passing variablesReference to the VariablesRequest.\nThe value should be less than or equal to 2147483647 (2^31-1)." + }, + "namedVariables": { + "type": "integer", + "description": "The number of named child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks.\nThe value should be less than or equal to 2147483647 (2^31-1)." + }, + "indexedVariables": { + "type": "integer", + "description": "The number of indexed child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks.\nThe value should be less than or equal to 2147483647 (2^31-1)." + }, + "memoryReference": { + "type": "string", + "description": "Optional memory reference to a location appropriate for this result.\nFor pointer type eval results, this is generally a reference to the memory address contained in the pointer.\nThis attribute should be returned by a debug adapter if the client has passed the value true for the 'supportsMemoryReferences' capability of the 'initialize' request." + } + }, + "required": [ "result", "variablesReference" ] + } + }, + "required": [ "body" ] + }] + }, + + "SetExpressionRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "Evaluates the given 'value' expression and assigns it to the 'expression' which must be a modifiable l-value.\nThe expressions have access to any variables and arguments that are in scope of the specified frame.\nClients should only call this request if the capability 'supportsSetExpression' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "setExpression" ] + }, + "arguments": { + "$ref": "#/definitions/SetExpressionArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "SetExpressionArguments": { + "type": "object", + "description": "Arguments for 'setExpression' request.", + "properties": { + "expression": { + "type": "string", + "description": "The l-value expression to assign to." + }, + "value": { + "type": "string", + "description": "The value expression to assign to the l-value expression." + }, + "frameId": { + "type": "integer", + "description": "Evaluate the expressions in the scope of this stack frame. If not specified, the expressions are evaluated in the global scope." + }, + "format": { + "$ref": "#/definitions/ValueFormat", + "description": "Specifies how the resulting value should be formatted." + } + }, + "required": [ "expression", "value" ] + }, + "SetExpressionResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'setExpression' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "value": { + "type": "string", + "description": "The new value of the expression." + }, + "type": { + "type": "string", + "description": "The optional type of the value.\nThis attribute should only be returned by a debug adapter if the client has passed the value true for the 'supportsVariableType' capability of the 'initialize' request." + }, + "presentationHint": { + "$ref": "#/definitions/VariablePresentationHint", + "description": "Properties of a value that can be used to determine how to render the result in the UI." + }, + "variablesReference": { + "type": "integer", + "description": "If variablesReference is > 0, the value is structured and its children can be retrieved by passing variablesReference to the VariablesRequest.\nThe value should be less than or equal to 2147483647 (2^31-1)." + }, + "namedVariables": { + "type": "integer", + "description": "The number of named child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks.\nThe value should be less than or equal to 2147483647 (2^31-1)." + }, + "indexedVariables": { + "type": "integer", + "description": "The number of indexed child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks.\nThe value should be less than or equal to 2147483647 (2^31-1)." + } + }, + "required": [ "value" ] + } + }, + "required": [ "body" ] + }] + }, + + "StepInTargetsRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "This request retrieves the possible stepIn targets for the specified stack frame.\nThese targets can be used in the 'stepIn' request.\nThe StepInTargets may only be called if the 'supportsStepInTargetsRequest' capability exists and is true.\nClients should only call this request if the capability 'supportsStepInTargetsRequest' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "stepInTargets" ] + }, + "arguments": { + "$ref": "#/definitions/StepInTargetsArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "StepInTargetsArguments": { + "type": "object", + "description": "Arguments for 'stepInTargets' request.", + "properties": { + "frameId": { + "type": "integer", + "description": "The stack frame for which to retrieve the possible stepIn targets." + } + }, + "required": [ "frameId" ] + }, + "StepInTargetsResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'stepInTargets' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "targets": { + "type": "array", + "items": { + "$ref": "#/definitions/StepInTarget" + }, + "description": "The possible stepIn targets of the specified source location." + } + }, + "required": [ "targets" ] + } + }, + "required": [ "body" ] + }] + }, + + "GotoTargetsRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "This request retrieves the possible goto targets for the specified source location.\nThese targets can be used in the 'goto' request.\nClients should only call this request if the capability 'supportsGotoTargetsRequest' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "gotoTargets" ] + }, + "arguments": { + "$ref": "#/definitions/GotoTargetsArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "GotoTargetsArguments": { + "type": "object", + "description": "Arguments for 'gotoTargets' request.", + "properties": { + "source": { + "$ref": "#/definitions/Source", + "description": "The source location for which the goto targets are determined." + }, + "line": { + "type": "integer", + "description": "The line location for which the goto targets are determined." + }, + "column": { + "type": "integer", + "description": "An optional column location for which the goto targets are determined." + } + }, + "required": [ "source", "line" ] + }, + "GotoTargetsResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'gotoTargets' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "targets": { + "type": "array", + "items": { + "$ref": "#/definitions/GotoTarget" + }, + "description": "The possible goto targets of the specified location." + } + }, + "required": [ "targets" ] + } + }, + "required": [ "body" ] + }] + }, + + "CompletionsRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "Returns a list of possible completions for a given caret position and text.\nClients should only call this request if the capability 'supportsCompletionsRequest' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "completions" ] + }, + "arguments": { + "$ref": "#/definitions/CompletionsArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "CompletionsArguments": { + "type": "object", + "description": "Arguments for 'completions' request.", + "properties": { + "frameId": { + "type": "integer", + "description": "Returns completions in the scope of this stack frame. If not specified, the completions are returned for the global scope." + }, + "text": { + "type": "string", + "description": "One or more source lines. Typically this is the text a user has typed into the debug console before he asked for completion." + }, + "column": { + "type": "integer", + "description": "The character position for which to determine the completion proposals." + }, + "line": { + "type": "integer", + "description": "An optional line for which to determine the completion proposals. If missing the first line of the text is assumed." + } + }, + "required": [ "text", "column" ] + }, + "CompletionsResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'completions' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "targets": { + "type": "array", + "items": { + "$ref": "#/definitions/CompletionItem" + }, + "description": "The possible completions for ." + } + }, + "required": [ "targets" ] + } + }, + "required": [ "body" ] + }] + }, + + "ExceptionInfoRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "Retrieves the details of the exception that caused this event to be raised.\nClients should only call this request if the capability 'supportsExceptionInfoRequest' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "exceptionInfo" ] + }, + "arguments": { + "$ref": "#/definitions/ExceptionInfoArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "ExceptionInfoArguments": { + "type": "object", + "description": "Arguments for 'exceptionInfo' request.", + "properties": { + "threadId": { + "type": "integer", + "description": "Thread for which exception information should be retrieved." + } + }, + "required": [ "threadId" ] + }, + "ExceptionInfoResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'exceptionInfo' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "exceptionId": { + "type": "string", + "description": "ID of the exception that was thrown." + }, + "description": { + "type": "string", + "description": "Descriptive text for the exception provided by the debug adapter." + }, + "breakMode": { + "$ref": "#/definitions/ExceptionBreakMode", + "description": "Mode that caused the exception notification to be raised." + }, + "details": { + "$ref": "#/definitions/ExceptionDetails", + "description": "Detailed information about the exception." + } + }, + "required": [ "exceptionId", "breakMode" ] + } + }, + "required": [ "body" ] + }] + }, + + "ReadMemoryRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "Reads bytes from memory at the provided location.\nClients should only call this request if the capability 'supportsReadMemoryRequest' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "readMemory" ] + }, + "arguments": { + "$ref": "#/definitions/ReadMemoryArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "ReadMemoryArguments": { + "type": "object", + "description": "Arguments for 'readMemory' request.", + "properties": { + "memoryReference": { + "type": "string", + "description": "Memory reference to the base location from which data should be read." + }, + "offset": { + "type": "integer", + "description": "Optional offset (in bytes) to be applied to the reference location before reading data. Can be negative." + }, + "count": { + "type": "integer", + "description": "Number of bytes to read at the specified location and offset." + } + }, + "required": [ "memoryReference", "count" ] + }, + "ReadMemoryResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'readMemory' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "address": { + "type": "string", + "description": "The address of the first byte of data returned.\nTreated as a hex value if prefixed with '0x', or as a decimal value otherwise." + }, + "unreadableBytes": { + "type": "integer", + "description": "The number of unreadable bytes encountered after the last successfully read byte.\nThis can be used to determine the number of bytes that must be skipped before a subsequent 'readMemory' request will succeed." + }, + "data": { + "type": "string", + "description": "The bytes read from memory, encoded using base64." + } + }, + "required": [ "address" ] + } + } + }] + }, + + "DisassembleRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "Disassembles code stored at the provided location.\nClients should only call this request if the capability 'supportsDisassembleRequest' is true.", + "properties": { + "command": { + "type": "string", + "enum": [ "disassemble" ] + }, + "arguments": { + "$ref": "#/definitions/DisassembleArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "DisassembleArguments": { + "type": "object", + "description": "Arguments for 'disassemble' request.", + "properties": { + "memoryReference": { + "type": "string", + "description": "Memory reference to the base location containing the instructions to disassemble." + }, + "offset": { + "type": "integer", + "description": "Optional offset (in bytes) to be applied to the reference location before disassembling. Can be negative." + }, + "instructionOffset": { + "type": "integer", + "description": "Optional offset (in instructions) to be applied after the byte offset (if any) before disassembling. Can be negative." + }, + "instructionCount": { + "type": "integer", + "description": "Number of instructions to disassemble starting at the specified location and offset.\nAn adapter must return exactly this number of instructions - any unavailable instructions should be replaced with an implementation-defined 'invalid instruction' value." + }, + "resolveSymbols": { + "type": "boolean", + "description": "If true, the adapter should attempt to resolve memory addresses and other values to symbolic names." + } + }, + "required": [ "memoryReference", "instructionCount" ] + }, + "DisassembleResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'disassemble' request.", + "properties": { + "body": { + "type": "object", + "properties": { + "instructions": { + "type": "array", + "items": { + "$ref": "#/definitions/DisassembledInstruction" + }, + "description": "The list of disassembled instructions." + } + }, + "required": [ "instructions" ] + } + } + }] + }, + + "Capabilities": { + "type": "object", + "title": "Types", + "description": "Information about the capabilities of a debug adapter.", + "properties": { + "supportsConfigurationDoneRequest": { + "type": "boolean", + "description": "The debug adapter supports the 'configurationDone' request." + }, + "supportsFunctionBreakpoints": { + "type": "boolean", + "description": "The debug adapter supports function breakpoints." + }, + "supportsConditionalBreakpoints": { + "type": "boolean", + "description": "The debug adapter supports conditional breakpoints." + }, + "supportsHitConditionalBreakpoints": { + "type": "boolean", + "description": "The debug adapter supports breakpoints that break execution after a specified number of hits." + }, + "supportsEvaluateForHovers": { + "type": "boolean", + "description": "The debug adapter supports a (side effect free) evaluate request for data hovers." + }, + "exceptionBreakpointFilters": { + "type": "array", + "items": { + "$ref": "#/definitions/ExceptionBreakpointsFilter" + }, + "description": "Available exception filter options for the 'setExceptionBreakpoints' request." + }, + "supportsStepBack": { + "type": "boolean", + "description": "The debug adapter supports stepping back via the 'stepBack' and 'reverseContinue' requests." + }, + "supportsSetVariable": { + "type": "boolean", + "description": "The debug adapter supports setting a variable to a value." + }, + "supportsRestartFrame": { + "type": "boolean", + "description": "The debug adapter supports restarting a frame." + }, + "supportsGotoTargetsRequest": { + "type": "boolean", + "description": "The debug adapter supports the 'gotoTargets' request." + }, + "supportsStepInTargetsRequest": { + "type": "boolean", + "description": "The debug adapter supports the 'stepInTargets' request." + }, + "supportsCompletionsRequest": { + "type": "boolean", + "description": "The debug adapter supports the 'completions' request." + }, + "completionTriggerCharacters": { + "type": "array", + "items": { + "type": "string" + }, + "description": "The set of characters that should trigger completion in a REPL. If not specified, the UI should assume the '.' character." + }, + "supportsModulesRequest": { + "type": "boolean", + "description": "The debug adapter supports the 'modules' request." + }, + "additionalModuleColumns": { + "type": "array", + "items": { + "$ref": "#/definitions/ColumnDescriptor" + }, + "description": "The set of additional module information exposed by the debug adapter." + }, + "supportedChecksumAlgorithms": { + "type": "array", + "items": { + "$ref": "#/definitions/ChecksumAlgorithm" + }, + "description": "Checksum algorithms supported by the debug adapter." + }, + "supportsRestartRequest": { + "type": "boolean", + "description": "The debug adapter supports the 'restart' request. In this case a client should not implement 'restart' by terminating and relaunching the adapter but by calling the RestartRequest." + }, + "supportsExceptionOptions": { + "type": "boolean", + "description": "The debug adapter supports 'exceptionOptions' on the setExceptionBreakpoints request." + }, + "supportsValueFormattingOptions": { + "type": "boolean", + "description": "The debug adapter supports a 'format' attribute on the stackTraceRequest, variablesRequest, and evaluateRequest." + }, + "supportsExceptionInfoRequest": { + "type": "boolean", + "description": "The debug adapter supports the 'exceptionInfo' request." + }, + "supportTerminateDebuggee": { + "type": "boolean", + "description": "The debug adapter supports the 'terminateDebuggee' attribute on the 'disconnect' request." + }, + "supportsDelayedStackTraceLoading": { + "type": "boolean", + "description": "The debug adapter supports the delayed loading of parts of the stack, which requires that both the 'startFrame' and 'levels' arguments and an optional 'totalFrames' result of the 'StackTrace' request are supported." + }, + "supportsLoadedSourcesRequest": { + "type": "boolean", + "description": "The debug adapter supports the 'loadedSources' request." + }, + "supportsLogPoints": { + "type": "boolean", + "description": "The debug adapter supports logpoints by interpreting the 'logMessage' attribute of the SourceBreakpoint." + }, + "supportsTerminateThreadsRequest": { + "type": "boolean", + "description": "The debug adapter supports the 'terminateThreads' request." + }, + "supportsSetExpression": { + "type": "boolean", + "description": "The debug adapter supports the 'setExpression' request." + }, + "supportsTerminateRequest": { + "type": "boolean", + "description": "The debug adapter supports the 'terminate' request." + }, + "supportsDataBreakpoints": { + "type": "boolean", + "description": "The debug adapter supports data breakpoints." + }, + "supportsReadMemoryRequest": { + "type": "boolean", + "description": "The debug adapter supports the 'readMemory' request." + }, + "supportsDisassembleRequest": { + "type": "boolean", + "description": "The debug adapter supports the 'disassemble' request." + }, + "supportsCancelRequest": { + "type": "boolean", + "description": "The debug adapter supports the 'cancel' request." + }, + "supportsBreakpointLocationsRequest": { + "type": "boolean", + "description": "The debug adapter supports the 'breakpointLocations' request." + }, + "supportsClipboardContext": { + "type": "boolean", + "description": "The debug adapter supports the 'clipboard' context value in the 'evaluate' request." + }, + "supportsSteppingGranularity": { + "type": "boolean", + "description": "The debug adapter supports stepping granularities (argument 'granularity') for the stepping requests." + }, + "supportsInstructionBreakpoints": { + "type": "boolean", + "description": "The debug adapter supports adding breakpoints based on instruction references." + }, + "supportsExceptionFilterOptions": { + "type": "boolean", + "description": "The debug adapter supports 'filterOptions' as an argument on the 'setExceptionBreakpoints' request." + } + } + }, + + "ExceptionBreakpointsFilter": { + "type": "object", + "description": "An ExceptionBreakpointsFilter is shown in the UI as an filter option for configuring how exceptions are dealt with.", + "properties": { + "filter": { + "type": "string", + "description": "The internal ID of the filter option. This value is passed to the 'setExceptionBreakpoints' request." + }, + "label": { + "type": "string", + "description": "The name of the filter option. This will be shown in the UI." + }, + "default": { + "type": "boolean", + "description": "Initial value of the filter option. If not specified a value 'false' is assumed." + }, + "supportsCondition": { + "type": "boolean", + "description": "Controls whether a condition can be specified for this filter option. If false or missing, a condition can not be set." + } + }, + "required": [ "filter", "label" ] + }, + + "Message": { + "type": "object", + "description": "A structured message object. Used to return errors from requests.", + "properties": { + "id": { + "type": "integer", + "description": "Unique identifier for the message." + }, + "format": { + "type": "string", + "description": "A format string for the message. Embedded variables have the form '{name}'.\nIf variable name starts with an underscore character, the variable does not contain user data (PII) and can be safely used for telemetry purposes." + }, + "variables": { + "type": "object", + "description": "An object used as a dictionary for looking up the variables in the format string.", + "additionalProperties": { + "type": "string", + "description": "Values must be strings." + } + }, + "sendTelemetry": { + "type": "boolean", + "description": "If true send to telemetry." + }, + "showUser": { + "type": "boolean", + "description": "If true show user." + }, + "url": { + "type": "string", + "description": "An optional url where additional information about this message can be found." + }, + "urlLabel": { + "type": "string", + "description": "An optional label that is presented to the user as the UI for opening the url." + } + }, + "required": [ "id", "format" ] + }, + + "Module": { + "type": "object", + "description": "A Module object represents a row in the modules view.\nTwo attributes are mandatory: an id identifies a module in the modules view and is used in a ModuleEvent for identifying a module for adding, updating or deleting.\nThe name is used to minimally render the module in the UI.\n\nAdditional attributes can be added to the module. They will show up in the module View if they have a corresponding ColumnDescriptor.\n\nTo avoid an unnecessary proliferation of additional attributes with similar semantics but different names\nwe recommend to re-use attributes from the 'recommended' list below first, and only introduce new attributes if nothing appropriate could be found.", + "properties": { + "id": { + "type": ["integer", "string"], + "description": "Unique identifier for the module." + }, + "name": { + "type": "string", + "description": "A name of the module." + }, + "path": { + "type": "string", + "description": "optional but recommended attributes.\nalways try to use these first before introducing additional attributes.\n\nLogical full path to the module. The exact definition is implementation defined, but usually this would be a full path to the on-disk file for the module." + }, + "isOptimized": { + "type": "boolean", + "description": "True if the module is optimized." + }, + "isUserCode": { + "type": "boolean", + "description": "True if the module is considered 'user code' by a debugger that supports 'Just My Code'." + }, + "version": { + "type": "string", + "description": "Version of Module." + }, + "symbolStatus": { + "type": "string", + "description": "User understandable description of if symbols were found for the module (ex: 'Symbols Loaded', 'Symbols not found', etc." + }, + "symbolFilePath": { + "type": "string", + "description": "Logical full path to the symbol file. The exact definition is implementation defined." + }, + "dateTimeStamp": { + "type": "string", + "description": "Module created or modified." + }, + "addressRange": { + "type": "string", + "description": "Address range covered by this module." + } + }, + "required": [ "id", "name" ] + }, + + "ColumnDescriptor": { + "type": "object", + "description": "A ColumnDescriptor specifies what module attribute to show in a column of the ModulesView, how to format it,\nand what the column's label should be.\nIt is only used if the underlying UI actually supports this level of customization.", + "properties": { + "attributeName": { + "type": "string", + "description": "Name of the attribute rendered in this column." + }, + "label": { + "type": "string", + "description": "Header UI label of column." + }, + "format": { + "type": "string", + "description": "Format to use for the rendered values in this column. TBD how the format strings looks like." + }, + "type": { + "type": "string", + "enum": [ "string", "number", "boolean", "unixTimestampUTC" ], + "description": "Datatype of values in this column. Defaults to 'string' if not specified." + }, + "width": { + "type": "integer", + "description": "Width of this column in characters (hint only)." + } + }, + "required": [ "attributeName", "label"] + }, + + "ModulesViewDescriptor": { + "type": "object", + "description": "The ModulesViewDescriptor is the container for all declarative configuration options of a ModuleView.\nFor now it only specifies the columns to be shown in the modules view.", + "properties": { + "columns": { + "type": "array", + "items": { + "$ref": "#/definitions/ColumnDescriptor" + } + } + }, + "required": [ "columns" ] + }, + + "Thread": { + "type": "object", + "description": "A Thread", + "properties": { + "id": { + "type": "integer", + "description": "Unique identifier for the thread." + }, + "name": { + "type": "string", + "description": "A name of the thread." + } + }, + "required": [ "id", "name" ] + }, + + "Source": { + "type": "object", + "description": "A Source is a descriptor for source code.\nIt is returned from the debug adapter as part of a StackFrame and it is used by clients when specifying breakpoints.", + "properties": { + "name": { + "type": "string", + "description": "The short name of the source. Every source returned from the debug adapter has a name.\nWhen sending a source to the debug adapter this name is optional." + }, + "path": { + "type": "string", + "description": "The path of the source to be shown in the UI.\nIt is only used to locate and load the content of the source if no sourceReference is specified (or its value is 0)." + }, + "sourceReference": { + "type": "integer", + "description": "If sourceReference > 0 the contents of the source must be retrieved through the SourceRequest (even if a path is specified).\nA sourceReference is only valid for a session, so it must not be used to persist a source.\nThe value should be less than or equal to 2147483647 (2^31-1)." + }, + "presentationHint": { + "type": "string", + "description": "An optional hint for how to present the source in the UI.\nA value of 'deemphasize' can be used to indicate that the source is not available or that it is skipped on stepping.", + "enum": [ "normal", "emphasize", "deemphasize" ] + }, + "origin": { + "type": "string", + "description": "The (optional) origin of this source: possible values 'internal module', 'inlined content from source map', etc." + }, + "sources": { + "type": "array", + "items": { + "$ref": "#/definitions/Source" + }, + "description": "An optional list of sources that are related to this source. These may be the source that generated this source." + }, + "adapterData": { + "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], + "description": "Optional data that a debug adapter might want to loop through the client.\nThe client should leave the data intact and persist it across sessions. The client should not interpret the data." + }, + "checksums": { + "type": "array", + "items": { + "$ref": "#/definitions/Checksum" + }, + "description": "The checksums associated with this file." + } + } + }, + + "StackFrame": { + "type": "object", + "description": "A Stackframe contains the source location.", + "properties": { + "id": { + "type": "integer", + "description": "An identifier for the stack frame. It must be unique across all threads.\nThis id can be used to retrieve the scopes of the frame with the 'scopesRequest' or to restart the execution of a stackframe." + }, + "name": { + "type": "string", + "description": "The name of the stack frame, typically a method name." + }, + "source": { + "$ref": "#/definitions/Source", + "description": "The optional source of the frame." + }, + "line": { + "type": "integer", + "description": "The line within the file of the frame. If source is null or doesn't exist, line is 0 and must be ignored." + }, + "column": { + "type": "integer", + "description": "The column within the line. If source is null or doesn't exist, column is 0 and must be ignored." + }, + "endLine": { + "type": "integer", + "description": "An optional end line of the range covered by the stack frame." + }, + "endColumn": { + "type": "integer", + "description": "An optional end column of the range covered by the stack frame." + }, + "instructionPointerReference": { + "type": "string", + "description": "Optional memory reference for the current instruction pointer in this frame." + }, + "moduleId": { + "type": ["integer", "string"], + "description": "The module associated with this frame, if any." + }, + "presentationHint": { + "type": "string", + "enum": [ "normal", "label", "subtle" ], + "description": "An optional hint for how to present this frame in the UI.\nA value of 'label' can be used to indicate that the frame is an artificial frame that is used as a visual label or separator. A value of 'subtle' can be used to change the appearance of a frame in a 'subtle' way." + } + }, + "required": [ "id", "name", "line", "column" ] + }, + + "Scope": { + "type": "object", + "description": "A Scope is a named container for variables. Optionally a scope can map to a source or a range within a source.", + "properties": { + "name": { + "type": "string", + "description": "Name of the scope such as 'Arguments', 'Locals', or 'Registers'. This string is shown in the UI as is and can be translated." + }, + "presentationHint": { + "type": "string", + "description": "An optional hint for how to present this scope in the UI. If this attribute is missing, the scope is shown with a generic UI.", + "_enum": [ "arguments", "locals", "registers" ], + "enumDescriptions": [ + "Scope contains method arguments.", + "Scope contains local variables.", + "Scope contains registers. Only a single 'registers' scope should be returned from a 'scopes' request." + ] + }, + "variablesReference": { + "type": "integer", + "description": "The variables of this scope can be retrieved by passing the value of variablesReference to the VariablesRequest." + }, + "namedVariables": { + "type": "integer", + "description": "The number of named variables in this scope.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks." + }, + "indexedVariables": { + "type": "integer", + "description": "The number of indexed variables in this scope.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks." + }, + "expensive": { + "type": "boolean", + "description": "If true, the number of variables in this scope is large or expensive to retrieve." + }, + "source": { + "$ref": "#/definitions/Source", + "description": "Optional source for this scope." + }, + "line": { + "type": "integer", + "description": "Optional start line of the range covered by this scope." + }, + "column": { + "type": "integer", + "description": "Optional start column of the range covered by this scope." + }, + "endLine": { + "type": "integer", + "description": "Optional end line of the range covered by this scope." + }, + "endColumn": { + "type": "integer", + "description": "Optional end column of the range covered by this scope." + } + }, + "required": [ "name", "variablesReference", "expensive" ] + }, + + "Variable": { + "type": "object", + "description": "A Variable is a name/value pair.\nOptionally a variable can have a 'type' that is shown if space permits or when hovering over the variable's name.\nAn optional 'kind' is used to render additional properties of the variable, e.g. different icons can be used to indicate that a variable is public or private.\nIf the value is structured (has children), a handle is provided to retrieve the children with the VariablesRequest.\nIf the number of named or indexed children is large, the numbers should be returned via the optional 'namedVariables' and 'indexedVariables' attributes.\nThe client can use this optional information to present the children in a paged UI and fetch them in chunks.", + "properties": { + "name": { + "type": "string", + "description": "The variable's name." + }, + "value": { + "type": "string", + "description": "The variable's value. This can be a multi-line text, e.g. for a function the body of a function." + }, + "type": { + "type": "string", + "description": "The type of the variable's value. Typically shown in the UI when hovering over the value.\nThis attribute should only be returned by a debug adapter if the client has passed the value true for the 'supportsVariableType' capability of the 'initialize' request." + }, + "presentationHint": { + "$ref": "#/definitions/VariablePresentationHint", + "description": "Properties of a variable that can be used to determine how to render the variable in the UI." + }, + "evaluateName": { + "type": "string", + "description": "Optional evaluatable name of this variable which can be passed to the 'EvaluateRequest' to fetch the variable's value." + }, + "variablesReference": { + "type": "integer", + "description": "If variablesReference is > 0, the variable is structured and its children can be retrieved by passing variablesReference to the VariablesRequest." + }, + "namedVariables": { + "type": "integer", + "description": "The number of named child variables.\nThe client can use this optional information to present the children in a paged UI and fetch them in chunks." + }, + "indexedVariables": { + "type": "integer", + "description": "The number of indexed child variables.\nThe client can use this optional information to present the children in a paged UI and fetch them in chunks." + }, + "memoryReference": { + "type": "string", + "description": "Optional memory reference for the variable if the variable represents executable code, such as a function pointer.\nThis attribute is only required if the client has passed the value true for the 'supportsMemoryReferences' capability of the 'initialize' request." + } + }, + "required": [ "name", "value", "variablesReference" ] + }, + + "VariablePresentationHint": { + "type": "object", + "description": "Optional properties of a variable that can be used to determine how to render the variable in the UI.", + "properties": { + "kind": { + "description": "The kind of variable. Before introducing additional values, try to use the listed values.", + "type": "string", + "_enum": [ "property", "method", "class", "data", "event", "baseClass", "innerClass", "interface", "mostDerivedClass", "virtual", "dataBreakpoint" ], + "enumDescriptions": [ + "Indicates that the object is a property.", + "Indicates that the object is a method.", + "Indicates that the object is a class.", + "Indicates that the object is data.", + "Indicates that the object is an event.", + "Indicates that the object is a base class.", + "Indicates that the object is an inner class.", + "Indicates that the object is an interface.", + "Indicates that the object is the most derived class.", + "Indicates that the object is virtual, that means it is a synthetic object introducedby the\nadapter for rendering purposes, e.g. an index range for large arrays.", + "Deprecated: Indicates that a data breakpoint is registered for the object. The 'hasDataBreakpoint' attribute should generally be used instead." + ] + }, + "attributes": { + "description": "Set of attributes represented as an array of strings. Before introducing additional values, try to use the listed values.", + "type": "array", + "items": { + "type": "string", + "_enum": [ "static", "constant", "readOnly", "rawString", "hasObjectId", "canHaveObjectId", "hasSideEffects", "hasDataBreakpoint" ], + "enumDescriptions": [ + "Indicates that the object is static.", + "Indicates that the object is a constant.", + "Indicates that the object is read only.", + "Indicates that the object is a raw string.", + "Indicates that the object can have an Object ID created for it.", + "Indicates that the object has an Object ID associated with it.", + "Indicates that the evaluation had side effects.", + "Indicates that the object has its value tracked by a data breakpoint." + ] + } + }, + "visibility": { + "description": "Visibility of variable. Before introducing additional values, try to use the listed values.", + "type": "string", + "_enum": [ "public", "private", "protected", "internal", "final" ] + } + } + }, + + "BreakpointLocation": { + "type": "object", + "description": "Properties of a breakpoint location returned from the 'breakpointLocations' request.", + "properties": { + "line": { + "type": "integer", + "description": "Start line of breakpoint location." + }, + "column": { + "type": "integer", + "description": "Optional start column of breakpoint location." + }, + "endLine": { + "type": "integer", + "description": "Optional end line of breakpoint location if the location covers a range." + }, + "endColumn": { + "type": "integer", + "description": "Optional end column of breakpoint location if the location covers a range." + } + }, + "required": [ "line" ] + }, + + "SourceBreakpoint": { + "type": "object", + "description": "Properties of a breakpoint or logpoint passed to the setBreakpoints request.", + "properties": { + "line": { + "type": "integer", + "description": "The source line of the breakpoint or logpoint." + }, + "column": { + "type": "integer", + "description": "An optional source column of the breakpoint." + }, + "condition": { + "type": "string", + "description": "An optional expression for conditional breakpoints.\nIt is only honored by a debug adapter if the capability 'supportsConditionalBreakpoints' is true." + }, + "hitCondition": { + "type": "string", + "description": "An optional expression that controls how many hits of the breakpoint are ignored.\nThe backend is expected to interpret the expression as needed.\nThe attribute is only honored by a debug adapter if the capability 'supportsHitConditionalBreakpoints' is true." + }, + "logMessage": { + "type": "string", + "description": "If this attribute exists and is non-empty, the backend must not 'break' (stop)\nbut log the message instead. Expressions within {} are interpolated.\nThe attribute is only honored by a debug adapter if the capability 'supportsLogPoints' is true." + } + }, + "required": [ "line" ] + }, + + "FunctionBreakpoint": { + "type": "object", + "description": "Properties of a breakpoint passed to the setFunctionBreakpoints request.", + "properties": { + "name": { + "type": "string", + "description": "The name of the function." + }, + "condition": { + "type": "string", + "description": "An optional expression for conditional breakpoints.\nIt is only honored by a debug adapter if the capability 'supportsConditionalBreakpoints' is true." + }, + "hitCondition": { + "type": "string", + "description": "An optional expression that controls how many hits of the breakpoint are ignored.\nThe backend is expected to interpret the expression as needed.\nThe attribute is only honored by a debug adapter if the capability 'supportsHitConditionalBreakpoints' is true." + } + }, + "required": [ "name" ] + }, + + "DataBreakpointAccessType": { + "type": "string", + "description": "This enumeration defines all possible access types for data breakpoints.", + "enum": [ "read", "write", "readWrite" ] + }, + + "DataBreakpoint": { + "type": "object", + "description": "Properties of a data breakpoint passed to the setDataBreakpoints request.", + "properties": { + "dataId": { + "type": "string", + "description": "An id representing the data. This id is returned from the dataBreakpointInfo request." + }, + "accessType": { + "$ref": "#/definitions/DataBreakpointAccessType", + "description": "The access type of the data." + }, + "condition": { + "type": "string", + "description": "An optional expression for conditional breakpoints." + }, + "hitCondition": { + "type": "string", + "description": "An optional expression that controls how many hits of the breakpoint are ignored.\nThe backend is expected to interpret the expression as needed." + } + }, + "required": [ "dataId" ] + }, + + "InstructionBreakpoint": { + "type": "object", + "description": "Properties of a breakpoint passed to the setInstructionBreakpoints request", + "properties": { + "instructionReference": { + "type": "string", + "description": "The instruction reference of the breakpoint.\nThis should be a memory or instruction pointer reference from an EvaluateResponse, Variable, StackFrame, GotoTarget, or Breakpoint." + }, + "offset": { + "type": "integer", + "description": "An optional offset from the instruction reference.\nThis can be negative." + }, + "condition": { + "type": "string", + "description": "An optional expression for conditional breakpoints.\nIt is only honored by a debug adapter if the capability 'supportsConditionalBreakpoints' is true." + }, + "hitCondition": { + "type": "string", + "description": "An optional expression that controls how many hits of the breakpoint are ignored.\nThe backend is expected to interpret the expression as needed.\nThe attribute is only honored by a debug adapter if the capability 'supportsHitConditionalBreakpoints' is true." + } + }, + "required": [ "instructionReference" ] + }, + + "Breakpoint": { + "type": "object", + "description": "Information about a Breakpoint created in setBreakpoints, setFunctionBreakpoints, setInstructionBreakpoints, or setDataBreakpoints.", + "properties": { + "id": { + "type": "integer", + "description": "An optional identifier for the breakpoint. It is needed if breakpoint events are used to update or remove breakpoints." + }, + "verified": { + "type": "boolean", + "description": "If true breakpoint could be set (but not necessarily at the desired location)." + }, + "message": { + "type": "string", + "description": "An optional message about the state of the breakpoint.\nThis is shown to the user and can be used to explain why a breakpoint could not be verified." + }, + "source": { + "$ref": "#/definitions/Source", + "description": "The source where the breakpoint is located." + }, + "line": { + "type": "integer", + "description": "The start line of the actual range covered by the breakpoint." + }, + "column": { + "type": "integer", + "description": "An optional start column of the actual range covered by the breakpoint." + }, + "endLine": { + "type": "integer", + "description": "An optional end line of the actual range covered by the breakpoint." + }, + "endColumn": { + "type": "integer", + "description": "An optional end column of the actual range covered by the breakpoint.\nIf no end line is given, then the end column is assumed to be in the start line." + }, + "instructionReference": { + "type": "string", + "description": "An optional memory reference to where the breakpoint is set." + }, + "offset": { + "type": "integer", + "description": "An optional offset from the instruction reference.\nThis can be negative." + } + }, + "required": [ "verified" ] + }, + + "SteppingGranularity": { + "type": "string", + "description": "The granularity of one 'step' in the stepping requests 'next', 'stepIn', 'stepOut', and 'stepBack'.", + "enum": [ "statement", "line", "instruction" ], + "enumDescriptions": [ + "The step should allow the program to run until the current statement has finished executing.\nThe meaning of a statement is determined by the adapter and it may be considered equivalent to a line.\nFor example 'for(int i = 0; i < 10; i++) could be considered to have 3 statements 'int i = 0', 'i < 10', and 'i++'.", + "The step should allow the program to run until the current source line has executed.", + "The step should allow one instruction to execute (e.g. one x86 instruction)." + ] + }, + + "StepInTarget": { + "type": "object", + "description": "A StepInTarget can be used in the 'stepIn' request and determines into which single target the stepIn request should step.", + "properties": { + "id": { + "type": "integer", + "description": "Unique identifier for a stepIn target." + }, + "label": { + "type": "string", + "description": "The name of the stepIn target (shown in the UI)." + } + }, + "required": [ "id", "label" ] + }, + + "GotoTarget": { + "type": "object", + "description": "A GotoTarget describes a code location that can be used as a target in the 'goto' request.\nThe possible goto targets can be determined via the 'gotoTargets' request.", + "properties": { + "id": { + "type": "integer", + "description": "Unique identifier for a goto target. This is used in the goto request." + }, + "label": { + "type": "string", + "description": "The name of the goto target (shown in the UI)." + }, + "line": { + "type": "integer", + "description": "The line of the goto target." + }, + "column": { + "type": "integer", + "description": "An optional column of the goto target." + }, + "endLine": { + "type": "integer", + "description": "An optional end line of the range covered by the goto target." + }, + "endColumn": { + "type": "integer", + "description": "An optional end column of the range covered by the goto target." + }, + "instructionPointerReference": { + "type": "string", + "description": "Optional memory reference for the instruction pointer value represented by this target." + } + }, + "required": [ "id", "label", "line" ] + }, + + "CompletionItem": { + "type": "object", + "description": "CompletionItems are the suggestions returned from the CompletionsRequest.", + "properties": { + "label": { + "type": "string", + "description": "The label of this completion item. By default this is also the text that is inserted when selecting this completion." + }, + "text": { + "type": "string", + "description": "If text is not falsy then it is inserted instead of the label." + }, + "sortText": { + "type": "string", + "description": "A string that should be used when comparing this item with other items. When `falsy` the label is used." + }, + "type": { + "$ref": "#/definitions/CompletionItemType", + "description": "The item's type. Typically the client uses this information to render the item in the UI with an icon." + }, + "start": { + "type": "integer", + "description": "This value determines the location (in the CompletionsRequest's 'text' attribute) where the completion text is added.\nIf missing the text is added at the location specified by the CompletionsRequest's 'column' attribute." + }, + "length": { + "type": "integer", + "description": "This value determines how many characters are overwritten by the completion text.\nIf missing the value 0 is assumed which results in the completion text being inserted." + }, + "selectionStart": { + "type": "integer", + "description": "Determines the start of the new selection after the text has been inserted (or replaced).\nThe start position must in the range 0 and length of the completion text.\nIf omitted the selection starts at the end of the completion text." + }, + "selectionLength": { + "type": "integer", + "description": "Determines the length of the new selection after the text has been inserted (or replaced).\nThe selection can not extend beyond the bounds of the completion text.\nIf omitted the length is assumed to be 0." + } + }, + "required": [ "label" ] + }, + + "CompletionItemType": { + "type": "string", + "description": "Some predefined types for the CompletionItem. Please note that not all clients have specific icons for all of them.", + "enum": [ "method", "function", "constructor", "field", "variable", "class", "interface", "module", "property", "unit", "value", "enum", "keyword", "snippet", "text", "color", "file", "reference", "customcolor" ] + }, + + "ChecksumAlgorithm": { + "type": "string", + "description": "Names of checksum algorithms that may be supported by a debug adapter.", + "enum": [ "MD5", "SHA1", "SHA256", "timestamp" ] + }, + + "Checksum": { + "type": "object", + "description": "The checksum of an item calculated by the specified algorithm.", + "properties": { + "algorithm": { + "$ref": "#/definitions/ChecksumAlgorithm", + "description": "The algorithm used to calculate this checksum." + }, + "checksum": { + "type": "string", + "description": "Value of the checksum." + } + }, + "required": [ "algorithm", "checksum" ] + }, + + "ValueFormat": { + "type": "object", + "description": "Provides formatting information for a value.", + "properties": { + "hex": { + "type": "boolean", + "description": "Display the value in hex." + } + } + }, + + "StackFrameFormat": { + "allOf": [ { "$ref": "#/definitions/ValueFormat" }, { + "type": "object", + "description": "Provides formatting information for a stack frame.", + "properties": { + "parameters": { + "type": "boolean", + "description": "Displays parameters for the stack frame." + }, + "parameterTypes": { + "type": "boolean", + "description": "Displays the types of parameters for the stack frame." + }, + "parameterNames": { + "type": "boolean", + "description": "Displays the names of parameters for the stack frame." + }, + "parameterValues": { + "type": "boolean", + "description": "Displays the values of parameters for the stack frame." + }, + "line": { + "type": "boolean", + "description": "Displays the line number of the stack frame." + }, + "module": { + "type": "boolean", + "description": "Displays the module of the stack frame." + }, + "includeAll": { + "type": "boolean", + "description": "Includes all stack frames, including those the debug adapter might otherwise hide." + } + } + }] + }, + + "ExceptionFilterOptions": { + "type": "object", + "description": "An ExceptionFilterOptions is used to specify an exception filter together with a condition for the setExceptionsFilter request.", + "properties": { + "filterId": { + "type": "string", + "description": "ID of an exception filter returned by the 'exceptionBreakpointFilters' capability." + }, + "condition": { + "type": "string", + "description": "An optional expression for conditional exceptions.\nThe exception will break into the debugger if the result of the condition is true." + } + }, + "required": [ "filterId" ] + }, + + "ExceptionOptions": { + "type": "object", + "description": "An ExceptionOptions assigns configuration options to a set of exceptions.", + "properties": { + "path": { + "type": "array", + "items": { + "$ref": "#/definitions/ExceptionPathSegment" + }, + "description": "A path that selects a single or multiple exceptions in a tree. If 'path' is missing, the whole tree is selected.\nBy convention the first segment of the path is a category that is used to group exceptions in the UI." + }, + "breakMode": { + "$ref": "#/definitions/ExceptionBreakMode", + "description": "Condition when a thrown exception should result in a break." + } + }, + "required": [ "breakMode" ] + }, + + "ExceptionBreakMode": { + "type": "string", + "description": "This enumeration defines all possible conditions when a thrown exception should result in a break.\nnever: never breaks,\nalways: always breaks,\nunhandled: breaks when exception unhandled,\nuserUnhandled: breaks if the exception is not handled by user code.", + "enum": [ "never", "always", "unhandled", "userUnhandled" ] + }, + + "ExceptionPathSegment": { + "type": "object", + "description": "An ExceptionPathSegment represents a segment in a path that is used to match leafs or nodes in a tree of exceptions.\nIf a segment consists of more than one name, it matches the names provided if 'negate' is false or missing or\nit matches anything except the names provided if 'negate' is true.", + "properties": { + "negate": { + "type": "boolean", + "description": "If false or missing this segment matches the names provided, otherwise it matches anything except the names provided." + }, + "names": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Depending on the value of 'negate' the names that should match or not match." + } + }, + "required": [ "names" ] + }, + + "ExceptionDetails": { + "type": "object", + "description": "Detailed information about an exception that has occurred.", + "properties": { + "message": { + "type": "string", + "description": "Message contained in the exception." + }, + "typeName": { + "type": "string", + "description": "Short type name of the exception object." + }, + "fullTypeName": { + "type": "string", + "description": "Fully-qualified type name of the exception object." + }, + "evaluateName": { + "type": "string", + "description": "Optional expression that can be evaluated in the current scope to obtain the exception object." + }, + "stackTrace": { + "type": "string", + "description": "Stack trace at the time the exception was thrown." + }, + "innerException": { + "type": "array", + "items": { + "$ref": "#/definitions/ExceptionDetails" + }, + "description": "Details of the exception contained by this exception, if any." + } + } + }, + + "DisassembledInstruction": { + "type": "object", + "description": "Represents a single disassembled instruction.", + "properties": { + "address": { + "type": "string", + "description": "The address of the instruction. Treated as a hex value if prefixed with '0x', or as a decimal value otherwise." + }, + "instructionBytes": { + "type": "string", + "description": "Optional raw bytes representing the instruction and its operands, in an implementation-defined format." + }, + "instruction": { + "type": "string", + "description": "Text representing the instruction and its operands, in an implementation-defined format." + }, + "symbol": { + "type": "string", + "description": "Name of the symbol that corresponds with the location of this instruction, if any." + }, + "location": { + "$ref": "#/definitions/Source", + "description": "Source location that corresponds to this instruction, if any.\nShould always be set (if available) on the first instruction returned,\nbut can be omitted afterwards if this instruction maps to the same source file as the previous instruction." + }, + "line": { + "type": "integer", + "description": "The line within the source location that corresponds to this instruction, if any." + }, + "column": { + "type": "integer", + "description": "The column within the line that corresponds to this instruction, if any." + }, + "endLine": { + "type": "integer", + "description": "The end line of the range that corresponds to this instruction, if any." + }, + "endColumn": { + "type": "integer", + "description": "The end column of the range that corresponds to this instruction, if any." + } + }, + "required": [ "address", "instruction" ] + }, + + "InvalidatedAreas": { + "type": "string", + "description": "Logical areas that can be invalidated by the 'invalidated' event.", + "_enum": [ "all", "stacks", "threads", "variables" ], + "enumDescriptions": [ + "All previously fetched data has become invalid and needs to be refetched.", + "Previously fetched stack related data has become invalid and needs to be refetched.", + "Previously fetched thread related data has become invalid and needs to be refetched.", + "Previously fetched variable data has become invalid and needs to be refetched." + ] + } + + } +} diff --git a/protocols/dap/tycho/plugins/org.eclipse.gemoc.protocols.dap.api/.classpath b/protocols/dap/tycho/plugins/org.eclipse.gemoc.protocols.dap.api/.classpath new file mode 100644 index 000000000..bc001b4a7 --- /dev/null +++ b/protocols/dap/tycho/plugins/org.eclipse.gemoc.protocols.dap.api/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/protocols/dap/tycho/plugins/org.eclipse.gemoc.protocols.dap.api/.gitignore b/protocols/dap/tycho/plugins/org.eclipse.gemoc.protocols.dap.api/.gitignore new file mode 100644 index 000000000..b34c53731 --- /dev/null +++ b/protocols/dap/tycho/plugins/org.eclipse.gemoc.protocols.dap.api/.gitignore @@ -0,0 +1 @@ +/src-gen/ diff --git a/protocols/dap/tycho/plugins/org.eclipse.gemoc.protocols.dap.api/.project b/protocols/dap/tycho/plugins/org.eclipse.gemoc.protocols.dap.api/.project new file mode 100644 index 000000000..852cade7e --- /dev/null +++ b/protocols/dap/tycho/plugins/org.eclipse.gemoc.protocols.dap.api/.project @@ -0,0 +1,34 @@ + + + org.eclipse.gemoc.protocols.dap.api + + + + + + org.eclipse.xtext.ui.shared.xtextBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + org.eclipse.xtext.ui.shared.xtextNature + + diff --git a/protocols/dap/tycho/plugins/org.eclipse.gemoc.protocols.dap.api/META-INF/MANIFEST.MF b/protocols/dap/tycho/plugins/org.eclipse.gemoc.protocols.dap.api/META-INF/MANIFEST.MF new file mode 100644 index 000000000..547f635e3 --- /dev/null +++ b/protocols/dap/tycho/plugins/org.eclipse.gemoc.protocols.dap.api/META-INF/MANIFEST.MF @@ -0,0 +1,12 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: org.eclipse.gemoc.protocols.dap.api +Bundle-SymbolicName: org.eclipse.gemoc.protocols.dap.api;singleton:=true +Bundle-Version: 2.3.0.qualifier +Bundle-RequiredExecutionEnvironment: JavaSE-1.8 +Require-Bundle: org.eclipse.core.runtime;bundle-version="3.14.0", + org.eclipse.xtend.lib;bundle-version="2.25.0", + com.google.gson;bundle-version="2.8.2", + org.eclipse.lsp4j.jsonrpc;bundle-version="0.10.0", + org.eclipse.lsp4j.generator;bundle-version="0.12.0" +Bundle-Vendor: Eclipse GEMOC Project diff --git a/protocols/engine_addon_protocol/docs/EngineAddonProtocol.asciidoc b/protocols/engine_addon_protocol/docs/EngineAddonProtocol.asciidoc new file mode 100644 index 000000000..d8cac643f --- /dev/null +++ b/protocols/engine_addon_protocol/docs/EngineAddonProtocol.asciidoc @@ -0,0 +1,26 @@ +//////////////////////////////////////////////////////////////// +// Reproduce title only if not included in master documentation +//////////////////////////////////////////////////////////////// +ifndef::includedInMaster[] + += Developer Guide +== Protocols + +endif::[] + +=== Engine Add-On Protocol + +footnote:[asciidoc source of this page: https://github.com/eclipse/gemoc-studio-modeldebugging/tree/master/protocols/engine_addon_protocol/docs/EngineAddonProtocol.asciidoc.] + +The goal of the Engine Add-On Protocol (EAOP) is to provide services similar to those offered by the java IEngineAddon API (cf. <>) +but via websocket communication. + +The figure <> presents the Client and Server JSON RPC methods and the exchanged data. + +[[img-EAOP-CD-devguide]] +.Engine Add-On Protocol overview +image::images/EngineAddonProtocol.png["EngineAddonProtocol"] + + + + diff --git a/protocols/engine_addon_protocol/docs/images/EngineAddonProtocol.plantuml b/protocols/engine_addon_protocol/docs/images/EngineAddonProtocol.plantuml new file mode 100644 index 000000000..ef7699297 --- /dev/null +++ b/protocols/engine_addon_protocol/docs/images/EngineAddonProtocol.plantuml @@ -0,0 +1,106 @@ +@startuml +' GENERATED FILE, DO NOT MODIFY MANUALLY + +package EngineAddonProtocol_API { +package data { +class EngineAboutToStartEventArguments { + ExecutionEngine engine +} +class EngineStartedEventArguments { + ExecutionEngine engine +} +class EngineInitializedEventArguments { + ExecutionEngine engine +} +class EngineAboutToStopEventArguments { + ExecutionEngine engine +} +class EngineStoppedEventArguments { + ExecutionEngine engine +} +class EngineAboutToDisposeEventArguments { + ExecutionEngine engine +} +class AboutToExecuteStepEventArguments { + ExecutionEngine engine + Step stepToExecute +} +class StepExecutedEventArguments { + ExecutionEngine engine + Step stepToExecute +} +class GetStateArguments { + String stateId +} +class GetStateResponse { + { + State state + } body +} +class GetStepArguments { + String stateId +} +class GetStepResponse { + { + Step state + } body +} +class ExecutionEngine { + String engineKindName + String engineName +} +class Step { + MSEOccurence mseOccurence + String startingStateID + String endingStateID +} +class MSEOccurence { + MSE mse + String parameters + String result +} +class MSE { + String callerEObjectURI + String actionID +} +class State { + StateValue[] changedValues + String[] startedStepsID + String[] endedStepsID +} +class StateValue { +} +class Message { + Integer id + String format + Map variables + boolean sendTelemetry + boolean showUser + String url + String urlLabel +} +} +package services { +class EngineAddonProtocolServer { + @JsonRequest| { + State state + } getState(GetStateArguments arguments) + @JsonRequest| { + Step state + } getStep(GetStepArguments arguments) +} +class EngineAddonProtocolClient { + @JsonNotification| void engineAboutToStart(EngineAboutToStartEventArguments args) + @JsonNotification| void engineStarted(EngineStartedEventArguments args) + @JsonNotification| void engineInitialized(EngineInitializedEventArguments args) + @JsonNotification| void engineAboutToStop(EngineAboutToStopEventArguments args) + @JsonNotification| void engineStopped(EngineStoppedEventArguments args) + @JsonNotification| void engineAboutToDispose(EngineAboutToDisposeEventArguments args) + @JsonNotification| void aboutToExecuteStep(AboutToExecuteStepEventArguments args) + @JsonNotification| void stepExecuted(StepExecutedEventArguments args) +} +} +services -[hidden]- data +} +@enduml + diff --git a/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/.classpath b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/.classpath new file mode 100644 index 000000000..95cdcb120 --- /dev/null +++ b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/.gitignore b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/.gitignore new file mode 100644 index 000000000..b34c53731 --- /dev/null +++ b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/.gitignore @@ -0,0 +1 @@ +/src-gen/ diff --git a/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/.project b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/.project new file mode 100644 index 000000000..8a4810f14 --- /dev/null +++ b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/.project @@ -0,0 +1,34 @@ + + + org.eclipse.gemoc.protocols.eaop.api + + + + + + org.eclipse.xtext.ui.shared.xtextBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + org.eclipse.xtext.ui.shared.xtextNature + + diff --git a/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/.settings/org.eclipse.jdt.core.prefs b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..c9545f06a --- /dev/null +++ b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,9 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=11 +org.eclipse.jdt.core.compiler.compliance=11 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning +org.eclipse.jdt.core.compiler.release=enabled +org.eclipse.jdt.core.compiler.source=11 diff --git a/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/META-INF/MANIFEST.MF b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/META-INF/MANIFEST.MF new file mode 100644 index 000000000..bdf604c5b --- /dev/null +++ b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/META-INF/MANIFEST.MF @@ -0,0 +1,17 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: org.eclipse.gemoc.protocols.eaop.api +Bundle-SymbolicName: org.eclipse.gemoc.protocols.eaop.api;singleton:=true +Bundle-Version: 2.3.0.qualifier +Bundle-RequiredExecutionEnvironment: JavaSE-11 +Require-Bundle: org.eclipse.core.runtime;bundle-version="3.14.0", + org.eclipse.xtend.lib;bundle-version="2.25.0", + com.google.gson;bundle-version="2.8.2", + org.eclipse.lsp4j.jsonrpc;bundle-version="0.10.0", + org.eclipse.lsp4j.generator;bundle-version="0.12.0" +Bundle-Vendor: Eclipse GEMOC Project +Automatic-Module-Name: org.eclipse.gemoc.protocols.eaop.api +Export-Package: org.eclipse.gemoc.protocols.eaop.api.data, + org.eclipse.gemoc.protocols.eaop.api.json, + org.eclipse.gemoc.protocols.eaop.api.messages, + org.eclipse.gemoc.protocols.eaop.api.services diff --git a/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/build.properties b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/build.properties new file mode 100644 index 000000000..a6835df7c --- /dev/null +++ b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/build.properties @@ -0,0 +1,6 @@ +source.. = src/,\ + src-gen/,\ + xtend-gen/ +output.. = bin/ +bin.includes = META-INF/,\ + . diff --git a/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src/org/eclipse/gemoc/protocols/eaop/api/json/EaopMessageJsonHandler.java b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src/org/eclipse/gemoc/protocols/eaop/api/json/EaopMessageJsonHandler.java new file mode 100644 index 000000000..bed004450 --- /dev/null +++ b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src/org/eclipse/gemoc/protocols/eaop/api/json/EaopMessageJsonHandler.java @@ -0,0 +1,26 @@ +package org.eclipse.gemoc.protocols.eaop.api.json; + +import java.util.Map; +import java.util.function.Consumer; + +import org.eclipse.lsp4j.jsonrpc.json.JsonRpcMethod; +import org.eclipse.lsp4j.jsonrpc.json.MessageJsonHandler; + +import com.google.gson.GsonBuilder; + +public class EaopMessageJsonHandler extends MessageJsonHandler { + public EaopMessageJsonHandler(Map supportedMethods) { + super(supportedMethods); + } + + public EaopMessageJsonHandler(Map supportedMethods, Consumer configureGson) { + super(supportedMethods, configureGson); + } + + public GsonBuilder getDefaultGsonBuilder() { + GsonBuilder gsonBuilder = super.getDefaultGsonBuilder(); + gsonBuilder.registerTypeAdapterFactory(new EaopMessageTypeAdapter.Factory(this)); + // add more adapter if required + return gsonBuilder; + } +} diff --git a/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src/org/eclipse/gemoc/protocols/eaop/api/json/EaopMessageTypeAdapter.java b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src/org/eclipse/gemoc/protocols/eaop/api/json/EaopMessageTypeAdapter.java new file mode 100644 index 000000000..45846295c --- /dev/null +++ b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src/org/eclipse/gemoc/protocols/eaop/api/json/EaopMessageTypeAdapter.java @@ -0,0 +1,470 @@ +package org.eclipse.gemoc.protocols.eaop.api.json; + + +import java.io.EOFException; +import java.io.IOException; +import java.lang.reflect.Type; + +import org.eclipse.gemoc.protocols.eaop.api.messages.EaopNotificationMessage; +import org.eclipse.gemoc.protocols.eaop.api.messages.EaopRequestMessage; +import org.eclipse.gemoc.protocols.eaop.api.messages.EaopResponseMessage; +import org.eclipse.lsp4j.jsonrpc.MessageIssueException; +import org.eclipse.lsp4j.jsonrpc.json.JsonRpcMethod; +import org.eclipse.lsp4j.jsonrpc.json.MessageJsonHandler; +import org.eclipse.lsp4j.jsonrpc.json.MethodProvider; +import org.eclipse.lsp4j.jsonrpc.json.adapters.MessageTypeAdapter; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.eclipse.lsp4j.jsonrpc.messages.Message; +import org.eclipse.lsp4j.jsonrpc.messages.MessageIssue; +import org.eclipse.lsp4j.jsonrpc.messages.ResponseError; +import org.eclipse.lsp4j.jsonrpc.messages.ResponseErrorCode; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonToken; +import com.google.gson.stream.JsonWriter; +import com.google.gson.stream.MalformedJsonException; + +/** + * The {@link METPMessageTypeAdapter} provides an adapter that maps METP + * Server Protocol style JSON to/from LSP4J's JSONRPC implementation. The Model Execution + * Trace Protocol (METP) has its own message format that is quite similar to + * JSON-RPC 2.0. The METP is defined in a JSON + * schema in the VS Code METP Adapter. This section documents how LSP4J's + * jsonrpc classes maps to the METP Protocol, using some extensions in the DSP + * code to the lsp4j's {@link Message}s. + *

+ * + *

+	"ProtocolMessage": { // implemented by {@link Message}
+		"type": "object",
+		"description": "Base class of requests, responses, and events.",
+		"properties": {
+			"seq": { // implemented by (depending on type, with conversion to/from String):
+			         //  {@link METPRequestMessage#getId()}, or
+			         //  {@link METPNotificationMessage#getId()} or
+			         //  {@link METPResponseMessage#getResponseId()}
+				"type": "integer",
+				"description": "Sequence number."
+			},
+			"type": { // implicit in type of subclass of {@link Message}
+				"type": "string",
+				"description": "Message type.",
+				"_enum": [ "request", "response", "event" ]
+			}
+		},
+		"required": [ "seq", "type" ]
+	},
+	"Request": { // implemented by {@link METPRequestMessage}
+		"allOf": [ { "$ref": "#/definitions/ProtocolMessage" }, {
+			"type": "object",
+			"description": "A client or server-initiated request.",
+			"properties": {
+				"type": { // implicit by being of type {@link METPRequestMessage}
+					"type": "string",
+					"enum": [ "request" ]
+				},
+				"command": { // implemented by {@link METPRequestMessage#getMethod()}
+					"type": "string",
+					"description": "The command to execute."
+				},
+				"arguments": { // implemented by {@link METPRequestMessage#getParams()}
+					"type": [ "array", "boolean", "integer", "null", "number" , "object", "string" ],
+					"description": "Object containing arguments for the command."
+				}
+			},
+			"required": [ "type", "command" ]
+		}]
+	},
+	"Event": { // implemented by {@link METPNotificationMessage}
+		"allOf": [ { "$ref": "#/definitions/ProtocolMessage" }, {
+			"type": "object",
+			"description": "Server-initiated event.",
+			"properties": {
+				"type": { // implicit by being of type {@link METPNotificationMessage}
+					"type": "string",
+					"enum": [ "event" ]
+				},
+				"event": { // implemented by {@link METPNotificationMessage#getMethod()}
+					"type": "string",
+					"description": "Type of event."
+				},
+				"body": { // implemented by {@link METPNotificationMessage#getParams()}
+					"type": [ "array", "boolean", "integer", "null", "number" , "object", "string" ],
+					"description": "Event-specific information."
+				}
+			},
+			"required": [ "type", "event" ]
+		}]
+	},
+	"Response": { // implemented by {@link METPResponseMessage}
+		"allOf": [ { "$ref": "#/definitions/ProtocolMessage" }, {
+			"type": "object",
+			"description": "Response to a request.",
+			"properties": {
+				"type": { // implicit by being of type {@link METPResponseMessage}
+					"type": "string",
+					"enum": [ "response" ]
+				},
+				"request_seq": { // implemented by {@link METPResponseMessage#getId()}
+					"type": "integer",
+					"description": "Sequence number of the corresponding request."
+				},
+				"success": { // implemented by {@link METPResponseMessage#getError()} == null
+					"type": "boolean",
+					"description": "Outcome of the request."
+				},
+				"command": { // implemented by {@link METPResponseMessage#getMethod()}
+					"type": "string",
+					"description": "The command requested."
+				},
+				"message": { // implemented by {@link ResponseError#getMessage()}
+					"type": "string",
+					"description": "Contains error message if success == false."
+				},
+				"body": { // implemented by {@link METPResponseMessage#getResult()} for success and {@link ResponseError#getData()} for error
+					"type": [ "array", "boolean", "integer", "null", "number" , "object", "string" ],
+					"description": "Contains request result if success is true and optional error details if success is false."
+				}
+			},
+			"required": [ "type", "request_seq", "success", "command" ]
+		}]
+	},
+ * 
+ * + */ +public class EaopMessageTypeAdapter extends MessageTypeAdapter { + + public static class Factory implements TypeAdapterFactory { + + private final MessageJsonHandler handler; + + public Factory(MessageJsonHandler handler) { + this.handler = handler; + } + + @Override + @SuppressWarnings("unchecked") + public TypeAdapter create(Gson gson, TypeToken typeToken) { + if (!Message.class.isAssignableFrom(typeToken.getRawType())) + return null; + return (TypeAdapter) new EaopMessageTypeAdapter(handler, gson); + } + + } + + private final MessageJsonHandler handler; + private final Gson gson; + + public EaopMessageTypeAdapter(MessageJsonHandler handler, Gson gson) { + super(handler, gson); + this.handler = handler; + this.gson = gson; + } + + @Override + public Message read(JsonReader in) throws IOException { + if (in.peek() == JsonToken.NULL) { + in.nextNull(); + return null; + } + + in.beginObject(); + String messageType = null, method = null, message = null; + int seq = 0, request_seq = 0; + Boolean rawSuccess = null; + Object rawParams = null; + Object rawBody = null; + + try { + + while (in.hasNext()) { + String name = in.nextName(); + switch (name) { + case "seq": { + seq = in.nextInt(); + break; + } + case "request_seq": { + // on responses we treat the request_seq as the id + request_seq = in.nextInt(); + break; + } + case "type": { + messageType = in.nextString(); + break; + } + case "success": { + rawSuccess = in.nextBoolean(); + break; + } + case "command": { + method = in.nextString(); + break; + } + case "event": { + method = in.nextString(); + break; + } + case "message": { + if (in.peek() == JsonToken.NULL) { + in.nextNull(); + } else { + message = in.nextString(); + } + break; + } + case "arguments": { + rawParams = parseParams(in, method); + break; + } + case "body": { + rawBody = parseBody(in, messageType, request_seq, method, rawSuccess); + break; + } + default: + in.skipValue(); + } + } + boolean success = rawSuccess != null ? rawSuccess : false; + Object params = parseParams(rawParams, method); + Object body = parseBody(rawBody, messageType, request_seq, method, success); + + in.endObject(); + return createMessage(messageType, seq, request_seq, method, success, message, params, body); + + } catch (JsonSyntaxException | MalformedJsonException | EOFException exception) { + if ("request".equals(messageType) || "event".equals(messageType) || "response".equals(messageType)) { + // Create a message and bundle it to an exception with an issue that wraps the original exception + boolean success = rawSuccess != null ? rawSuccess : false; + Message resultMessage = createMessage(messageType, seq, request_seq, method, success, message, rawParams, rawBody); + MessageIssue issue = new MessageIssue("Message could not be parsed.", ResponseErrorCode.ParseError.getValue(), exception); + throw new MessageIssueException(resultMessage, issue); + } else { + throw exception; + } + } + } + + /** + * Convert the json input into the body object corresponding to the type of + * message. + * + * If the type of message or any other necessary field is not known until after + * parsing, call {@link #parseBody(Object, String, int, String, Boolean)} on + * the return value of this call for a second chance conversion. + * + * @param in + * json input to read from + * @param messageType + * message type if known + * @param request_seq + * seq id of request message if known + * @param method + * event/method being called + * @param success + * if success of a response is known + * @return correctly typed object if the correct expected type can be + * determined, or a JsonElement representing the body + */ + protected Object parseBody(JsonReader in, String messageType, int request_seq, String method, Boolean success) + throws IOException { + if ("event".equals(messageType)) { + return parseParams(in, method); + } else if ("response".equals(messageType) && success != null && success) { + return super.parseResult(in, Integer.toString(request_seq)); + } else { + return new JsonParser().parse(in); + } + } + + /** + * Convert the JsonElement into the body object corresponding to the type of + * message. If the rawBody is already converted, does nothing. + * + * @param rawBody + * json element to read from + * @param messageType + * message type if known + * @param request_seq + * seq id of request message if known + * @param method + * event/method being called + * @param success + * if success of a response is known + * @return correctly typed object if the correct expected type can be + * determined, or rawBody unmodified if no conversion can be done. + */ + protected Object parseBody(Object rawBody, String messageType, int request_seq, String method, Boolean success) { + if ("event".equals(messageType)) { + return parseParams(rawBody, method); + } else if ("response".equals(messageType)) { + if (success != null && success) { + return super.parseResult(rawBody, Integer.toString(request_seq)); + } + if (isNull(rawBody)) { + return null; + } + if (!(rawBody instanceof JsonElement)) { + return rawBody; + } + JsonElement rawJsonParams = (JsonElement) rawBody; + return fromJson(rawJsonParams, Object.class); + } + return rawBody; + } + + private Message createMessage(String messageType, int seq, int request_seq, String method, boolean success, + String errorMessage, Object params, Object body) throws JsonParseException { + if (messageType == null) { + throw new JsonParseException("Unable to identify the input message. Missing 'type' field."); + } + switch (messageType) { + case "request": { + EaopRequestMessage message = new EaopRequestMessage(); + message.setId(seq); + message.setMethod(method); + message.setParams(params); + return message; + } + case "event": { + EaopNotificationMessage message = new EaopNotificationMessage(); + message.setId(seq); + message.setMethod(method); + message.setParams(body); + return message; + } + case "response": { + EaopResponseMessage message = new EaopResponseMessage(); + message.setId(request_seq); + message.setResponseId(seq); + message.setMethod(method); + if (!success) { + ResponseError error = new ResponseError(); + error.setCode(ResponseErrorCode.UnknownErrorCode); + error.setData(body); + if (errorMessage == null) { + // Some METP servers/clients don't provide a "message" field on an error. + // Generally in those cases the body has some extra details to figure out + // what went wrong. + errorMessage = "Unset error message."; + } + error.setMessage(errorMessage); + message.setError(error); + } else { + if (body instanceof JsonElement) { + // Type of result could not be resolved - try again with the parsed JSON tree + MethodProvider methodProvider = handler.getMethodProvider(); + if (methodProvider != null) { + String resolvedMethod = methodProvider.resolveMethod(Integer.toString(request_seq)); + if (resolvedMethod != null) { + JsonRpcMethod jsonRpcMethod = handler.getJsonRpcMethod(resolvedMethod); + if (jsonRpcMethod != null) { + TypeAdapter typeAdapter = null; + Type returnType = jsonRpcMethod.getReturnType(); + if (jsonRpcMethod.getReturnTypeAdapterFactory() != null) + typeAdapter = jsonRpcMethod.getReturnTypeAdapterFactory().create(gson, TypeToken.get(returnType)); + JsonElement jsonElement = (JsonElement) body; + if (typeAdapter != null) + body = typeAdapter.fromJsonTree(jsonElement); + else + body = gson.fromJson(jsonElement, returnType); + } + } + } + } + message.setResult(body); + } + return message; + } + default: + throw new JsonParseException("Unable to identify the input message."); + } + } + + @Override + public void write(JsonWriter out, Message message) throws IOException { + out.beginObject(); + if (message instanceof EaopRequestMessage) { + EaopRequestMessage requestMessage = (EaopRequestMessage) message; + out.name("type"); + out.value("request"); + out.name("seq"); + writeIntId(out, requestMessage.getRawId()); + out.name("command"); + out.value(requestMessage.getMethod()); + Object params = requestMessage.getParams(); + if (params != null) { + out.name("arguments"); + gson.toJson(params, params.getClass(), out); + } + } else if (message instanceof EaopResponseMessage) { + EaopResponseMessage responseMessage = (EaopResponseMessage) message; + out.name("type"); + out.value("response"); + out.name("seq"); + writeIntId(out, responseMessage.getRawResponseId()); + out.name("request_seq"); + writeIntId(out, responseMessage.getRawId()); + out.name("command"); + out.value(responseMessage.getMethod()); + ResponseError error = responseMessage.getError(); + if (error != null) { + out.name("success"); + out.value(false); + String errorMessage = error.getMessage(); + out.name("message"); + if (errorMessage == null) + writeNullValue(out); + else + gson.toJson(errorMessage, errorMessage.getClass(), out); + + Object errorData = error.getData(); + if (errorData != null) { + out.name("body"); + gson.toJson(errorData, errorData.getClass(), out); + } + } else { + out.name("success"); + out.value(true); + Object result = responseMessage.getResult(); + if (result != null) { + out.name("body"); + gson.toJson(result, result.getClass(), out); + } + } + } else if (message instanceof EaopNotificationMessage) { + EaopNotificationMessage notificationMessage = (EaopNotificationMessage) message; + out.name("type"); + out.value("event"); + out.name("seq"); + writeIntId(out, notificationMessage.getRawId()); + out.name("event"); + out.value(notificationMessage.getMethod()); + Object params = notificationMessage.getParams(); + if (params != null) { + out.name("body"); + gson.toJson(params, params.getClass(), out); + } + } + + out.endObject(); + } + + private void writeIntId(JsonWriter out, Either id) throws IOException { + if (id == null) + writeNullValue(out); + else if (id.isLeft()) + out.value(Integer.parseInt(id.getLeft())); + else if (id.isRight()) + out.value(id.getRight()); + } +} diff --git a/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src/org/eclipse/gemoc/protocols/eaop/api/messages/EaopNotificationMessage.java b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src/org/eclipse/gemoc/protocols/eaop/api/messages/EaopNotificationMessage.java new file mode 100644 index 000000000..67777ac70 --- /dev/null +++ b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src/org/eclipse/gemoc/protocols/eaop/api/messages/EaopNotificationMessage.java @@ -0,0 +1,73 @@ +package org.eclipse.gemoc.protocols.eaop.api.messages; + + +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.eclipse.lsp4j.jsonrpc.messages.NotificationMessage; +import org.eclipse.lsp4j.jsonrpc.validation.NonNull; + +/** + * EAOP specific version of NotificationMessage. + * + * @see EaopMessageTypeAdapter + */ +public class EaopNotificationMessage extends NotificationMessage { + /** + * The notification id. + */ + @NonNull + private Either id; + + public String getId() { + if (id == null) + return null; + if (id.isLeft()) + return id.getLeft(); + if (id.isRight()) + return id.getRight().toString(); + return null; + } + + @NonNull + public Either getRawId() { + return id; + } + + public void setId(String id) { + this.id = Either.forLeft(id); + } + + public void setId(int id) { + this.id = Either.forRight(id); + } + + public void setRawId(@NonNull Either id) { + this.id = id; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + if (!super.equals(obj)) + return false; + EaopNotificationMessage other = (EaopNotificationMessage) obj; + if (this.id == null) { + if (other.id != null) + return false; + } else if (!this.id.equals(other.id)) + return false; + return true; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((this.id == null) ? 0 : this.id.hashCode()); + return result; + } +} diff --git a/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src/org/eclipse/gemoc/protocols/eaop/api/messages/EaopRequestMessage.java b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src/org/eclipse/gemoc/protocols/eaop/api/messages/EaopRequestMessage.java new file mode 100644 index 000000000..ee31abcb4 --- /dev/null +++ b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src/org/eclipse/gemoc/protocols/eaop/api/messages/EaopRequestMessage.java @@ -0,0 +1,12 @@ +package org.eclipse.gemoc.protocols.eaop.api.messages; + +import org.eclipse.lsp4j.jsonrpc.messages.RequestMessage; + +/** + * EAOP specific version of RequestMessage. + * + * @see EaopMessageTypeAdapter + */ +public class EaopRequestMessage extends RequestMessage { + // no additional fields are needed to represent request messages in EAOP +} diff --git a/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src/org/eclipse/gemoc/protocols/eaop/api/messages/EaopResponseMessage.java b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src/org/eclipse/gemoc/protocols/eaop/api/messages/EaopResponseMessage.java new file mode 100644 index 000000000..923d8ec78 --- /dev/null +++ b/protocols/engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src/org/eclipse/gemoc/protocols/eaop/api/messages/EaopResponseMessage.java @@ -0,0 +1,97 @@ +package org.eclipse.gemoc.protocols.eaop.api.messages; + + +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.eclipse.lsp4j.jsonrpc.messages.ResponseMessage; +import org.eclipse.lsp4j.jsonrpc.validation.NonNull; + + +/** + * EAOP specific version of ResponseMessage. + * + * @see EaopMessageTypeAdapter + */ +public class EaopResponseMessage extends ResponseMessage { + /** + * The response id. + * + * The {@link #getId()} field is the id of the message being replied to. + */ + @NonNull + private Either responseId; + + public String getResponseId() { + if (responseId == null) + return null; + if (responseId.isLeft()) + return responseId.getLeft(); + if (responseId.isRight()) + return responseId.getRight().toString(); + return null; + } + + @NonNull + public Either getRawResponseId() { + return responseId; + } + + public void setResponseId(String id) { + this.responseId = Either.forLeft(id); + } + + public void setResponseId(int id) { + this.responseId = Either.forRight(id); + } + + public void setRawResponseId(@NonNull Either id) { + this.responseId = id; + } + + /** + * The method that was invoked. + */ + @NonNull + private String method; + + @NonNull + public String getMethod() { + return this.method; + } + + public void setMethod(@NonNull String method) { + this.method = method; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + if (!super.equals(obj)) + return false; + EaopResponseMessage other = (EaopResponseMessage) obj; + if (this.responseId == null) { + if (other.responseId != null) + return false; + } else if (!this.responseId.equals(other.responseId)) + return false; + if (this.method == null) { + if (other.method != null) + return false; + } else if (!this.method.equals(other.method)) + return false; + return true; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((this.responseId == null) ? 0 : this.responseId.hashCode()); + result = prime * result + ((this.method == null) ? 0 : this.method.hashCode()); + return result; + } +} diff --git a/protocols/engine_addon_protocol/plugins/pom.xml b/protocols/engine_addon_protocol/plugins/pom.xml new file mode 100644 index 000000000..a576edca3 --- /dev/null +++ b/protocols/engine_addon_protocol/plugins/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + + .. + org.eclipse.gemoc.gemoc-studio-modeldebugging.bundle + org.eclipse.gemoc.modeldebugging.protocols.engine_addon_protocol.root + 3.3.0-SNAPSHOT + + + org.eclipse.gemoc.modeldebugging.protocols.engine_addon_protocol.plugins + 4.0.0-SNAPSHOT + pom + + + false + + + + + org.eclipse.gemoc.protocols.eaop.api + + + + + + org.eclipse.xtend + xtend-maven-plugin + ${xtend.version} + + + + compile + + + xtend-gen + + + + + + + org.apache.maven.plugins + maven-clean-plugin + 2.5 + + + + xtend-gen + + + + + + + + + + diff --git a/protocols/engine_addon_protocol/pom.xml b/protocols/engine_addon_protocol/pom.xml new file mode 100644 index 000000000..b3682df2d --- /dev/null +++ b/protocols/engine_addon_protocol/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + org.eclipse.gemoc.modeldebugging.protocols.engine_addon_protocol.root + pom + + org.eclipse.gemoc.gemoc-studio-modeldebugging.bundle + org.eclipse.gemoc.modeldebugging.root + 3.3.0-SNAPSHOT + ../.. + + + + plugins + + + + + + org.eclipse.xtend + xtend-maven-plugin + ${xtend.version} + + + + compile + + + xtend-gen + + + + + + + + + + Eclipse release + p2 + ${eclipse.release.p2.url} + + + diff --git a/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/.classpath b/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/.classpath new file mode 100644 index 000000000..a7bf06493 --- /dev/null +++ b/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/.classpath @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/.project b/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/.project new file mode 100644 index 000000000..a43952708 --- /dev/null +++ b/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/.project @@ -0,0 +1,29 @@ + + + org.eclipse.gemoc.protocols.eaop.api_pomfirst + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.xtext.ui.shared.xtextBuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.xtext.ui.shared.xtextNature + org.eclipse.m2e.core.maven2Nature + + diff --git a/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/.settings/org.eclipse.core.resources.prefs b/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..a5090b3d3 --- /dev/null +++ b/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,3 @@ +eclipse.preferences.version=1 +encoding//target/src/main/java=UTF-8 +encoding/=UTF-8 diff --git a/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/.settings/org.eclipse.jdt.core.prefs b/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..2f5cc74c3 --- /dev/null +++ b/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore +org.eclipse.jdt.core.compiler.release=disabled +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/.settings/org.eclipse.xtend.core.Xtend.prefs b/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/.settings/org.eclipse.xtend.core.Xtend.prefs new file mode 100644 index 000000000..32c37bfe6 --- /dev/null +++ b/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/.settings/org.eclipse.xtend.core.Xtend.prefs @@ -0,0 +1,8 @@ +//outlet.DEFAULT_OUTPUT.sourceFolder.src/main/java.directory=target/xtend-gen +//outlet.DEFAULT_OUTPUT.sourceFolder.src/test/java.directory=src/test/generated-sources/xtend +//outlet.DEFAULT_OUTPUT.sourceFolder.target/src/main/java.directory=target/xtend-gen +BuilderConfiguration.is_project_specific=true +eclipse.preferences.version=1 +outlet.DEFAULT_OUTPUT.hideLocalSyntheticVariables=true +outlet.DEFAULT_OUTPUT.installDslAsPrimarySource=false +outlet.DEFAULT_OUTPUT.userOutputPerSourceFolder=true diff --git a/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/pom.xml b/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/pom.xml new file mode 100644 index 000000000..908142e54 --- /dev/null +++ b/protocols/engine_addon_protocol/pomfirst/org.eclipse.gemoc.protocols.eaop.api/pom.xml @@ -0,0 +1,112 @@ + + + 4.0.0 + + org.eclipse.gemoc.protocols.eaop.api + + jar + + + ../../../../pomfirst + org.eclipse.gemoc.gemoc-studio-modeldebugging + org.eclipse.gemoc.modeldebugging.root + 3.5.0-SNAPSHOT + + + + scm:git:https://github.com/eclipse/gemoc-studio-modeldebugging.git + UTF-8 + + + + + + + maven-resources-plugin + 3.0.2 + + + copy-resource-src + generate-sources + + copy-resources + + + ${basedir}/target/src/main/java + + + ../../plugins/org.eclipse.gemoc.protocols.eaop.api/src-gen + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.2.0 + + + generate-sources + + add-source + + + + target/src/main/java + + + + + + + org.eclipse.xtend + xtend-maven-plugin + + + + + + + org.eclipse.gemoc.gemoc-studio + gemoc-studio-bom + ${project.version} + import + pom + + + + + + org.eclipse.platform + org.eclipse.core.resources + + + org.eclipse.emf + org.eclipse.emf.common + + + org.eclipse.emf + org.eclipse.emf.ecore + + + + org.eclipse.xtend + org.eclipse.xtend.lib + + + org.eclipse.xtend + org.eclipse.xtend.ide.common + + + + org.eclipse.xtext + org.eclipse.xtext.xbase.lib + + + + \ No newline at end of file diff --git a/protocols/engine_addon_protocol/specification/EngineAddonProtocol.json b/protocols/engine_addon_protocol/specification/EngineAddonProtocol.json new file mode 100644 index 000000000..377c4d3be --- /dev/null +++ b/protocols/engine_addon_protocol/specification/EngineAddonProtocol.json @@ -0,0 +1,596 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "title": "GEMOC Engine Addon Protocol", + "description": "GEMOC Engine Addon Protocol defines the protocol used to receive engine notification as defined by the IEngineAddon", + "type": "object", + + + "definitions": { + + "ProtocolMessage": { + "type": "object", + "title": "Base Protocol", + "description": "Base class of requests, responses, and events.", + "properties": { + "seq": { + "type": "integer", + "description": "Sequence number (also known as message ID). For protocol messages of type 'request' this ID can be used to cancel the request." + }, + "type": { + "type": "string", + "description": "Message type.", + "_enum": [ "request", "response", "event" ] + } + }, + "required": [ "seq", "type" ] + }, + + "Request": { + "allOf": [ { "$ref": "#/definitions/ProtocolMessage" }, { + "type": "object", + "description": "A client or debug adapter initiated request.", + "properties": { + "type": { + "type": "string", + "enum": [ "request" ] + }, + "command": { + "type": "string", + "description": "The command to execute." + }, + "arguments": { + "type": [ "array", "boolean", "integer", "null", "number" , "object", "string" ], + "description": "Object containing arguments for the command." + } + }, + "required": [ "type", "command" ] + }] + }, + + "Event": { + "allOf": [ { "$ref": "#/definitions/ProtocolMessage" }, { + "type": "object", + "description": "A debug adapter initiated event.", + "properties": { + "type": { + "type": "string", + "enum": [ "event" ] + }, + "event": { + "type": "string", + "description": "Type of event." + }, + "body": { + "type": [ "array", "boolean", "integer", "null", "number" , "object", "string" ], + "description": "Event-specific information." + } + }, + "required": [ "type", "event" ] + }] + }, + + "Response": { + "allOf": [ { "$ref": "#/definitions/ProtocolMessage" }, { + "type": "object", + "description": "Response for a request.", + "properties": { + "type": { + "type": "string", + "enum": [ "response" ] + }, + "request_seq": { + "type": "integer", + "description": "Sequence number of the corresponding request." + }, + "success": { + "type": "boolean", + "description": "Outcome of the request.\nIf true, the request was successful and the 'body' attribute may contain the result of the request.\nIf the value is false, the attribute 'message' contains the error in short form and the 'body' may contain additional information (see 'ErrorResponse.body.error')." + }, + "command": { + "type": "string", + "description": "The command requested." + }, + "message": { + "type": "string", + "description": "Contains the raw error in short form if 'success' is false.\nThis raw error might be interpreted by the frontend and is not shown in the UI.\nSome predefined values exist.", + "_enum": [ "cancelled" ], + "enumDescriptions": [ + "request was cancelled." + ] + }, + "body": { + "type": [ "array", "boolean", "integer", "null", "number" , "object", "string" ], + "description": "Contains request result if success is true and optional error details if success is false." + } + }, + "required": [ "type", "request_seq", "success", "command" ] + }] + }, + + "ErrorResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "On error (whenever 'success' is false), the body can provide more details.", + "properties": { + "body": { + "type": "object", + "properties": { + "error": { + "$ref": "#/definitions/Message", + "description": "An optional, structured error message." + } + } + } + }, + "required": [ "body" ] + }] + }, + "EngineAboutToStartEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The (blocking) event indicates that an engine is about to start", + "properties": { + "event": { + "type": "string", + "enum": [ "engineAboutToStart" ] + }, + "body": { + "type": "object", + "properties": { + "engine": { + "$ref": "#/definitions/ExecutionEngineDto", + "description": "The name of the engine that is will start" + } + }, + "required": [ "engine" ] + } + }, + "required": [ "event", "body" ] + }] + }, + "EngineStartedEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event indicates that an engine is about to start", + "properties": { + "event": { + "type": "string", + "enum": [ "engineStarted" ] + }, + "body": { + "type": "object", + "properties": { + "engine": { + "$ref": "#/definitions/ExecutionEngineDto", + "description": "The name of the started engine" + } + }, + "required": [ "engine" ] + } + }, + "required": [ "event", "body" ] + }] + }, + "EngineInitializedEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event indicates that an engine has beed initialized", + "properties": { + "event": { + "type": "string", + "enum": [ "engineInitialized" ] + }, + "body": { + "type": "object", + "properties": { + "engine": { + "$ref": "#/definitions/ExecutionEngineDto", + "description": "The name of the initialized engine" + } + }, + "required": [ "engine" ] + } + }, + "required": [ "event", "body" ] + }] + }, + "EngineAboutToStopEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event indicates that an engine is about to stop", + "properties": { + "event": { + "type": "string", + "enum": [ "engineAboutToStop" ] + }, + "body": { + "type": "object", + "properties": { + "engine": { + "$ref": "#/definitions/ExecutionEngineDto", + "description": "The name of the engine" + } + }, + "required": [ "engine" ] + } + }, + "required": [ "event", "body" ] + }] + }, + "EngineStoppedEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event indicates that an engine stopped", + "properties": { + "event": { + "type": "string", + "enum": [ "engineStopped" ] + }, + "body": { + "type": "object", + "properties": { + "engine": { + "$ref": "#/definitions/ExecutionEngineDto", + "description": "The name of the engine" + } + }, + "required": [ "engine" ] + } + }, + "required": [ "event", "body" ] + }] + }, + "EngineAboutToDisposeEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event indicates that an engine is about to dispose", + "properties": { + "event": { + "type": "string", + "enum": [ "engineAboutToDispose" ] + }, + "body": { + "type": "object", + "properties": { + "engine": { + "$ref": "#/definitions/ExecutionEngineDto", + "description": "The name of the engine" + } + }, + "required": [ "engine" ] + } + }, + "required": [ "event", "body" ] + }] + }, + "AboutToExecuteStepEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event indicates that some step is about to execute", + "properties": { + "event": { + "type": "string", + "enum": [ "aboutToExecuteStep" ] + }, + "body": { + "type": "object", + "properties": { + "engine": { + "$ref": "#/definitions/ExecutionEngineDto", + "description": "The name of the engine" + }, + "stepToExecute": { + "$ref": "#/definitions/StepDto", + "description": "step that is about to execute" + } + }, + "required": [ "stateListAsEMFJSON" ] + } + }, + "required": [ "event", "body" ] + }] + }, + "StepExecutedEvent": { + "allOf": [ { "$ref": "#/definitions/Event" }, { + "type": "object", + "description": "The event indicates that a step has been executed", + "properties": { + "event": { + "type": "string", + "enum": [ "stepExecuted" ] + }, + "body": { + "type": "object", + "properties": { + "engine": { + "$ref": "#/definitions/ExecutionEngineDto", + "description": "The name of the engine" + }, + "stepToExecute": { + "$ref": "#/definitions/StepDto", + "description": "step executed" + } + }, + "required": [ "stateListAsEMFJSON" ] + } + }, + "required": [ "event", "body" ] + }] + }, + "InitializeRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "The 'initialize' request is sent as the first request from the client to the eaop\nin order to configure it with client capabilities and register for engine events\nThe 'initialize' request may only be sent once.", + "properties": { + "command": { + "type": "string", + "enum": [ "initialize" ] + }, + "arguments": { + "$ref": "#/definitions/InitializeArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "InitializeArguments": { + "type": "object", + "description": "Arguments for 'Initialize' request.", + "properties": { + "engineIdRegExp": { + "type": "string", + "description": "Regular expression of the engineId of the engine(s) this client is controling/monitoring. (optional, default is '.*')" + } + }, + "required": [] + }, + "InitializeResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'initialize' request. ", + "properties": { + "body": { + "type": "object", + "properties": { + } + } + }, + "required": [ "body" ] + }] + }, + "GetStateRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "", + "properties": { + "command": { + "type": "string", + "enum": [ "getState" ] + }, + "arguments": { + "$ref": "#/definitions/GetStateArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "GetStateArguments": { + "type": "object", + "description": "Arguments for 'getState' request.", + "properties": { + "stateId": { + "type": "string", + "description": "ID or URI of the State" + } + }, + "required": [ "stateId" ] + }, + "GetStateResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'getState' request. ", + "properties": { + "body": { + "type": "object", + "properties": { + "state": { + "$ref": "#/definitions/StateDto", + "description": "" + } + } + } + }, + "required": [ "body" ] + }] + }, + "GetStepRequest": { + "allOf": [ { "$ref": "#/definitions/Request" }, { + "type": "object", + "description": "", + "properties": { + "command": { + "type": "string", + "enum": [ "getStep" ] + }, + "arguments": { + "$ref": "#/definitions/GetStepArguments" + } + }, + "required": [ "command", "arguments" ] + }] + }, + "GetStepArguments": { + "type": "object", + "description": "Arguments for 'getStep' request.", + "properties": { + "stateId": { + "type": "string", + "description": "ID or URI of the Step" + } + }, + "required": [ "stateId" ] + }, + "GetStepResponse": { + "allOf": [ { "$ref": "#/definitions/Response" }, { + "type": "object", + "description": "Response to 'getStep' request. ", + "properties": { + "body": { + "type": "object", + "properties": { + "step": { + "$ref": "#/definitions/StepDto", + "description": "" + } + } + } + }, + "required": [ "body" ] + }] + }, + "ExecutionEngineDto": { + "type": "object", + "title": "Types", + "description": "Information about the Execution Engine.", + "properties": { + "engineKindName": { + "type": "string", + "description": "The engine kind name." + }, + "engineName": { + "type": "string", + "description": "The engine name." + } + } + }, + "StepDto": { + "type": "object", + "title": "Types", + "description": "Information about a Step.", + "properties": { + "mseOccurence": { + "$ref": "#/definitions/MSEOccurenceDto", + "description": "" + }, + "startingStateID": { + "type": "string", + "description": "ID (typically an URI) of the starting RTD state (ie. before this step)" + }, + "endingStateID": { + "type": "string", + "description": "ID (typically an URI) of the ending RTD state (ie. after this step)" + } + } + }, + "MSEOccurenceDto": { + "type": "object", + "title": "Types", + "description": "Information about a MSEOccurence.", + "properties": { + "mse": { + "$ref": "#/definitions/MSEDto", + "description": "" + }, + "parameters": { + "type": "string", + "description": "TODO !" + }, + "result": { + "type": "string", + "description": "TODO !" + } + + } + }, + "MSEDto": { + "type": "object", + "title": "Types", + "description": "Information about a MSE.", + "properties": { + "callerEObjectURI": { + "type": "string", + "description": "URI of the caller EObject in the model" + }, + "actionID": { + "type": "string", + "description": "ID of the action applied to the EObject. Typically the URI of the EOperation." + } + } + }, + "StateDto": { + "type": "object", + "title": "Types", + "description": "Information about a State. NOTE: version working as diff between previous steps (StartedStep) / next steps (EndedSteps)", + "properties": { + "changedValues": { + "type": "array", + "description": "", + "items": { + "$ref": "#/definitions/StateValueDto" + } + }, + "startedStepsID": { + "type": "array", + "description": "List of ID (or URI) of the steps that have this state as StartingState", + "items": { + "type": "string" + } + }, + "endedStepsID": { + "type": "array", + "description": "List of ID (or URI) of the steps that have this state as EndingState", + "items": { + "type": "string" + } + } + } + }, + "StateValueDto": { + "type": "object", + "title": "Types", + "description": "Information about a StateValue.", + "properties": { + } + }, + "Message": { + "type": "object", + "description": "A structured message object. Used to return errors from requests.", + "properties": { + "id": { + "type": "integer", + "description": "Unique identifier for the message." + }, + "format": { + "type": "string", + "description": "A format string for the message. Embedded variables have the form '{name}'.\nIf variable name starts with an underscore character, the variable does not contain user data (PII) and can be safely used for telemetry purposes." + }, + "variables": { + "type": "object", + "description": "An object used as a dictionary for looking up the variables in the format string.", + "additionalProperties": { + "type": "string", + "description": "Values must be strings." + } + }, + "sendTelemetry": { + "type": "boolean", + "description": "If true send to telemetry." + }, + "showUser": { + "type": "boolean", + "description": "If true show user." + }, + "url": { + "type": "string", + "description": "An optional url where additional information about this message can be found." + }, + "urlLabel": { + "type": "string", + "description": "An optional label that is presented to the user as the UI for opening the url." + } + }, + "required": [ "id", "format" ] + } + + } +} diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/.gitignore b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/.gitignore new file mode 100644 index 000000000..b0a5c349c --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/.gitignore @@ -0,0 +1,2 @@ +/node_modules/ +/dist/ diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/.vscode/launch.json b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/.vscode/launch.json new file mode 100644 index 000000000..80b0b1f05 --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/.vscode/launch.json @@ -0,0 +1,34 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Launch Test Generator", + "program": "${workspaceFolder}/dist/testgenconf", + "args": ["./generator_config.json" + ], + "request": "launch", + "skipFiles": [ + "/**" + ], + "type": "pwa-node" + }, + { + "name": "Launch Generator", + "program": "${workspaceFolder}/dist/Generator", + "args": ["../../../mep/specification/ModelExecutionProtocol.json", + "../../../mep/ModelExecutionProtocol.ts", + "../../../mep/IModelExecutionTraceProtocolServer.java", + "../../../mep/IModelExecutionTraceProtocolClient.java", + "../../../mep/IModelExecutionTraceProtocolData.xtend" + ], + "request": "launch", + "skipFiles": [ + "/**" + ], + "type": "pwa-node" + } + ] +} \ No newline at end of file diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/.vscode/tasks.json b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/.vscode/tasks.json new file mode 100644 index 000000000..22f57395b --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/.vscode/tasks.json @@ -0,0 +1,17 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "type": "typescript", + "tsconfig": "tsconfig.json", + "problemMatcher": [ + "$tsc" + ], + "group": { + "kind": "build", + "isDefault": true + }, + "label": "tsc: build - tsconfig.json" + } + ] +} \ No newline at end of file diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/README.md b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/README.md new file mode 100644 index 000000000..95601911b --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/README.md @@ -0,0 +1,25 @@ +# Protocol Generator + +This folder contains the API generator for protocols expressed using a json schema. + +## Configuration + +* `generator_config.json` : contains generation directives (ie. list of protocols and locations of output files) + + +Currently, for each protocol, the generator is able to produce: + +* a typescript interface for the protocol + +* java interfaces and classes compatible with `org.eclipse.lsp4j.jsonrpc` library from https://github.com/eclipse/lsp4j in order to implement Client and Server in java. + +* an overview of the protocol as a plantuml diagram. + +## Useful commands + + +* `npm run build` compiles the generator (in the `dist` folder) + +* `npm run watch` continuously compiles the generator (useful in dev) + +* `npm run generate` calls the generator to generate the language specific interface code from the `*.json` schemas defined in `generator_config.json` diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/generator_config.json b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/generator_config.json new file mode 100644 index 000000000..ae3be1bb4 --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/generator_config.json @@ -0,0 +1,49 @@ +{ + "protocolGenConfigs" : [{ + "protocolName" : "EngineAddonProtocol", + "protocolShortName" : "EAP", + "protocolJSONSchemaPath" : "../../../engine_addon_protocol/specification/EngineAddonProtocol.json", + "tsAPI" : { + "destFileName" : "../../../engine_addon_protocol/ts/org.eclipse.gemoc.protocols.eaop.api/src-gen/EngineAddonProtocol.ts" + }, + "javaServer" : { + "packageName" : "org.eclipse.gemoc.protocols.eaop.api", + "destFileName" : "../../../engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src-gen/org/eclipse/gemoc/protocols/eaop/api/services/IEngineAddonProtocolServer.java" + }, + "javaClient" : { + "packageName" : "org.eclipse.gemoc.protocols.eaop.api", + "destFileName" : "../../../engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src-gen/org/eclipse/gemoc/protocols/eaop/api/services/IEngineAddonProtocolClient.java" + }, + "javaAPI" : { + "packageName" : "org.eclipse.gemoc.protocols.eaop.api", + "destFileName" : "../../../engine_addon_protocol/plugins/org.eclipse.gemoc.protocols.eaop.api/src-gen/org/eclipse/gemoc/protocols/eaop/api/data/EngineAddonProtocolData.xtend" + }, + "plantuml" : { + "destFileName" : "../../../engine_addon_protocol/docs/images/EngineAddonProtocol.plantuml" + } + }, + { + "protocolName" : "DebugAdapterProtocol", + "protocolShortName" : "DAP", + "protocolJSONSchemaPath" : "../../../dap/specification/debugAdapterProtocol.json", + "tsAPI" : { + "destFileName" : "../../../dap/ts/org.eclipse.gemoc.protocols.dap.api/src-gen/DebugAdapterProtocol.ts" + }, + "javaServer" : { + "packageName" : "org.eclipse.gemoc.protocols.dap.api", + "destFileName" : "../../../dap/tycho/plugins/org.eclipse.gemoc.protocols.dap.api/src-gen/org/eclipse/gemoc/protocols/dap/api/services/IDebugAdapterProtocolServer.java" + }, + "javaClient" : { + "packageName" : "org.eclipse.gemoc.protocols.dap.api", + "destFileName" : "../../../dap/tycho/plugins/org.eclipse.gemoc.protocols.dap.api/src-gen/org/eclipse/gemoc/protocols/dap/api/services/IDebugAdapterProtocolClient.java" + }, + "javaAPI" : { + "packageName" : "org.eclipse.gemoc.protocols.dap.api", + "destFileName" : "../../../dap/tycho/plugins/org.eclipse.gemoc.protocols.dap.api/src-gen/org/eclipse/gemoc/protocols/dap/api/data/DebugAdapterProtocolData.xtend" + }, + "plantuml" : { + "destFileName" : "../../../dap/docs/images/DebugAdapterProtocol.plantuml" + } + } + ] +} \ No newline at end of file diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/package-lock.json b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/package-lock.json new file mode 100644 index 000000000..97e607d53 --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/package-lock.json @@ -0,0 +1,63 @@ +{ + "name": "json-schema-2-api-protocol-generator", + "version": "0.0.1", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@types/node": { + "version": "16.11.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-16.11.6.tgz", + "integrity": "sha512-ua7PgUoeQFjmWPcoo9khiPum3Pd60k4/2ZGXt18sm2Slk0W0xZTqt5Y0Ny1NyBiN1EVQ/+FaF9NcY4Qe6rwk5w==", + "dev": true + }, + "fs": { + "version": "0.0.1-security", + "resolved": "https://registry.npmjs.org/fs/-/fs-0.0.1-security.tgz", + "integrity": "sha1-invTcYa23d84E/I4WLV+yq9eQdQ=" + }, + "fs-extra": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.0.0.tgz", + "integrity": "sha512-C5owb14u9eJwizKGdchcDUQeFtlSHHthBk8pbX9Vc1PFZrLombudjDnNns88aYslCyF6IY5SUw3Roz6xShcEIQ==", + "dev": true, + "requires": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + } + }, + "graceful-fs": { + "version": "4.2.8", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.8.tgz", + "integrity": "sha512-qkIilPUYcNhJpd33n0GBXTB1MMPp14TxEsEs0pTrsSVucApsYzW5V+Q8Qxhik6KU3evy+qkAAowTByymK0avdg==", + "dev": true + }, + "jsonfile": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.6", + "universalify": "^2.0.0" + } + }, + "process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=" + }, + "typescript": { + "version": "3.9.10", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.9.10.tgz", + "integrity": "sha512-w6fIxVE/H1PkLKcCPsFqKE7Kv7QUwhU8qQY2MueZXWx5cPZdwFupLgKK3vntcK98BtNHZtAF4LA/yl2a7k8R6Q==", + "dev": true + }, + "universalify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz", + "integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==", + "dev": true + } + } +} diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/package.json b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/package.json new file mode 100644 index 000000000..935f6d10f --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/package.json @@ -0,0 +1,32 @@ +{ + "name": "json-schema-2-api-protocol-generator", + "version": "0.0.1", + "description": "Typescript and Xtend/java Generator from json schema definition of a JSONRCP protocol", + "author": { + "name": "Inria", + "email": "didier.vojtisek@inria.fr" + }, + "private": true, + "repository": { + "type": "git", + "url": "https://github.com/eclipse/gemoc-studio-modeldebugging.git" + }, + "bugs": { + "url": "https://github.com/eclipse/gemoc-studio-modeldebugging/issues" + }, + "devDependencies": { + "@types/node": "^16.11.6", + "fs-extra": "^10.0.0", + "typescript": "^3.9.7" + }, + "scripts": { + "build": "tsc -p .", + "watch": "tsc -w -p .", + "generate": "node ./dist/Generator.js ./generator_config.json" + }, + "main": "./dist/Generator", + "dependencies": { + "fs": "^0.0.1-security", + "process": "^0.11.10" + } +} diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/Generator.ts b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/Generator.ts new file mode 100644 index 000000000..51470cec3 --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/Generator.ts @@ -0,0 +1,90 @@ +/*--------------------------------------------------------- + * Copyright (c) 2020 Inria and others.. All rights reserved. + *--------------------------------------------------------*/ + +'use strict'; + +import * as fs from 'fs'; +import * as path from 'path'; +//import {IProtocol, Protocol as P} from './json_schema'; +import {TSGeneratorModule} from './modules/TsAPIGenerator'; +import {JavaServerGeneratorModule} from './modules/JavaServerGenerator'; +import {XtendArgumentsGeneratorModule} from './modules/XtendArgumentsGenerator'; +import {JavaClientGeneratorModule} from './modules/JavaClientGenerator'; +import {PlantumlGeneratorModule} from './modules/plantumlGenerator'; + + +import * as pconf from './modules/generatorConfig' + +function ensureDirForFile(file : string) { + var dirName = path.dirname(file) + if (!fs.existsSync(dirName)) { + fs.mkdirSync(dirName, { + recursive: true + }); + } +} + + +/// Main +const protocolName = 'ModelExecutionServerProtocol'; + +var args = process.argv.slice(2); + +const protocolGenConfs : pconf.ProtocolGenConfigs = JSON.parse(fs.readFileSync(args[0]).toString()); + +protocolGenConfs.protocolGenConfigs.forEach(protocolGenConf => { + //console.table(protocolGenConf) + console.table(protocolGenConf, ["destFileName"]) + console.table(protocolGenConf, ["packageName", "Values"]) + let protocolSchema = JSON.parse(fs.readFileSync(protocolGenConf.protocolJSONSchemaPath).toString()); + + if(protocolGenConf.tsAPI != null) { + console.log("*****"); + console.log("***** Generate TS API for "+protocolGenConf.protocolName); + const emitTSStr = TSGeneratorModule(protocolGenConf.protocolName, protocolSchema); + ensureDirForFile(protocolGenConf.tsAPI.destFileName) + fs.writeFileSync(protocolGenConf.tsAPI.destFileName, emitTSStr, { encoding: 'utf-8'}); + console.info("Saved "+protocolGenConf.tsAPI.destFileName) + } + if(protocolGenConf.javaServer != null) { + console.log("*****"); + console.log("***** Generate I"+protocolGenConf.protocolName+"Server.java"); + const emitJavaServerStr = JavaServerGeneratorModule("I"+protocolGenConf.protocolName+"Server", + protocolGenConf.javaServer.packageName, + protocolSchema); + ensureDirForFile(protocolGenConf.javaServer.destFileName) + fs.writeFileSync(protocolGenConf.javaServer.destFileName, emitJavaServerStr, { encoding: 'utf-8'}); + console.info("Saved "+protocolGenConf.javaServer.destFileName) + } + if(protocolGenConf.javaClient != null) { + console.log("*****"); + console.log("***** Generate I"+protocolGenConf.protocolName+"Client.java"); + const emitJavaClientStr = JavaClientGeneratorModule("I"+protocolGenConf.protocolName+"Client", + protocolGenConf.javaClient.packageName, + protocolSchema); + + ensureDirForFile(protocolGenConf.javaClient.destFileName) + fs.writeFileSync(protocolGenConf.javaClient.destFileName, emitJavaClientStr, { encoding: 'utf-8'}); + console.info("Saved "+protocolGenConf.javaClient.destFileName) + } + if(protocolGenConf.javaAPI != null) { + console.log("*****"); + console.log("***** Generate I"+protocolGenConf.protocolName+"Data.xtend"); + const emitXtendArgumentsStr = XtendArgumentsGeneratorModule(protocolGenConf.protocolName+"Data", + protocolGenConf.javaAPI.packageName, + protocolSchema); + ensureDirForFile(protocolGenConf.javaAPI.destFileName) + fs.writeFileSync(protocolGenConf.javaAPI.destFileName, emitXtendArgumentsStr, { encoding: 'utf-8'}); + console.info("Saved "+protocolGenConf.javaAPI.destFileName) + } + if(protocolGenConf.plantuml != null) { + console.log("*****"); + console.log("***** Generate Plantuml for "+protocolGenConf.protocolName); + const emitTSStr = PlantumlGeneratorModule(protocolGenConf.protocolName, protocolSchema); + ensureDirForFile(protocolGenConf.plantuml.destFileName) + fs.writeFileSync(protocolGenConf.plantuml.destFileName, emitTSStr, { encoding: 'utf-8'}); + console.info("Saved "+protocolGenConf.plantuml.destFileName) + } + +}); \ No newline at end of file diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/GeneratorTester.ts b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/GeneratorTester.ts new file mode 100644 index 000000000..29df13f49 --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/GeneratorTester.ts @@ -0,0 +1,48 @@ +/*--------------------------------------------------------- + * Copyright (c) 2020 Inria and others.. All rights reserved. + *--------------------------------------------------------*/ + +'use strict'; + +import * as fs from 'fs'; +//import {IProtocol, Protocol as P} from './json_schema'; +import {TSGeneratorModule} from './modules/TsAPIGenerator'; +import {JavaServerGeneratorModule} from './modules/JavaServerGenerator'; +import {XtendArgumentsGeneratorModule} from './modules/XtendArgumentsGenerator'; +import {JavaClientGeneratorModule} from './modules/JavaClientGenerator'; + +/// Main + +const protocolName = 'ModelExecutionServerProtocol'; + +var args = process.argv.slice(2); + +const debugProtocolSchema = JSON.parse(fs.readFileSync(args[0]).toString()); + +console.table(debugProtocolSchema.definitions); + +console.log("**************************************************"); +console.log("***** Generate ModelExecutionTraceProtocol.ts ****"); +const emitTSStr = TSGeneratorModule('ModelExecutionTraceProtocol', debugProtocolSchema); +fs.writeFileSync(args[1], emitTSStr, { encoding: 'utf-8'}); + +console.log("***********************************************************"); +console.log("***** Generate IModelExecutionTraceProtocolServer.java ****"); +const emitJavaServerStr = JavaServerGeneratorModule('IModelExecutionTraceProtocolServer', + `org.eclipse.gemoc.trace.metp.addonbased.server.metp`, + debugProtocolSchema); +fs.writeFileSync(args[2], emitJavaServerStr, { encoding: 'utf-8'}); + +console.log("***********************************************************"); +console.log("***** Generate IModelExecutionTraceProtocolClient.java ****"); +const emitJavaClientStr = JavaClientGeneratorModule('IModelExecutionTraceProtocolClient', + `org.eclipse.gemoc.trace.metp.addonbased.server.metp`, + debugProtocolSchema); +fs.writeFileSync(args[3], emitJavaClientStr, { encoding: 'utf-8'}); + +console.log("**********************************************************"); +console.log("***** Generate IModelExecutionTraceProtocolData.xtend ****"); +const emitXtendArgumentsStr = XtendArgumentsGeneratorModule('ModelExecutionTraceProtocolData', + `org.eclipse.gemoc.trace.metp.addonbased.server.metp`, + debugProtocolSchema); +fs.writeFileSync(args[4], emitXtendArgumentsStr, { encoding: 'utf-8'}); diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/JavaClientGenerator.ts b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/JavaClientGenerator.ts new file mode 100644 index 000000000..3a5f3b6bd --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/JavaClientGenerator.ts @@ -0,0 +1,311 @@ +/*--------------------------------------------------------- + * Copyright (c) 2020 Inria and others.. All rights reserved. + *--------------------------------------------------------*/ + +'use strict'; + +//import * as fs from 'fs'; +import {IProtocol, Protocol as P} from './json_schema'; + +let numIndents = 0; + +export function JavaClientGeneratorModule(moduleName: string, basePackageName: string, schema: IProtocol): string { + + let s = ''; + s += line("/*---------------------------------------------------------------------------------------------"); + s += line(" * Copyright (c) 2020 Inria and others."); + s += line(" * All rights reserved. This program and the accompanying materials"); + s += line(" * are made available under the terms of the Eclipse Public License v1.0"); + s += line(" * which accompanies this distribution, and is available at"); + s += line(" * http://www.eclipse.org/legal/epl-v10.html"); + s += line(" *--------------------------------------------------------------------------------------------*/"); + s += line("/* GENERATED FILE, DO NOT MODIFY MANUALLY */"); + s += line(); + s += line("package "+basePackageName+".services;"); + s += line(); + + //s += line("import java.util.concurrent.CompletableFuture;"); + s += line("import org.eclipse.lsp4j.jsonrpc.services.JsonNotification;"); + s += line("import "+basePackageName+".data.*;"); + s += line(); + + //s += comment(schema.description); + s += comment({ description : 'Client interface for the model execution trace protocol.\nAuto-generated from json schema. Do not edit manually.'}); + + s += openBlock(`public interface ${moduleName}`); + + // for (let typeName in schema.definitions) { + // console.log(typeName); + // } + + //console.table(schema.definitions); + + for (let typeName in schema.definitions) { + + const d2 = schema.definitions[typeName]; + + let supertype: string = null; + if ((d2).allOf) { + const array = (d2).allOf; + for (let d of array) { + if ((d).$ref) { + supertype = getRef((d).$ref); + } else { + if(supertype == 'Event') { + //let eventName = typeName.replace(/(.*)Event$/, "$1"); // TODO find the real name of the command in the "command"" property rather than infer from typeName + + + s += EventInterface(typeName, d); + } + } + } + } + } + + s += closeBlock(); + s += line(); + + return s; +} + +function EventInterface(interfaceName: string, definition: P.Definition): string { + + let desc = definition.description; + let methodName = ""; + if (definition.properties && definition.properties.event && definition.properties.event['enum']) { + const eventName = `${definition.properties.event['enum'][0]}`; + methodName = eventName; + if (eventName) { + desc = `Event message for '${eventName}' event type.\n${desc}`; + } + } else if (definition.properties && definition.properties.command && definition.properties.command['enum']) { + const eventName = `${definition.properties.command['enum'][0]}`; + methodName = eventName; + if (eventName) { + const EventtName = eventName[0].toUpperCase() + eventName.substr(1); + desc = `${EventtName} event; value of command field is '${eventName}'.\n${desc}`; + } + } + let s = line(); + s += comment({ description : desc }); + + s += line("@JsonNotification"); + + + + var argsString : string[] = []; + + if(definition.properties['body']){ + argsString.push(`${interfaceName}Arguments args`); + } + + + /*for (let propName in definition.properties) { + + const type = propertyType(definition.properties[propName]); + const propertyDef = `${type} ${propName}`; + if (type[0] === '\'' && type[type.length-1] === '\'' && type.indexOf('|') < 0) { + //s += line(`// ${propertyDef};`); + } else { + argsString.push(`${propertyDef}`); + } + }*/ + + s += openBlock(`default void ${methodName}(`+argsString.join(', ')+`)`); + s += line(`throw new UnsupportedOperationException();`) + s += closeBlock(); + return s; +} + + +function Enum(typeName: string, definition: P.StringType): string { + let s = line(); + s += comment(definition); + const x = enumAsOrType(definition.enum); + s += line(`export type ${typeName} = ${x};`); + return s; +} + +function enumAsOrType(enm: string[]) { + return enm.map(v => `'${v}'`).join(' | '); +} + +function comment(c: P.Commentable): string { + + let description = c.description || ''; + + if ((c).items) { // array + c = (c).items; + } + + // a 'closed' enum with individual descriptions + if (c.enum && c.enumDescriptions) { + for (let i = 0; i < c.enum.length; i++) { + description += `\n'${c.enum[i]}': ${c.enumDescriptions[i]}`; + } + } + + // an 'open' enum + if (c._enum) { + description += '\nValues: '; + if (c.enumDescriptions) { + for (let i = 0; i < c._enum.length; i++) { + description += `\n'${c._enum[i]}': ${c.enumDescriptions[i]}`; + } + description += '\netc.'; + } else { + description += `${c._enum.map(v => `'${v}'`).join(', ')}, etc.`; + } + } + + if (description) { + description = description.replace(/(.*)<\/code>/g, "'$1'"); + numIndents++; + description = description.replace(/\n/g, '\n' + indent()); + numIndents--; + if (description.indexOf('\n') >= 0) { + return line(`/** ${description}\n${indent()}*/`); + } else { + return line(`/** ${description} */`); + } + } + return ''; +} + +function openBlock(str: string, openChar?: string, indent?: boolean): string { + indent = typeof indent === 'boolean' ? indent : true; + openChar = openChar || ' {'; + let s = line(`${str}${openChar}`, true, indent); + numIndents++; + return s; +} + +function closeBlock(closeChar?: string, newline?: boolean): string { + newline = typeof newline === 'boolean' ? newline : true; + closeChar = closeChar || '}'; + numIndents--; + return line(closeChar, newline); +} + +function propertyType(prop: any): string { + if (prop.$ref) { + return getRef(prop.$ref); + } + switch (prop.type) { + case 'array': + const s = propertyType(prop.items); + if (s.indexOf(' ') >= 0) { + return `(${s})[]`; + } + return `${s}[]`; + case 'object': + return objectType(prop); + case 'string': + if (prop.enum) { + return enumAsOrType(prop.enum); + } + return `String`; + case 'integer': + return 'Integer'; + } + if (Array.isArray(prop.type)) { + if (prop.type.length === 7 && prop.type.sort().join() === 'array,boolean,integer,null,number,object,string') { // silly way to detect all possible json schema types + return 'Object'; + } else { + return prop.type.map(v => v === 'integer' ? 'Integer' : v).join(' | '); + } + } + return prop.type; +} + +function objectType(prop: any): string { + if (prop.properties) { + let s = openBlock('', '{', false); + + for (let propName in prop.properties) { + const required = prop.required ? prop.required.indexOf(propName) >= 0 : false; + s += property(propName, !required, prop.properties[propName]); + } + + s += closeBlock('}', false); + return s; + } + if (prop.additionalProperties) { + return `{ [key: string]: ${orType(prop.additionalProperties.type)}; }`; + } + return '{}'; +} + +function orType(enm: string | string[]): string { + if (typeof enm === 'string') { + return enm; + } + return enm.join(' | '); +} + +function requestArg(name: string, prop: P.PropertyType): string { + let s = ''; + s += comment(prop); + const type = propertyType(prop); + const propertyDef = `${type} ${name}`; + if (type[0] === '\'' && type[type.length-1] === '\'' && type.indexOf('|') < 0) { + s += line(`// ${propertyDef};`); + } else { + s += line(`${propertyDef};`); + } + return s; +} + +function property(name: string, optional: boolean, prop: P.PropertyType): string { + let s = ''; + s += comment(prop); + const type = propertyType(prop); + const propertyDef = `${name}${optional ? '?' : ''}: ${type}`; + if (type[0] === '\'' && type[type.length-1] === '\'' && type.indexOf('|') < 0) { + s += line(`// ${propertyDef};`); + } else { + s += line(`${propertyDef};`); + } + return s; +} + +function getRef(ref: string): string { + const REXP = /#\/(.+)\/(.+)/; + const matches = REXP.exec(ref); + if (matches && matches.length === 3) { + return matches[2]; + } + console.log('error: ref'); + return ref; +} + +function indent(): string { + return '\t'.repeat(numIndents); +} + +function line(str?: string, newline?: boolean, indnt?: boolean): string { + newline = typeof newline === 'boolean' ? newline : true; + indnt = typeof indnt === 'boolean' ? indnt : true; + let s = ''; + if (str) { + if (indnt) { + s += indent(); + } + s += str; + } + if (newline) { + s += '\n'; + } + return s; +} + + +/// Main + +/* +const debugProtocolSchema = JSON.parse(fs.readFileSync('./ModelExecutionTraceProtocol.json').toString()); + +const emitStr = TSGeneratorModule('ModelExecutionTraceProtocol', debugProtocolSchema); + +fs.writeFileSync(`../metp_protocol/src/ModelExecutionTraceProtocol.ts`, emitStr, { encoding: 'utf-8'}); +*/ diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/JavaServerGenerator.ts b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/JavaServerGenerator.ts new file mode 100644 index 000000000..db51d3c86 --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/JavaServerGenerator.ts @@ -0,0 +1,331 @@ +/*--------------------------------------------------------- + * Copyright (c) 2020 Inria and others.. All rights reserved. + *--------------------------------------------------------*/ + +'use strict'; + +//import * as fs from 'fs'; +import {IProtocol, Protocol as P} from './json_schema'; +import {ResponseHelper, getJavaSafeName, capitalizeFirstLetter, isJavaKeyWord} from './json_schemaHelpers' + +let numIndents = 0; + +export function JavaServerGeneratorModule(moduleName: string, basePackageName: string, schema: IProtocol): string { + + let s = ''; + s += line("/*---------------------------------------------------------------------------------------------"); + s += line(" * Copyright (c) 2020 Inria and others."); + s += line(" * All rights reserved. This program and the accompanying materials"); + s += line(" * are made available under the terms of the Eclipse Public License v1.0"); + s += line(" * which accompanies this distribution, and is available at"); + s += line(" * http://www.eclipse.org/legal/epl-v10.html"); + s += line(" *--------------------------------------------------------------------------------------------*/"); + s += line("/* GENERATED FILE, DO NOT MODIFY MANUALLY */"); + s += line(); + s += line("package "+basePackageName+".services;"); + s += line(); + + s += line("import com.google.gson.annotations.SerializedName;"); + s += line("import java.util.concurrent.CompletableFuture;"); + s += line("import org.eclipse.lsp4j.jsonrpc.services.JsonRequest;"); + + s += line("import "+basePackageName+".data.*;"); + // TODO add the other imports individually + + //s += comment(schema.description); + s += comment({ description : 'Server interface for the model execution trace protocol.\nAuto-generated from json schema. Do not edit manually.'}); + + s += openBlock(`public interface ${moduleName}`); + + // for (let typeName in schema.definitions) { + // console.log(typeName); + // } + + //console.table(schema.definitions); + + for (let typeName in schema.definitions) { + + const d2 = schema.definitions[typeName]; + + let supertype: string = null; + if ((d2).allOf) { + const array = (d2).allOf; + for (let d of array) { + if ((d).$ref) { + supertype = getRef((d).$ref); + } else { + if(supertype == 'Request') { + let requestName = typeName.replace(/(.*)Request$/, "$1"); // TODO find the real name of the command in the "command"" property rather than infer from typeName + let responseDefTypeName = typeName.replace(/(.*)Request$/, "$1Response"); // TODO do we have a better way to find the response from the request in the json schema ? + let responseDefType = schema.definitions[responseDefTypeName]; + var responseDef : P.Definition + for (let respDef of (responseDefType).allOf) { + if ((respDef).$ref) { + } else { + responseDef = respDef; + } + } + const response : ResponseHelper = new ResponseHelper(responseDefTypeName, responseDef); + + s += RequestInterface(requestName, d, response); + } + } + } + } + } + + s += closeBlock(); + s += line(); + + return s; +} + +//function RequestInterface(interfaceName: string, definition: P.Definition, responsedefinition: P.Definition): string { +function RequestInterface(interfaceName: string, definition: P.Definition, responseHelper: ResponseHelper): string { + let desc = definition.description; + let methodName = ""; + if (definition.properties && definition.properties.event && definition.properties.event['enum']) { + const eventName = `${definition.properties.event['enum'][0]}`; + methodName = eventName; + if (eventName) { + desc = `Event message for '${eventName}' event type.\n${desc}`; + } + } else if (definition.properties && definition.properties.command && definition.properties.command['enum']) { + const requestName = `${definition.properties.command['enum'][0]}`; + methodName = requestName; + if (requestName) { + const RequestName = requestName[0].toUpperCase() + requestName.substr(1); + desc = `${RequestName} request; value of command field is '${requestName}'.\n${desc}`; + } + } + let s = line(); + s += comment({ description : desc }); + + s += line("@JsonRequest"); + // find response type + var returnType = 'CompletableFuture'; + + if(responseHelper.responseDef && responseHelper.responseDef.properties && responseHelper.responseDef.properties.body){ + /*console.log(interfaceName+': responsedefinition = '+responsedefinition.properties.body); + console.log(responsedefinition.properties.body); + console.table(responsedefinition.properties.body); + console.table(argumentType(responsedefinition.properties.body));*/ + + if(responseHelper.responseDef.properties.body.type === 'object'){ + returnType = "CompletableFuture<"+responseHelper.responseDefTypeName+">"; + } else { + returnType = "CompletableFuture<"+propertyType(responseHelper.responseDef.properties.body)+">"; + } + } + var argsString : string[] = []; + for (let propName in definition.properties) { + + const type = propertyType(definition.properties[propName]); + const propertyDef = `${type} ${propName}`; + if (type[0] === '\'' && type[type.length-1] === '\'' && type.indexOf('|') < 0) { + //s += line(`// ${propertyDef};`); + } else { + argsString.push(`${propertyDef}`); + } + } + if(isJavaKeyWord(methodName)){ + s += line(`@SerializedName("${methodName}")`); + } + s += openBlock(`default ${returnType} ${getJavaSafeName(methodName)}(`+argsString.join(', ')+`)`); + s += line(`throw new UnsupportedOperationException();`) + s += closeBlock(); + return s; +} + + +function Enum(typeName: string, definition: P.StringType): string { + let s = line(); + s += comment(definition); + const x = enumAsOrType(definition.enum); + s += line(`export type ${typeName} = ${x};`); + return s; +} + +function enumAsOrType(enm: string[]) { + return enm.map(v => `'${v}'`).join(' | '); +} + +function comment(c: P.Commentable): string { + + let description = c.description || ''; + + if ((c).items) { // array + c = (c).items; + } + + // a 'closed' enum with individual descriptions + if (c.enum && c.enumDescriptions) { + for (let i = 0; i < c.enum.length; i++) { + description += `\n'${c.enum[i]}': ${c.enumDescriptions[i]}`; + } + } + + // an 'open' enum + if (c._enum) { + description += '\nValues: '; + if (c.enumDescriptions) { + for (let i = 0; i < c._enum.length; i++) { + description += `\n'${c._enum[i]}': ${c.enumDescriptions[i]}`; + } + description += '\netc.'; + } else { + description += `${c._enum.map(v => `'${v}'`).join(', ')}, etc.`; + } + } + + if (description) { + description = description.replace(/(.*)<\/code>/g, "'$1'"); + numIndents++; + description = description.replace(/\n/g, '\n' + indent()); + numIndents--; + if (description.indexOf('\n') >= 0) { + return line(`/** ${description}\n${indent()}*/`); + } else { + return line(`/** ${description} */`); + } + } + return ''; +} + +function openBlock(str: string, openChar?: string, indent?: boolean): string { + indent = typeof indent === 'boolean' ? indent : true; + openChar = openChar || ' {'; + let s = line(`${str}${openChar}`, true, indent); + numIndents++; + return s; +} + +function closeBlock(closeChar?: string, newline?: boolean): string { + newline = typeof newline === 'boolean' ? newline : true; + closeChar = closeChar || '}'; + numIndents--; + return line(closeChar, newline); +} + +function propertyType(prop: any): string { + if (prop.$ref) { + return getRef(prop.$ref); + } + switch (prop.type) { + case 'array': + const s = propertyType(prop.items); + if (s.indexOf(' ') >= 0) { + return `(${s})[]`; + } + return `${s}[]`; + case 'object': + return objectType(prop); + case 'string': + if (prop.enum) { + return enumAsOrType(prop.enum); + } + return `String`; + case 'integer': + return 'Integer'; + } + if (Array.isArray(prop.type)) { + if (prop.type.length === 7 && prop.type.sort().join() === 'array,boolean,integer,null,number,object,string') { // silly way to detect all possible json schema types + return 'Object'; + } else { + return prop.type.map(v => v === 'integer' ? 'Integer' : v).join(' | '); + } + } + return prop.type; +} + +function objectType(prop: any): string { + if (prop.properties) { + let s = openBlock('', '{', false); + + for (let propName in prop.properties) { + const required = prop.required ? prop.required.indexOf(propName) >= 0 : false; + s += property(propName, !required, prop.properties[propName]); + } + + s += closeBlock('}', false); + return s; + } + if (prop.additionalProperties) { + return `{ [key: string]: ${orType(prop.additionalProperties.type)}; }`; + } + return '{}'; +} + +function orType(enm: string | string[]): string { + if (typeof enm === 'string') { + return enm; + } + return enm.join(' | '); +} + +function requestArg(name: string, prop: P.PropertyType): string { + let s = ''; + s += comment(prop); + const type = propertyType(prop); + const propertyDef = `${type} ${name}`; + if (type[0] === '\'' && type[type.length-1] === '\'' && type.indexOf('|') < 0) { + s += line(`// ${propertyDef};`); + } else { + s += line(`${propertyDef};`); + } + return s; +} + +function property(name: string, optional: boolean, prop: P.PropertyType): string { + let s = ''; + s += comment(prop); + const type = propertyType(prop); + const propertyDef = `${name}${optional ? '?' : ''}: ${type}`; + if (type[0] === '\'' && type[type.length-1] === '\'' && type.indexOf('|') < 0) { + s += line(`// ${propertyDef};`); + } else { + s += line(`${propertyDef};`); + } + return s; +} + +function getRef(ref: string): string { + const REXP = /#\/(.+)\/(.+)/; + const matches = REXP.exec(ref); + if (matches && matches.length === 3) { + return matches[2]; + } + console.log('error: ref'); + return ref; +} + +function indent(): string { + return '\t'.repeat(numIndents); +} + +function line(str?: string, newline?: boolean, indnt?: boolean): string { + newline = typeof newline === 'boolean' ? newline : true; + indnt = typeof indnt === 'boolean' ? indnt : true; + let s = ''; + if (str) { + if (indnt) { + s += indent(); + } + s += str; + } + if (newline) { + s += '\n'; + } + return s; +} + + +/// Main + +/* +const debugProtocolSchema = JSON.parse(fs.readFileSync('./ModelExecutionTraceProtocol.json').toString()); + +const emitStr = TSGeneratorModule('ModelExecutionTraceProtocol', debugProtocolSchema); + +fs.writeFileSync(`../metp_protocol/src/ModelExecutionTraceProtocol.ts`, emitStr, { encoding: 'utf-8'}); +*/ diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/TsAPIGenerator.ts b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/TsAPIGenerator.ts new file mode 100644 index 000000000..8ac6f298b --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/TsAPIGenerator.ts @@ -0,0 +1,282 @@ +/*--------------------------------------------------------- + * Copyright (c) 2020 Inria and others.. All rights reserved. + *--------------------------------------------------------*/ + + +// inspired from https://github.com/microsoft/vscode-debugadapter-node/blob/main/src/generator.ts + +'use strict'; + +//import * as fs from 'fs'; +import {IProtocol, Protocol as P} from './json_schema'; + +let numIndents = 0; + +export function TSGeneratorModule(moduleName: string, schema: IProtocol): string { + + let s = ''; + s += line("/*---------------------------------------------------------------------------------------------"); + s += line(" * Copyright (c) 2020 Inria and others."); + s += line(" * All rights reserved. This program and the accompanying materials"); + s += line(" * are made available under the terms of the Eclipse Public License v1.0"); + s += line(" * which accompanies this distribution, and is available at"); + s += line(" * http://www.eclipse.org/legal/epl-v10.html"); + s += line(" *--------------------------------------------------------------------------------------------*/"); + s += line("/* GENERATED FILE, DO NOT MODIFY MANUALLY */"); + s += line(); + s += line("'use strict';"); + s += line(); + + //s += comment(schema.description); + s += comment({ description : 'Declaration module describing the model execution trace protocol.\nAuto-generated from json schema. Do not edit manually.'}); + + s += openBlock(`export module ${moduleName}`); + + for (let typeName in schema.definitions) { + + const d2 = schema.definitions[typeName]; + + let supertype: string = null; + if ((d2).allOf) { + const array = (d2).allOf; + for (let d of array) { + if ((d).$ref) { + supertype = getRef((d).$ref); + } else { + s += Interface(typeName, d, supertype); + } + } + } else { + if ((d2).enum) { + s += Enum(typeName, d2); + } else { + s += Interface(typeName, d2); + } + } + } + + s += closeBlock(); + s += line(); + + return s; +} + +function Interface(interfaceName: string, definition: P.Definition, superType?: string): string { + + let desc = definition.description; + + if (definition.properties && definition.properties.event && definition.properties.event['enum']) { + const eventName = `${definition.properties.event['enum'][0]}`; + if (eventName) { + desc = `Event message for '${eventName}' event type.\n${desc}`; + } + } else if (definition.properties && definition.properties.command && definition.properties.command['enum']) { + const requestName = `${definition.properties.command['enum'][0]}`; + if (requestName) { + const RequestName = requestName[0].toUpperCase() + requestName.substr(1); + desc = `${RequestName} request; value of command field is '${requestName}'.\n${desc}`; + } + } + + let s = line(); + + s += comment({ description : desc }); + + let x = `export interface ${interfaceName}`; + if (superType) { + x += ` extends ${superType}`; + } + s += openBlock(x); + + for (let propName in definition.properties) { + const required = definition.required ? definition.required.indexOf(propName) >= 0 : false; + s += property(propName, !required, definition.properties[propName]); + } + + s += closeBlock(); + + return s; +} + +function Enum(typeName: string, definition: P.StringType): string { + let s = line(); + s += comment(definition); + const x = enumAsOrType(definition.enum); + s += line(`export type ${typeName} = ${x};`); + return s; +} + +function enumAsOrType(enm: string[]) { + return enm.map(v => `'${v}'`).join(' | '); +} + +function comment(c: P.Commentable): string { + + let description = c.description || ''; + + if ((c).items) { // array + c = (c).items; + } + + // a 'closed' enum with individual descriptions + if (c.enum && c.enumDescriptions) { + for (let i = 0; i < c.enum.length; i++) { + description += `\n'${c.enum[i]}': ${c.enumDescriptions[i]}`; + } + } + + // an 'open' enum + if (c._enum) { + description += '\nValues: '; + if (c.enumDescriptions) { + for (let i = 0; i < c._enum.length; i++) { + description += `\n'${c._enum[i]}': ${c.enumDescriptions[i]}`; + } + description += '\netc.'; + } else { + description += `${c._enum.map(v => `'${v}'`).join(', ')}, etc.`; + } + } + + if (description) { + description = description.replace(/(.*)<\/code>/g, "'$1'"); + numIndents++; + description = description.replace(/\n/g, '\n' + indent()); + numIndents--; + if (description.indexOf('\n') >= 0) { + return line(`/** ${description}\n${indent()}*/`); + } else { + return line(`/** ${description} */`); + } + } + return ''; +} + +function openBlock(str: string, openChar?: string, indent?: boolean): string { + indent = typeof indent === 'boolean' ? indent : true; + openChar = openChar || ' {'; + let s = line(`${str}${openChar}`, true, indent); + numIndents++; + return s; +} + +function closeBlock(closeChar?: string, newline?: boolean): string { + newline = typeof newline === 'boolean' ? newline : true; + closeChar = closeChar || '}'; + numIndents--; + return line(closeChar, newline); +} + +function propertyType(prop: any): string { + if (prop.$ref) { + return getRef(prop.$ref); + } + if (Array.isArray(prop.oneOf)) { + return (prop.oneOf as any[]).map(t => propertyType(t)).join(' | ') + } + switch (prop.type) { + case 'array': + const s = propertyType(prop.items); + if (s.indexOf(' ') >= 0) { + return `(${s})[]`; + } + return `${s}[]`; + case 'object': + return objectType(prop); + case 'string': + if (prop.enum) { + return enumAsOrType(prop.enum); + } + return `string`; + case 'integer': + return 'number'; + } + if (Array.isArray(prop.type)) { + if (prop.type.length === 7 && prop.type.sort().join() === 'array,boolean,integer,null,number,object,string') { // silly way to detect all possible json schema types + return 'any'; + } else { + return prop.type.map(v => v === 'integer' ? 'number' : v).join(' | '); + } + } + return prop.type; +} + +function objectType(prop: any): string { + if (prop.properties) { + let s = openBlock('', '{', false); + + for (let propName in prop.properties) { + const required = prop.required ? prop.required.indexOf(propName) >= 0 : false; + s += property(propName, !required, prop.properties[propName]); + } + + s += closeBlock('}', false); + return s; + } + if (prop.additionalProperties) { + return `{ [key: string]: ${orType(prop.additionalProperties.type)}; }`; + } + return '{}'; +} + +function orType(enm: string | string[]): string { + if (typeof enm === 'string') { + return enm; + } + return enm.join(' | '); +} + +function property(name: string, optional: boolean, prop: P.PropertyType): string { + let s = ''; + s += comment(prop); + const type = propertyType(prop); + //console.log('property() name='+name+' prop='+prop+' type='+type); + const propertyDef = `${name}${optional ? '?' : ''}: ${type}`; + if (type[0] === '\'' && type[type.length-1] === '\'' && type.indexOf('|') < 0) { + s += line(`// ${propertyDef};`); + } else { + s += line(`${propertyDef};`); + } + return s; +} + +function getRef(ref: string): string { + const REXP = /#\/(.+)\/(.+)/; + const matches = REXP.exec(ref); + if (matches && matches.length === 3) { + return matches[2]; + } + console.log('error: ref'); + return ref; +} + +function indent(): string { + return '\t'.repeat(numIndents); +} + +function line(str?: string, newline?: boolean, indnt?: boolean): string { + newline = typeof newline === 'boolean' ? newline : true; + indnt = typeof indnt === 'boolean' ? indnt : true; + let s = ''; + if (str) { + if (indnt) { + s += indent(); + } + s += str; + } + if (newline) { + s += '\n'; + } + return s; +} + + +/// Main + +/* +const debugProtocolSchema = JSON.parse(fs.readFileSync('./ModelExecutionTraceProtocol.json').toString()); + +const emitStr = TSGeneratorModule('ModelExecutionTraceProtocol', debugProtocolSchema); + +fs.writeFileSync(`../metp_protocol/src/ModelExecutionTraceProtocol.ts`, emitStr, { encoding: 'utf-8'}); +*/ diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/XtendArgumentsGenerator.ts b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/XtendArgumentsGenerator.ts new file mode 100644 index 000000000..84843e860 --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/XtendArgumentsGenerator.ts @@ -0,0 +1,396 @@ + +/*--------------------------------------------------------- + * Copyright (c) 2020 Inria and others.. All rights reserved. + *--------------------------------------------------------*/ + +'use strict'; + +import {IProtocol, Protocol as P } from './json_schema'; +import {PropertyHelper, getJavaSafeName, capitalizeFirstLetter, isJavaKeyWord} from './json_schemaHelpers' + +let numIndents = 0; + +export function XtendArgumentsGeneratorModule(moduleName: string, basePackageName: string, schema: IProtocol): string { + + let s = ''; + s += line("/*---------------------------------------------------------------------------------------------"); + s += line(" * Copyright (c) 2020 Inria and others."); + s += line(" * All rights reserved. This program and the accompanying materials"); + s += line(" * are made available under the terms of the Eclipse Public License v1.0"); + s += line(" * which accompanies this distribution, and is available at"); + s += line(" * http://www.eclipse.org/legal/epl-v10.html"); + s += line(" *--------------------------------------------------------------------------------------------*/"); + s += line("/* GENERATED FILE, DO NOT MODIFY MANUALLY */"); + s += line(); + s += line("package "+basePackageName+".data;"); + s += line(); + + s += line("import com.google.gson.annotations.SerializedName"); + s += line("import java.util.Map"); + s += line("import org.eclipse.lsp4j.generator.JsonRpcData"); + s += line("import org.eclipse.lsp4j.jsonrpc.messages.Either"); + s += line("import org.eclipse.lsp4j.jsonrpc.validation.NonNull"); + s += line(); + s += comment({ description : `Declaration of data classes and enum for the ${moduleName}.\nAuto-generated from json schema. Do not edit manually.`}); + + for (let typeName in schema.definitions) { + + const d2 = schema.definitions[typeName]; + + let supertype: string = null; + if ((d2).allOf) { + // all definition with inheritances + const array = (d2).allOf; + for (let d of array) { + if ((d).$ref) { + supertype = getRef((d).$ref); + } else { + + // ignore generic Json RPC data + // Request, Event, Response, ErrorResponse + + if( typeName != 'Request' && typeName != 'Event' && typeName != 'Response' && typeName != 'ErrorResponse') { + if(supertype == 'Response') { + // let's create the data' + //console.log(`create interface for Response ${typeName}`); + if(( d).properties && ( d).properties['body']){ + s += MessageInterface(typeName, ( d).properties['body']); + } else { + s += MessageInterface(typeName, d); + } + } else if(supertype == 'Event') { + // let's create the data' + //console.log(`create interface for Event ${typeName}`); + //console.log(( d).properties['body']); + if(( d).properties['body']){ + s += MessageInterface(typeName+"Arguments", ( d).properties['body']); + } + //s += MessageInterface(typeName, d); + } else if(supertype !== 'Request'){ + s += MessageInterface(typeName, d); + } else { + console.log("Ignore1 "+typeName+ " with supertype="+supertype); + } + } else { + console.log("Ignore2 "+typeName); + } + } + } + } else { + // arguments + //console.log('not allOf ' + typeName); + //console.log(d2); + //s += MessageInterface(typeName, d); + if ((d2).enum) { + s += Enum(typeName, d2); + } else { + if(typeName != 'ProtocolMessage') { + s += MessageInterface(typeName, d2); + } else { + console.log("Ignore3 "+typeName); + } + } + } + } + +// s += closeBlock(); + s += line(); + + return s; +} + +function MessageInterface(interfaceName: string, definition: P.Definition): string { + + let desc = definition.description; + if (definition.properties && definition.properties.event && definition.properties.event['enum']) { + const eventName = `${definition.properties.event['enum'][0]}`; + if (eventName) { + desc = `Event message for '${eventName}' event type.\n${desc}`; + } + } else if (definition.properties && definition.properties.command && definition.properties.command['enum']) { + const requestName = `${definition.properties.command['enum'][0]}`; + if (requestName) { + const RequestName = requestName[0].toUpperCase() + requestName.substr(1); + desc = `${RequestName} request; value of command field is '${requestName}'.\n${desc}`; + } + } + let s = line(); + s += comment({ description : desc }); + + s += line("@JsonRpcData"); + + s += openBlock(`class ${interfaceName} `); +/* s += line(`throw new UnsupportedOperationException();`)*/ + for (let propName in definition.properties) { + const required = definition.required ? definition.required.indexOf(propName) >= 0 : false; + const propertyHelper: PropertyHelper = new PropertyHelper(interfaceName, propName, definition.properties[propName]); + s += property(!required, propertyHelper); + } + s += closeBlock(); + + // TODO property Enum Special classes + + for (let propName in definition.properties) { + const required = definition.required ? definition.required.indexOf(propName) >= 0 : false; + const propertyHelper: PropertyHelper = new PropertyHelper(interfaceName, propName, definition.properties[propName]); + s += propertySpecificTypeDef(propertyHelper); + } + return s; +} + + + +function Enum(typeName: string, definition: P.StringType): string { + let s = line(); + let commentableProp = definition; + s += comment(definition); + //const x = enumAsOrType(definition.enum); + s += line(`enum ${typeName} {`); + numIndents++; + s += line(definition.enum.map((v, index) => { + let comment = ''; + if (commentableProp.enumDescriptions && commentableProp.enumDescriptions.length > index) { + comment = formatDescription(commentableProp.enumDescriptions[index]); + } + return `${comment}${indent()}@SerializedName("${v}")\n${indent()}${EnumLiteralStringToJavaEnumLiteralString(v)}`; + }).join(`,\n`)); + + + numIndents--; + s += line('}') + + + return s; +} + +// function enumAsOrType(enm: string[]) { +// return enm.map(v => `'${v}'`).join(' | '); +// } + +// function enumAsDedicatedType(hostDefinitionName: string, propertyName: string) { +// return hostDefinitionName+capitalizeFirstLetter(propertyName); +// } + +function comment(c: P.Commentable): string { + + let description = c.description || ''; + + if ((c).items) { // array + c = (c).items; + } + + // a 'closed' enum with individual descriptions + if (c.enum && c.enumDescriptions) { + for (let i = 0; i < c.enum.length; i++) { + description += `\n'${c.enum[i]}': ${c.enumDescriptions[i]}`; + } + } + + // an 'open' enum + if (c._enum) { + description += '\nValues: '; + if (c.enumDescriptions) { + for (let i = 0; i < c._enum.length; i++) { + description += `\n'${c._enum[i]}': ${c.enumDescriptions[i]}`; + } + description += '\netc.'; + } else { + description += `${c._enum.map(v => `'${v}'`).join(', ')}, etc.`; + } + } + + if (description) { + description = description.replace(/(.*)<\/code>/g, "'$1'"); + numIndents++; + description = description.replace(/\n/g, '\n' + indent()); + numIndents--; + if (description.indexOf('\n') >= 0) { + return line(`/** ${description}\n${indent()}*/`); + } else { + return line(`/** ${description} */`); + } + } + return ''; +} + +function formatDescription(description: string) { + description = description.replace(/(.*)<\/code>/g, "'$1'"); + numIndents++; + description = description.replace(/\n/g, '\n' + indent()); + numIndents--; + if (description.indexOf('\n') >= 0) { + return line(`/** ${description}\n${indent()} */`); + } else { + return line(`/** ${description} */`); + } +} + +function openBlock(str: string, openChar?: string, indent?: boolean): string { + indent = typeof indent === 'boolean' ? indent : true; + openChar = openChar || ' {'; + let s = line(`${str}${openChar}`, true, indent); + numIndents++; + return s; +} + +function closeBlock(closeChar?: string, newline?: boolean): string { + newline = typeof newline === 'boolean' ? newline : true; + closeChar = closeChar || '}'; + numIndents--; + return line(closeChar, newline); +} + +function property(optional: boolean, propertyHelper: PropertyHelper) { + let s = ''; + s += comment(propertyHelper.propertyType as P.PropertyType); + const typeName = propertyHelper.propertyTypeOrRefJavaName() + //const type = propertyTypeOrRef(hostDefinitionName, propertyName, prop); + + const propertyDef = `${typeName} ${getJavaSafeName(propertyHelper.propertyName)}`; + //console.table(prop) + if (typeName[0] === '\'' && typeName[typeName.length-1] === '\'' && typeName.indexOf('|') < 0) { + s += line(`// ${propertyDef};`); + } else { + if(!optional) { + s += line('// @NonNull'); + } + if(isJavaKeyWord(propertyHelper.propertyName)){ + s += line(`@SerializedName("${propertyHelper.propertyName}")`); + } + s += line(`${propertyDef};`); + } + return s; +} + +// Class or Enum definition coming from property that declares a new Type (enum or class with static Strings) +function propertySpecificTypeDef(propertyHelper: PropertyHelper): string { + + let s = ''; + const prop = propertyHelper.propertyType as P.PropertyType + if (Array.isArray(prop.type)) { + if (prop.type.length === 7 && prop.type.sort().join() === 'array,boolean,integer,null,number,object,string') { // silly way to detect all possible json schema types + s+= '// Object'; + } else { + s+= '// '+ prop.type.map(v => v === 'integer' ? 'Integer' : v).join(' | '); + } + } else { + switch (prop.type) { + case 'array': + // const s2 = propertyTypeOrRef(hostDefinitionName, propertyName, prop.items); + // if (s2.indexOf(' ') >= 0) { + // s+= '// '+ `(${s2})[]`; + // } else { + // s += '// '+ `${s2}[]`; + // } + s += `// TODO deal with array propertytype for ${propertyHelper.propertyName}`; + break; + case 'object': + //s += '// '+ objectType(hostDefinitionName, prop); + + s += `// TODO deal with object propertytype for ${propertyHelper.propertyName}`; + break; + case 'string': + let commentableProp = prop; + let description = prop.description || ''; + if (commentableProp.enum) { + // a 'closed' enum + s += line(`/** ${description}\n${indent()}*/`); + s += line('enum ' + propertyHelper.getDedicatedTypeJavaName() + ' {') + s += line(); + numIndents++; + s += line(prop.enum.map((v, index) => { + let comment = ''; + if (commentableProp.enumDescriptions && commentableProp.enumDescriptions.length > index) { + // ${commentableProp.enumDescriptions[i]}` + comment = formatDescription(commentableProp.enumDescriptions[index]); + // comment = "/** "+commentableProp.enumDescriptions[index]+' */\n'+indent(); + // comment = comment.replace(/\n/g, '\n' + indent()); + } + return `${comment}${indent()}@SerializedName("${v}")\n${indent()}${EnumLiteralStringToJavaEnumLiteralString(v)}`; + }).join(`,\n`)); + numIndents--; + s += line('}') + } else if (commentableProp._enum) { + // an 'open' enum + s += line(`/** ${description}\n${indent()}*/`); + s += line('interface ' + propertyHelper.getDedicatedTypeJavaName() + ' {'); + numIndents++; + s += line(prop._enum.map(v => `public static final String ${EnumLiteralStringToJavaEnumLiteralString(v)} = "${v}";`) + .join(`\n${indent()}`)); + numIndents--; + s += line('}') + } else { + s += '// '+ `String`; + } + break; + case 'integer': + s += '// '+ 'Integer'; + break; + default: + s += '// '+ prop.type; + } + } + s += line(); + + return s; +} + + +/** + * + * @param string Convert the string of the enum literal into Java Enume literal + * Ie. remplace whitespace by '_' + * uppercase + * replace camel case by snake case + * @returns + */ +function EnumLiteralStringToJavaEnumLiteralString(s: string) { + s = s.replace(" ", "_"); + s = s.split(/(?=[A-Z])/).join('_'); + return s.toUpperCase() ; +} + +// function capitalizeFirstLetter(s: string) { +// return s.charAt(0).toUpperCase() + s.slice(1); +// } + +function getRef(ref: string): string { + const REXP = /#\/(.+)\/(.+)/; + const matches = REXP.exec(ref); + if (matches && matches.length === 3) { + return matches[2]; + } + console.log('error: ref'); + return ref; +} + +function indent(): string { + return '\t'.repeat(numIndents); +} + +function line(str?: string, newline?: boolean, indnt?: boolean): string { + newline = typeof newline === 'boolean' ? newline : true; + indnt = typeof indnt === 'boolean' ? indnt : true; + let s = ''; + if (str) { + if (indnt) { + s += indent(); + } + s += str; + } + if (newline) { + s += '\n'; + } + return s; +} + + +/// Main + +/* +const debugProtocolSchema = JSON.parse(fs.readFileSync('./ModelExecutionTraceProtocol.json').toString()); + +const emitStr = TSGeneratorModule('ModelExecutionTraceProtocol', debugProtocolSchema); + +fs.writeFileSync(`../metp_protocol/src/ModelExecutionTraceProtocol.ts`, emitStr, { encoding: 'utf-8'}); +*/ diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/generatorConfig.d.ts b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/generatorConfig.d.ts new file mode 100644 index 000000000..710dd3782 --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/generatorConfig.d.ts @@ -0,0 +1,26 @@ + + +// data structure to configure the generator inputs and outputs for several +export interface ProtocolGenConfigs { + protocolGenConfigs: ProtocolGenConfig[]; +} + +export interface ProtocolGenConfig { + protocolName: string; + protocolShortName: string; + protocolJSONSchemaPath: string; + tsAPI: FileGen; + javaServer: PackageGen; + javaClient: PackageGen; + javaAPI: PackageGen; + plantuml: FileGen; +} + +export interface PackageGen { + packageName: string; + destFileName: string; +} + +export interface FileGen { + destFileName: string; +} \ No newline at end of file diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/json_schema.d.ts b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/json_schema.d.ts new file mode 100644 index 000000000..b2f6de195 --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/json_schema.d.ts @@ -0,0 +1,80 @@ +/** + * TypeScript definitions for a subset of the json schema. + */ + +export interface IProtocol { + + $schema: string, + title: string, + description: string, + type: "object", + + definitions: { [key: string]: Protocol.Definition2 } +} + +export module Protocol { + + export interface Definition extends ObjectType { + } + + export interface AllOf { + allOf: (Definition | RefType ) [] + } + + export type Definition2 = Definition | AllOf | StringType; + type PropertyType = PrimitiveType | StringType | ObjectType | ArrayType; + + export interface PrimitiveType extends BaseType { + type: "number" | "integer" | "boolean" + } + + export interface Commentable { + /** Description of the type */ + description?: string + /** Possible values of a string. */ + enum?: string[] + /** Possible descriptions for the values of a string. */ + enumDescriptions?: string[] + /** Possible values of a string. */ + _enum?: string[] + } + + export interface StringType extends BaseType, Commentable { + type: "string" + /** Possible values of a string. */ + enum?: string[] + /** Possible descriptions for the values of a string. */ + enumDescriptions?: string[] + /** Possible values of a string. */ + _enum?: string[] + } + + export interface ObjectType extends BaseType { + type: "object" + /** Properties of the type. Maps to a typed object */ + properties?: { [key: string]: PropertyType; } + /** Names of required properties */ + required?: string[], + /** Are additional properties allowed? */ + additionalProperties?: boolean + } + + export interface ArrayType extends BaseType { + type: "array" + /** Maps to a typed array e.g string[] */ + items: RefType | PrimitiveType | StringType | ObjectType + /** Cardinality of length of array type */ + //minItems?: number + //maxItems?: number + } + + export interface RefType { + /** Reference to a domain defined type */ + $ref: string + } + + export interface BaseType { + /** Description of the type */ + description?: string + } +} \ No newline at end of file diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/json_schemaHelpers.ts b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/json_schemaHelpers.ts new file mode 100644 index 000000000..f8cefdcf6 --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/json_schemaHelpers.ts @@ -0,0 +1,174 @@ +/*--------------------------------------------------------- + * Copyright (c) 2020 Inria and others.. All rights reserved. + *--------------------------------------------------------*/ + +'use strict'; + +import {IProtocol, Protocol as P } from './json_schema'; + +/** + * Helper class to compute information from a property definition in json_schema + */ +export class PropertyHelper { + containerDefinitionName: string; + propertyName: string; + propertyType : (P.PropertyType | P.RefType ); + constructor(containerDefinitionName: string, propertyName: string, propertyType : (P.PropertyType | P.RefType )) { + this.containerDefinitionName = containerDefinitionName; + this.propertyName = propertyName + this.propertyType = propertyType + } + + propertyTypeOrRefJavaName(): string { + return this.internalPropertyTypeOrRefJavaName(this.propertyType); + } + + protected internalPropertyTypeOrRefJavaName(prop: (P.PropertyType | P.RefType )): string { + if (((prop as P.RefType)?.$ref)) { + return getRef((prop as P.RefType)?.$ref); + } else { + return this.internalPropertyTypeJavaName( prop as P.PropertyType); + } + } + + protected internalPropertyTypeJavaName(prop: P.PropertyType ): string { + switch (prop.type) { + case 'array': + const s = this.internalPropertyTypeOrRefJavaName( prop.items); + //console.table(prop.items); + //console.table(this); + if (s.indexOf(' ') >= 0) { + return `(${s})[]`; + } + return `${s}[]`; + case 'object': + + return this.objectTypeJavaName(prop); + case 'string': + if (prop.enum) { + return this.getDedicatedTypeJavaName(); + } + return `String`; + case 'integer': + return 'Integer'; + case 'number': + return 'Float'; + } + if (Array.isArray(prop.type)) { + + if(prop.type.length === 2 && prop.type['null']) { + // this is actually a nullable + let a = prop.type.filter(e => e !== 'null') + switch (a[0]){ + case 'string': + return 'String'; + case 'integer': + return 'Integer'; + case 'number': + return 'Float'; + } + return 'Object'; + } else { + return 'Object'; + } + + // if (prop.type.length === 7 && prop.type.sort().join() === 'array,boolean,integer,null,number,object,string') { // silly way to detect all possible json schema types + // return 'Object'; + // } else { + // return prop.type.map(v => v === 'integer' ? 'Integer' : v).join(' | '); + // } + } + return prop.type; + } + + getDedicatedTypeJavaName() { + return this.containerDefinitionName+capitalizeFirstLetter(this.propertyName); + } + + objectTypeJavaName( prop: P.ObjectType): string { + // if (prop.properties) { + // let s = openBlock('', '{', false); + + // for (let propName in prop.properties) { + // const required = prop.required ? prop.required.indexOf(propName) >= 0 : false; + // s += property(hostDefinitionName, propName, !required, prop.properties[propName]); + // } + + // s += closeBlock('}', false); + // return s; + // } + // if (prop.additionalProperties) { + // return `Map`; + // //return `{ [key: string]: ${orType(prop.additionalProperties.type)}; }`; + // } + // return '{}'; + if (prop.properties) { + if(prop.properties['body']) { + return this.internalPropertyTypeOrRefJavaName(prop.properties['body']); + } else { + return `\/* TODO objectTypeJavaName() properties ? ${prop} ${this.containerDefinitionName+capitalizeFirstLetter(this.propertyName)} *\/` + } + + // for (let propName in prop.properties) { + // const required = prop.required ? prop.required.indexOf(propName) >= 0 : false; + // return property(hostDefinitionName, propName, !required, prop.properties[propName]); + // } + } else if (prop.additionalProperties) { + // TODO check version of json_schema.d.ts and use of it ... + return `Map`; + } else { + return `\/* TODO objectTypeJavaName() ? ${prop} ${this.containerDefinitionName+capitalizeFirstLetter(this.propertyName)} *\/` + } + } + +} + +export class ResponseHelper { + responseDefTypeName: string; + responseDef: P.Definition; + constructor(responseDefTypeName: string, responseDef: P.Definition){ + this.responseDef=responseDef; + this.responseDefTypeName=responseDefTypeName; + } + +} + +function orType(enm: string | string[]): string { + if (typeof enm === 'string') { + return 'String'; + } + return enm.join(' | '); +} + +function getRef(ref: string): string { + const REXP = /#\/(.+)\/(.+)/; + const matches = REXP.exec(ref); + if (matches && matches.length === 3) { + return matches[2]; + } + console.log('error: ref'); + return ref; +} + +// function toEnumLiteral(string: string) { +// // TODO transform camelcase into uppercase and _ +// return string.toUpperCase() ; +// } + +/** + * replace java keywords + * @param s + */ +export function isJavaKeyWord(s: string): boolean { + return s === 'continue' ||s === 'default' || s === 'goto' || s === 'switch' ; +} + +export function getJavaSafeName(s: string): string { + if(isJavaKeyWord(s)){ + return '_'+s; + } else return s; +} + +export function capitalizeFirstLetter(s: string) { + return s.charAt(0).toUpperCase() + s.slice(1); +} \ No newline at end of file diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/plantumlGenerator.ts b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/plantumlGenerator.ts new file mode 100644 index 000000000..982116b7c --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/src/modules/plantumlGenerator.ts @@ -0,0 +1,579 @@ +/*--------------------------------------------------------- + * Copyright (c) 2020 Inria and others.. All rights reserved. + *--------------------------------------------------------*/ + +'use strict'; + +//import * as fs from 'fs'; +import {IProtocol, Protocol as P} from './json_schema'; +import {PropertyHelper, ResponseHelper} from './json_schemaHelpers' + +let numIndents = 0; + +export function PlantumlGeneratorModule(protocolName: string, schema: IProtocol): string { + + let s = ''; + s += line("@startuml"); + s += line("' GENERATED FILE, DO NOT MODIFY MANUALLY"); + s+= line("left to right direction"); + s += line(); + s += line("package "+protocolName+"_API {"); + + let links = ''; + let messagesClasses = ''; + let messagesClassesList :string[] = []; + let dtoClasses = ''; + + + s += line("package data {"); + for (let typeName in schema.definitions) { + + const d2 = schema.definitions[typeName]; + + let supertype: string = null; + if ((d2).allOf) { + // responses and messages + const array = (d2).allOf; + for (let d of array) { + if ((d).$ref) { + supertype = getRef((d).$ref); + } else { + + // ignore generic Json RPC data + // Request, Event, Response, ErrorResponse + + if( typeName != 'Request' && typeName != 'Event' && typeName != 'Response' && typeName != 'ErrorResponse') { + if(supertype == 'Response') { + // let's create the data' + //console.log(`create interface for Response ${typeName}`); + + if(( d).properties && ( d).properties['body']){ + messagesClasses += MessageInterface(typeName, ( d).properties['body'], true); + messagesClassesList.push(typeName); + links += MessageInterfaceLinks(typeName, ( d).properties['body']); + } else { + messagesClasses += MessageInterface(typeName, d, true); + messagesClassesList.push(typeName); + links += MessageInterfaceLinks(typeName, d2); + } + } else if(supertype == 'Event') { + // let's create the data' + //console.log(`create interface for Event ${typeName}`); + //console.log(( d).properties['body']); + if(( d).properties['body']){ + messagesClasses += MessageInterface(typeName+"Arguments", ( d).properties['body'], true); + messagesClassesList.push(typeName+"Arguments"); + links += MessageInterfaceLinks(typeName+"Arguments", ( d).properties['body']); + } else { + console.log("plantuml Ignore1 "+typeName); + } + //s += MessageInterface(typeName, d); + } + } else { + console.log("plantuml Ignore2 "+typeName); + } + } + } + } else { + // arguments + //console.log('not allOf ' + typeName); + //console.log(d2); + //s += MessageInterface(typeName, d); + if ((d2).enum) { + s += Enum(typeName, d2); + } else { + if(typeName != 'ProtocolMessage') { + //console.log(`create interface for DTO ${typeName}`); + if(typeName.toLowerCase().endsWith('dto')){ + dtoClasses += MessageInterface(typeName, d2, true); + } else { + messagesClasses += MessageInterface(typeName, d2, true); + messagesClassesList.push(typeName); + } + links += MessageInterfaceLinks(typeName, d2); + } + } + } + } + s += line("package messageClasses {"); + s += messagesClasses; + s += line("}"); + s += line("package dtoClasses {"); + s += dtoClasses; + s += line("}"); + s += line("}"); + + s += links; + + messagesClassesList.forEach(function (messagesClass) { + s += line(""+messagesClass+" -[hidden]- dtoClasses" ); + }); + + s += line("package services {"); + + s += openBlock("class "+protocolName+'Server'); + for (let typeName in schema.definitions) { + + const d2 = schema.definitions[typeName]; + + let supertype: string = null; + if ((d2).allOf) { + const array = (d2).allOf; + for (let d of array) { + if ((d).$ref) { + supertype = getRef((d).$ref); + } else { + if(supertype == 'Request') { + let requestName = typeName.replace(/(.*)Request$/, "$1"); // TODO find the real name of the command in the "command"" property rather than infer from typeName + let responseDefTypeName = typeName.replace(/(.*)Request$/, "$1Response"); // TODO do we have a better way to find the response from the request in the json schema ? + let responseDefType = schema.definitions[responseDefTypeName]; + var responseDef : P.Definition + for (let respDef of (responseDefType).allOf) { + if ((respDef).$ref) { + } else { + responseDef = respDef; + } + } + const response : ResponseHelper = new ResponseHelper(responseDefTypeName, responseDef); + s += RequestInterface(requestName, d, response); + } + } + } + } + } + s += closeBlock(); + + s += openBlock("class "+protocolName+'Client'); + for (let typeName in schema.definitions) { + + const d2 = schema.definitions[typeName]; + + let supertype: string = null; + if ((d2).allOf) { + const array = (d2).allOf; + for (let d of array) { + if ((d).$ref) { + supertype = getRef((d).$ref); + } else { + if(supertype == 'Event') { + //let eventName = typeName.replace(/(.*)Event$/, "$1"); // TODO find the real name of the command in the "command"" property rather than infer from typeName + + s += EventInterface(typeName, d); + } + } + } + } + } + s += closeBlock(); + s += line("}"); + + //s+= line('services -[hidden]- data'); + +// s += closeBlock(); + s += line("}"); + s += line("@enduml"); + s += line(); + + return s; +} + +function MessageInterface(interfaceName: string, definition: P.Definition, useLink : boolean): string { + + console.log("plantuml MessageInterface "+interfaceName); + + let s = ''; + + s += openBlock(`class ${interfaceName} `); + for (let propName in definition.properties) { + const required = definition.required ? definition.required.indexOf(propName) >= 0 : false; + const propertyHelper: PropertyHelper = new PropertyHelper(interfaceName, propName, definition.properties[propName]); + const prop = definition.properties[propName]; + if(!useLink || !propertyIsLinkable(prop)){ + s += property(propName, !required, definition.properties[propName]); + } + } + s += closeBlock(); + return s; +} + +/** + * Create links instead of attribute when possible + * @param interfaceName + * @param definition + * @returns + */ +function MessageInterfaceLinks(interfaceName: string, definition: P.Definition): string { + let s = ''; + for (let propName in definition.properties) { + const required = definition.required ? definition.required.indexOf(propName) >= 0 : false; + const propertyHelper: PropertyHelper = new PropertyHelper(interfaceName, propName, definition.properties[propName]); + const prop = definition.properties[propName]; + const type = propertySimpleType(prop); + if(propertyIsLinkable(prop)){ + if(propertyIsMany(prop)) { + s += line(interfaceName + " *-- \"*\" " + type + " : "+propName); + } else { + s += line(interfaceName + " *-- " + type + " : "+propName); + } + } + } + return s; +} + +function RequestInterface(interfaceName: string, definition: P.Definition, responseHelper: ResponseHelper): string { + + // let desc = definition.description; + let methodName = ""; + if (definition.properties && definition.properties.event && definition.properties.event['enum']) { + const eventName = `${definition.properties.event['enum'][0]}`; + methodName = eventName; + // if (eventName) { + // desc = `Event message for '${eventName}' event type.\n${desc}`; + // } + } else if (definition.properties && definition.properties.command && definition.properties.command['enum']) { + const requestName = `${definition.properties.command['enum'][0]}`; + methodName = requestName; + // if (requestName) { + // const RequestName = requestName[0].toUpperCase() + requestName.substr(1); + // desc = `${RequestName} request; value of command field is '${requestName}'.\n${desc}`; + // } + } + let s = ''; + //s += comment({ description : desc }); + + + // find response type + var returnType = '@JsonRequest| '; + if(responseHelper.responseDef && responseHelper.responseDef.properties && responseHelper.responseDef.properties.body){ + //console.log(interfaceName+': responsedefinition = '+responsedefinition.properties.body); + //console.log(responsedefinition.properties.body); + //console.table(responsedefinition.properties.body); + //console.table(argumentType(responsedefinition.properties.body)); + if(responseHelper.responseDef.properties.body.type === 'object'){ + returnType = responseHelper.responseDefTypeName; + } else { + returnType = returnType+ propertyType(responseHelper.responseDef.properties.body); + } + } + var argsString : string[] = []; + for (let propName in definition.properties) { + + const type = propertyType(definition.properties[propName]); + const propertyDef = `${type} ${propName}`; + if (type[0] === '\'' && type[type.length-1] === '\'' && type.indexOf('|') < 0) { + //s += line(`// ${propertyDef};`); + } else { + argsString.push(`${propertyDef}`); + } + } + + s += line(`${returnType} ${methodName}(`+argsString.join(', ')+`)`); + + return s; +} + +function EventInterface(interfaceName: string, definition: P.Definition): string { + + let methodName = ""; + if (definition.properties && definition.properties.event && definition.properties.event['enum']) { + const eventName = `${definition.properties.event['enum'][0]}`; + methodName = eventName; + } else if (definition.properties && definition.properties.command && definition.properties.command['enum']) { + const eventName = `${definition.properties.command['enum'][0]}`; + methodName = eventName; + if (eventName) { + const EventtName = eventName[0].toUpperCase() + eventName.substr(1); + } + } + let s = ''; + + + var argsString : string[] = []; + + if(definition.properties['body']){ + argsString.push(`${interfaceName}Arguments args`); + } + + + /*for (let propName in definition.properties) { + + const type = propertyType(definition.properties[propName]); + const propertyDef = `${type} ${propName}`; + if (type[0] === '\'' && type[type.length-1] === '\'' && type.indexOf('|') < 0) { + //s += line(`// ${propertyDef};`); + } else { + argsString.push(`${propertyDef}`); + } + }*/ + + s += line(`@JsonNotification| void ${methodName}(`+argsString.join(', ')+`)`); + return s; +} + +function Enum(typeName: string, definition: P.StringType): string { + let s = line(); + s += comment(definition); + const x = enumAsOrType(definition.enum); + s += line(`export type ${typeName} = ${x};`); + return s; +} + +function enumAsOrType(enm: string[]) { + return enm.map(v => `'${v}'`).join(' | '); +} + +function comment(c: P.Commentable): string { + + let description = c.description || ''; + + if ((c).items) { // array + c = (c).items; + } + + // a 'closed' enum with individual descriptions + if (c.enum && c.enumDescriptions) { + for (let i = 0; i < c.enum.length; i++) { + description += `\n'${c.enum[i]}': ${c.enumDescriptions[i]}`; + } + } + + // an 'open' enum + if (c._enum) { + description += '\nValues: '; + if (c.enumDescriptions) { + for (let i = 0; i < c._enum.length; i++) { + description += `\n'${c._enum[i]}': ${c.enumDescriptions[i]}`; + } + description += '\netc.'; + } else { + description += `${c._enum.map(v => `'${v}'`).join(', ')}, etc.`; + } + } + + if (description) { + description = description.replace(/(.*)<\/code>/g, "'$1'"); + numIndents++; + description = description.replace(/\n/g, '\n' + indent()); + numIndents--; + if (description.indexOf('\n') >= 0) { + return line(`/** ${description}\n${indent()}*/`); + } else { + return line(`/** ${description} */`); + } + } + return ''; +} + +function openBlock(str: string, openChar?: string, indent?: boolean): string { + indent = typeof indent === 'boolean' ? indent : true; + openChar = openChar || ' {'; + let s = line(`${str}${openChar}`, true, indent); + numIndents++; + return s; +} + +function closeBlock(closeChar?: string, newline?: boolean): string { + newline = typeof newline === 'boolean' ? newline : true; + closeChar = closeChar || '}'; + numIndents--; + return line(closeChar, newline); +} + +function propertyIsLinkable(prop: any): boolean { + if (prop.$ref) { return true; } + switch (prop.type) { + case 'array': + const s = propertyType(prop.items); + return propertyIsLinkable(prop.items); + case 'object': + return false; + case 'string': + return false; + case 'integer': + return false; + } + return false; +} +function propertyIsMany(prop: any): boolean { + if (prop.$ref) { return false; } + switch (prop.type) { + case 'array': + return true; + case 'object': + return false; + case 'string': + return false; + case 'integer': + return false; + } + return false; +} + +/** + * simple type name (without multiplicity brackets) + * @param prop + * @returns + */ +function propertySimpleType(prop: any): string { + if (prop.$ref) { + //console.log("propertyType is aref " + getRef(prop.$ref)); + return ""+getRef(prop.$ref); + } + switch (prop.type) { + case 'array': + const s = propertyType(prop.items); + if (s.indexOf(' ') >= 0) { + return `${s}`; + } + return `${s}`; + case 'object': + return objectType(prop); + case 'string': + if (prop.enum) { + return enumAsOrType(prop.enum); + } + return `String`; + case 'integer': + return 'Integer'; + } + if (Array.isArray(prop.type)) { + if (prop.type.length === 7 && prop.type.sort().join() === 'array,boolean,integer,null,number,object,string') { // silly way to detect all possible json schema types + return 'Object'; + } else { + return prop.type.map(v => v === 'integer' ? 'Integer' : v).join(' | '); + } + } + return prop.type; +} +function propertyType(prop: any): string { + if (prop.$ref) { + //console.log("propertyType is aref " + getRef(prop.$ref)); + return ""+getRef(prop.$ref); + } + switch (prop.type) { + case 'array': + const s = propertyType(prop.items); + if (s.indexOf(' ') >= 0) { + return `(${s})[]`; + } + return `${s}[]`; + case 'object': + return objectType(prop); + case 'string': + if (prop.enum) { + return enumAsOrType(prop.enum); + } + return `String`; + case 'integer': + return 'Integer'; + } + if (Array.isArray(prop.type)) { + if (prop.type.length === 7 && prop.type.sort().join() === 'array,boolean,integer,null,number,object,string') { // silly way to detect all possible json schema types + return 'Object'; + } else { + return prop.type.map(v => v === 'integer' ? 'Integer' : v).join(' | '); + } + } + return prop.type; +} + +function objectType(prop: any): string { + if (prop.properties) { + let s = openBlock('', '{', false); + + for (let propName in prop.properties) { + const required = prop.required ? prop.required.indexOf(propName) >= 0 : false; + s += property(propName, !required, prop.properties[propName]); + } + + s += closeBlock('}', false); + return s; + } + if (prop.additionalProperties) { + return `Map`; + //return `{ [key: string]: ${orType(prop.additionalProperties.type)}; }`; + } + return '{}'; +} + +function orType(enm: string | string[]): string { + if (typeof enm === 'string') { + return 'String'; + } + return enm.join(' | '); +} + +function requestArg(name: string, prop: P.PropertyType): string { + let s = ''; + s += comment(prop); + const type = propertyType(prop); + const propertyDef = `${type} ${name}`; + if (type[0] === '\'' && type[type.length-1] === '\'' && type.indexOf('|') < 0) { + s += line(`// ${propertyDef};`); + } else { + s += line(`${propertyDef};`); + } + return s; +} + +function property(name: string, optional: boolean, prop: P.PropertyType): string { + let s = ''; + //s += comment(prop); + const type = propertyType(prop); + const propertyDef = `${type} ${name}`; + /*if(prop.type == 'object' && name == 'body') { + console.log("this is a body object"); + }*/ + if (type[0] === '\'' && type[type.length-1] === '\'' && type.indexOf('|') < 0) { + s += line(`\' ${propertyDef};`); + } else { + // if(!optional) { + // s += line('// @NonNull'); + // } + s += line(`${propertyDef}`); + } + //console.log("type ="+type+"; name="+name); + return s; +} + + +function getRef(ref: string): string { + const REXP = /#\/(.+)\/(.+)/; + const matches = REXP.exec(ref); + if (matches && matches.length === 3) { + return matches[2]; + } + console.log('error: ref'); + return ref; +} + +function indent(): string { + return '\t'.repeat(numIndents); +} + +function line(str?: string, newline?: boolean, indnt?: boolean): string { + newline = typeof newline === 'boolean' ? newline : true; + indnt = typeof indnt === 'boolean' ? indnt : true; + let s = ''; + if (str) { + if (indnt) { + s += indent(); + } + s += str; + } + if (newline) { + s += '\n'; + } + return s; +} + + +/// Main + +/* +const debugProtocolSchema = JSON.parse(fs.readFileSync('./ModelExecutionTraceProtocol.json').toString()); + +const emitStr = TSGeneratorModule('ModelExecutionTraceProtocol', debugProtocolSchema); + +fs.writeFileSync(`../metp_protocol/src/ModelExecutionTraceProtocol.ts`, emitStr, { encoding: 'utf-8'}); +*/ diff --git a/protocols/generators/ts/JSONSchema2APIProtocolGenerator/tsconfig.json b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/tsconfig.json new file mode 100644 index 000000000..54e392337 --- /dev/null +++ b/protocols/generators/ts/JSONSchema2APIProtocolGenerator/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "moduleResolution": "node", + "noImplicitAny": false, + "removeComments": false, + "preserveConstEnums": true, + "target": "ES6", + "sourceMap": true, + "inlineSourceMap": false, + "outDir": "./dist", + "strictNullChecks": false + }, + "include": [ + "src/**/*.ts" + ], + "exclude": [ + "node_modules" + ] +} diff --git a/simulationmodelanimation/pom.xml b/simulationmodelanimation/pom.xml index a0a6950d9..46e5b5bae 100644 --- a/simulationmodelanimation/pom.xml +++ b/simulationmodelanimation/pom.xml @@ -27,7 +27,7 @@ - 2.5.0 + 2.7.0 scm:git:https://github.com/SiriusLab/ModelDebugging.git