[eclipse/xtext#1679]ported test code to java

Signed-off-by: Christian Dietrich <christian.dietrich@itemis.de>
This commit is contained in:
Christian Dietrich 2020-05-04 18:33:52 +02:00
parent 59d0234347
commit 16d926c7f3
59 changed files with 1845 additions and 4004 deletions

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2017 TypeFox GmbH (http://www.typefox.io) and others.
* Copyright (c) 2017, 2020 TypeFox GmbH (http://www.typefox.io) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
@ -11,19 +11,17 @@ package org.eclipse.xtext.ide.tests.serializer
import com.google.inject.Inject
import com.google.inject.Provider
import org.eclipse.emf.ecore.EClass
import org.eclipse.emf.ecore.EPackage
import org.eclipse.emf.ecore.EcoreFactory
import org.eclipse.xtext.ide.serializer.impl.ChangeSerializer
import org.eclipse.xtext.ide.tests.testlanguage.partialSerializationTestLanguage.EClassRef
import org.eclipse.xtext.ide.tests.testlanguage.partialSerializationTestLanguage.Model
import org.eclipse.xtext.ide.tests.testlanguage.tests.PartialSerializationTestLanguageInjectorProvider
import org.eclipse.xtext.testing.InjectWith
import org.eclipse.xtext.testing.XtextRunner
import org.eclipse.xtext.testing.util.InMemoryURIHandler
import org.eclipse.xtext.testlanguages.ecore.EcoreSupport
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.eclipse.emf.ecore.EPackage
/**
* @author Moritz Eysholdt - Initial contribution and API
@ -136,13 +134,3 @@ class ChangeSerializerWithEmfTest {
}
}
class PartialSerializationTestLanguageInjectorProviderWithEmf extends PartialSerializationTestLanguageInjectorProvider {
override protected internalCreateInjector() {
val result = super.internalCreateInjector()
new EcoreSupport().createInjectorAndDoEMFRegistration()
return result
}
}

View file

@ -1,5 +1,5 @@
/**
* Copyright (c) 2017 TypeFox GmbH (http://www.typefox.io) and others.
* Copyright (c) 2017, 2020 TypeFox GmbH (http://www.typefox.io) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
@ -12,8 +12,8 @@ import com.google.inject.Injector;
import org.eclipse.xtext.ide.tests.testlanguage.tests.PartialSerializationTestLanguageInjectorProvider;
import org.eclipse.xtext.testlanguages.ecore.EcoreSupport;
@SuppressWarnings("all")
public class PartialSerializationTestLanguageInjectorProviderWithEmf extends PartialSerializationTestLanguageInjectorProvider {
public class PartialSerializationTestLanguageInjectorProviderWithEmf
extends PartialSerializationTestLanguageInjectorProvider {
@Override
protected Injector internalCreateInjector() {
final Injector result = super.internalCreateInjector();

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2016 TypeFox GmbH (http://www.typefox.io) and others.
* Copyright (c) 2016, 2020 TypeFox GmbH (http://www.typefox.io) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.

View file

@ -0,0 +1,253 @@
/**
* Copyright (c) 2017, 2020 TypeFox GmbH (http://www.typefox.io) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.ide.tests.server;
import static org.junit.Assert.*;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.eclipse.emf.common.util.URI;
import org.eclipse.xtext.ide.server.UriExtensions;
import org.eclipse.xtext.ide.tests.testlanguage.TestLanguageIdeInjectorProvider;
import org.eclipse.xtext.testing.InjectWith;
import org.eclipse.xtext.testing.XtextRunner;
import org.eclipse.xtext.xbase.lib.Extension;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.google.common.base.CharMatcher;
import com.google.common.base.StandardSystemProperty;
import com.google.inject.Inject;
@RunWith(XtextRunner.class)
@InjectWith(TestLanguageIdeInjectorProvider.class)
public class UriExtensionsTest {
@Inject
@Extension
private UriExtensions uriExtensions;
@Test
public void test_toUri01() throws Exception {
assertEquals(URI.createURI("file://path/to/resource"), uriExtensions.toUri("file://path/to/resource"));
}
@Test
public void test_toUri_02() throws Exception {
assertEquals(URI.createURI("file:///path/to/resource"), uriExtensions.toUri("file:///path/to/resource"));
}
@Test
public void test_toUri03() throws Exception {
assertEquals(URI.createURI("file://path%20with%20whitespaces/to/resource"),
uriExtensions.toUri("file://path%20with%20whitespaces/to/resource"));
}
@Test
public void test_toUri_04() throws Exception {
assertEquals(URI.createURI("file:///path%20with%20whitespaces/to/resource"),
uriExtensions.toUri("file:///path%20with%20whitespaces/to/resource"));
}
@Test
public void test_toUri_05() throws Exception {
assertEquals(URI.createURI("file:///dir/\u0424\u0443%20\u0411\u0430\u0440"),
uriExtensions.toUri("file:///dir/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80"));
}
@Test
public void test_toUri_06() throws Exception {
assertEquals(URI.createURI("file://dir/\u0424\u0443%20\u0411\u0430\u0440"),
uriExtensions.toUri("file://dir/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80"));
}
@Test
public void test_toUri_07() throws Exception {
assertEquals(URI.createURI("something:/path/to/resource"), uriExtensions.toUri("something:/path/to/resource"));
}
@Test
public void test_toUri_08() throws Exception {
assertEquals(URI.createURI("something://path/to/resource"),
uriExtensions.toUri("something://path/to/resource"));
}
@Test
public void test_toUri_09() throws Exception {
assertEquals(URI.createURI("something:/dir/\u0424\u0443%20\u0411\u0430\u0440"),
uriExtensions.toUri("something:/dir/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80"));
}
@Test
public void test_toUri_10() throws Exception {
assertEquals(URI.createURI("something://dir/\u0424\u0443%20\u0411\u0430\u0440"),
uriExtensions.toUri("something://dir/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80"));
}
@Test
public void test_toUri_11() throws Exception {
assertEquals(URI.createURI("something:/path%20with%20whitespaces/to/resource"),
uriExtensions.toUri("something:/path%20with%20whitespaces/to/resource"));
}
@Test
public void test_toUri_12() throws Exception {
assertEquals(URI.createURI("something://path%20with%20whitespaces/to/resource"),
uriExtensions.toUri("something://path%20with%20whitespaces/to/resource"));
}
@Test
public void test_toUri_13() throws Exception {
assertEquals(URI.createURI("file:///c:/Users/dietrich/git/MyDSL_Imports/mydsl/workspace/src/something.mydsl"),
uriExtensions
.toUri("file:///c%3A/Users/dietrich/git/MyDSL_Imports/mydsl/workspace/src/something.mydsl"));
}
@Test
public void test_toUri_14() throws Exception {
assertEquals(URI.createURI("file:///c:/Users/dietrich/\u0424\u0443%20\u0411\u0430\u0440.mydsl"),
uriExtensions.toUri("file:///c%3A/Users/dietrich/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80.mydsl"));
}
@Test
public void test_toUriString_01() throws Exception {
assertEquals("file:///path/to/resource",
uriExtensions.toUriString(java.net.URI.create("file:///path/to/resource")));
}
@Test
public void test_toUriString_02() throws Exception {
assertEquals("file://path/to/resource",
uriExtensions.toUriString(java.net.URI.create("file://path/to/resource")));
}
@Test
public void test_toUriString_03() throws Exception {
assertEquals("file:///dir/\u0424\u0443%20\u0411\u0430\u0440",
uriExtensions.toUriString(java.net.URI.create("file:/dir/\u0424\u0443%20\u0411\u0430\u0440")));
}
@Test
public void test_toUriString_04() throws Exception {
assertEquals("file://dir/\u0424\u0443%20\u0411\u0430\u0440",
uriExtensions.toUriString(java.net.URI.create("file://dir/\u0424\u0443%20\u0411\u0430\u0440")));
}
@Test
public void test_toUriString_05() throws Exception {
assertEquals("file://path/to/resource/",
uriExtensions.toUriString(java.net.URI.create("file://path/to/resource/")));
}
@Test
public void test_toUriString_06() throws Exception {
assertEquals("file:///path/to/resource/",
uriExtensions.toUriString(java.net.URI.create("file:/path/to/resource/")));
}
@Test
public void test_toUriString_07() throws Exception {
assertEquals("file:///path/to/resource/",
uriExtensions.toUriString(java.net.URI.create("file:///path/to/resource/")));
}
@Test
public void test_symmetric_01() throws Exception {
assertEquals(URI.createURI("file:///path/to/resource"),
uriExtensions.toUri(uriExtensions.toUriString(java.net.URI.create("file:///path/to/resource"))));
}
@Test
public void test_symmetric_02() throws Exception {
assertEquals(URI.createURI("file://path/to/resource"),
uriExtensions.toUri(uriExtensions.toUriString(java.net.URI.create("file://path/to/resource"))));
}
@Test
public void test_symmetric_03() throws Exception {
assertEquals(URI.createURI("something:/path/to/resource"),
uriExtensions.toUri(uriExtensions.toUriString(java.net.URI.create("something:/path/to/resource"))));
}
@Test
public void test_symmetric_04() throws Exception {
assertEquals(URI.createURI("something://path/to/resource"),
uriExtensions.toUri(uriExtensions.toUriString(java.net.URI.create("something://path/to/resource"))));
}
@Test
public void testConversion() throws Exception {
assertEquals("file:///dir/name.ext", uriExtensions.toUriString(uriExtensions.toUri("file:///dir/name.ext")));
}
@Test
public void testFileUriConversion() throws Exception {
final String expected = Paths.get(new File(".").getCanonicalPath()).resolve("dir").resolve("name.ext").toUri()
.toString();
assertEquals(expected,
uriExtensions.toUriString(URI.createFileURI(new File("dir/name.ext").getAbsolutePath())));
}
@Test
public void testFilesWithSpaces() throws Exception {
final URI x = uriExtensions.toUri("file:///dir/Foo%20Bar.testlang");
final String y = uriExtensions.toUriString(x);
assertEquals("file:///dir/Foo%20Bar.testlang", y);
}
@Test
public void testFilesWithCyrillicSymbols() throws Exception {
assertEquals("file:///dir/\u0424\u0443%20\u0411\u0430\u0440.testlang", uriExtensions
.toUriString(uriExtensions.toUri("file:///dir/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80.testlang")));
}
@Test
public void testFolderIsPrefix() throws Exception {
File directory = new File("./test-data2/test-project");
directory.mkdirs();
assertTrue(directory.exists());
assertTrue(directory.isDirectory());
URI uri = uriExtensions.toUri(uriExtensions.toUriString(URI.createFileURI(directory.getAbsolutePath() + "/")));
assertTrue(uri.isPrefix());
}
@Test
public void testFolderIsPrefixWithWhitespace() throws Exception {
File directory = createTempDir("some name with whitespaces").toFile();
assertTrue(directory.exists());
assertTrue(directory.isDirectory());
assertTrue(CharMatcher.whitespace().matchesAnyOf(directory.getName()));
URI uri = uriExtensions.toUri(uriExtensions.toUriString(URI.createFileURI(directory.getAbsolutePath() + "/")));
assertTrue(uri.isPrefix());
}
@Test
public void test_withEmptyAuthority() throws Exception {
final URI uriWithoutAuthority = URI.createURI("file:/path/to/resource/");
assertNull(uriWithoutAuthority.authority());
final URI uriWithEmptyAuthority = uriExtensions.withEmptyAuthority(uriWithoutAuthority);
assertNotSame(uriWithoutAuthority, uriWithEmptyAuthority);
assertEquals("Returned URI is expected to have an empty instead of null authority", "",
uriWithEmptyAuthority.authority());
final URI uriWithAuthority = URI.createURI("https://xtext.org/path/to/resource/");
assertNotNull(uriWithAuthority.authority());
assertEquals("xtext.org", uriWithAuthority.authority());
assertSame(uriWithAuthority, uriExtensions.withEmptyAuthority(uriWithAuthority));
}
private Path createTempDir(final String prefix) throws Exception {
return Files.createTempDirectory(getTempDirPath(), prefix);
}
private Path getTempDirPath() {
return Paths.get(StandardSystemProperty.JAVA_IO_TMPDIR.value());
}
}

View file

@ -1,304 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 TypeFox GmbH (http://www.typefox.io) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.xtext.ide.tests.server
import com.google.common.base.CharMatcher
import com.google.common.base.StandardSystemProperty
import com.google.inject.Inject
import java.io.File
import java.net.URI
import java.nio.file.Files
import java.nio.file.Paths
import org.eclipse.xtext.ide.server.UriExtensions
import org.eclipse.xtext.ide.tests.testlanguage.TestLanguageIdeInjectorProvider
import org.eclipse.xtext.testing.InjectWith
import org.eclipse.xtext.testing.XtextRunner
import org.junit.Test
import org.junit.runner.RunWith
import static org.eclipse.emf.common.util.URI.createFileURI
import static org.eclipse.emf.common.util.URI.createURI
import static org.junit.Assert.*
@RunWith(XtextRunner)
@InjectWith(TestLanguageIdeInjectorProvider)
class UriExtensionsTest {
@Inject
extension UriExtensions
@Test
def void test_toUri01() {
assertEquals(
createURI('file://path/to/resource'),
'file://path/to/resource'.toUri
);
}
@Test
def void test_toUri_02() {
assertEquals(
createURI('file:///path/to/resource'),
'file:///path/to/resource'.toUri
);
}
@Test
def void test_toUri03() {
assertEquals(
createURI('file://path%20with%20whitespaces/to/resource'),
'file://path%20with%20whitespaces/to/resource'.toUri
);
}
@Test
def void test_toUri_04() {
assertEquals(
createURI('file:///path%20with%20whitespaces/to/resource'),
'file:///path%20with%20whitespaces/to/resource'.toUri
);
}
@Test
def void test_toUri_05() {
assertEquals(
createURI('file:///dir/\u0424\u0443%20\u0411\u0430\u0440'),
'file:///dir/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80'.toUri
);
}
@Test
def void test_toUri_06() {
assertEquals(
createURI('file://dir/\u0424\u0443%20\u0411\u0430\u0440'),
'file://dir/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80'.toUri
);
}
@Test
def void test_toUri_07() {
assertEquals(
createURI('something:/path/to/resource'),
'something:/path/to/resource'.toUri
);
}
@Test
def void test_toUri_08() {
assertEquals(
createURI('something://path/to/resource'),
'something://path/to/resource'.toUri
);
}
@Test
def void test_toUri_09() {
assertEquals(
createURI('something:/dir/\u0424\u0443%20\u0411\u0430\u0440'),
'something:/dir/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80'.toUri
);
}
@Test
def void test_toUri_10() {
assertEquals(
createURI('something://dir/\u0424\u0443%20\u0411\u0430\u0440'),
'something://dir/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80'.toUri
);
}
@Test
def void test_toUri_11() {
assertEquals(
createURI('something:/path%20with%20whitespaces/to/resource'),
'something:/path%20with%20whitespaces/to/resource'.toUri
);
}
@Test
def void test_toUri_12() {
assertEquals(
createURI('something://path%20with%20whitespaces/to/resource'),
'something://path%20with%20whitespaces/to/resource'.toUri
);
}
@Test
def void test_toUri_13() {
assertEquals(
createURI('file:///c:/Users/dietrich/git/MyDSL_Imports/mydsl/workspace/src/something.mydsl'),
'file:///c%3A/Users/dietrich/git/MyDSL_Imports/mydsl/workspace/src/something.mydsl'.toUri
);
}
@Test
def void test_toUri_14() {
assertEquals(
createURI('file:///c:/Users/dietrich/\u0424\u0443%20\u0411\u0430\u0440.mydsl'),
"file:///c%3A/Users/dietrich/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80.mydsl".toUri
);
}
@Test
def void test_toUriString_01() {
assertEquals(
'file:///path/to/resource',
URI.create('file:///path/to/resource').toUriString
);
}
@Test
def void test_toUriString_02() {
assertEquals(
'file://path/to/resource',
URI.create('file://path/to/resource').toUriString
);
}
@Test
def void test_toUriString_03() {
assertEquals(
'file:///dir/\u0424\u0443%20\u0411\u0430\u0440',
URI.create('file:/dir/\u0424\u0443%20\u0411\u0430\u0440').toUriString
);
}
@Test
def void test_toUriString_04() {
assertEquals(
'file://dir/\u0424\u0443%20\u0411\u0430\u0440',
URI.create('file://dir/\u0424\u0443%20\u0411\u0430\u0440').toUriString
);
}
@Test
def void test_toUriString_05() {
assertEquals(
'file://path/to/resource/',
URI.create('file://path/to/resource/').toUriString
);
}
@Test
def void test_toUriString_06() {
assertEquals(
'file:///path/to/resource/',
URI.create('file:/path/to/resource/').toUriString
);
}
@Test
def void test_toUriString_07() {
assertEquals(
'file:///path/to/resource/',
URI.create('file:///path/to/resource/').toUriString
);
}
@Test
def void test_symmetric_01() {
assertEquals(
createURI('file:///path/to/resource'),
URI.create('file:///path/to/resource').toUriString.toUri
);
}
@Test
def void test_symmetric_02() {
assertEquals(
createURI('file://path/to/resource'),
URI.create('file://path/to/resource').toUriString.toUri
)
}
@Test
def void test_symmetric_03() {
assertEquals(
createURI('something:/path/to/resource'),
URI.create('something:/path/to/resource').toUriString.toUri
);
}
@Test
def void test_symmetric_04() {
assertEquals(
createURI('something://path/to/resource'),
URI.create('something://path/to/resource').toUriString.toUri
);
}
@Test
def void testConversion() {
assertEquals("file:///dir/name.ext", "file:///dir/name.ext".toUri.toUriString)
}
@Test
def void testFileUriConversion() {
val expected = Paths.get(new File('.').canonicalPath).resolve('dir').resolve('name.ext').toUri.toString;
assertEquals(expected, createFileURI(new File('dir/name.ext').absolutePath).toUriString)
}
@Test
def void testFilesWithSpaces() {
val x = "file:///dir/Foo%20Bar.testlang".toUri
val y = x.toUriString
assertEquals("file:///dir/Foo%20Bar.testlang", y)
}
@Test
def void testFilesWithCyrillicSymbols() {
assertEquals("file:///dir/\u0424\u0443%20\u0411\u0430\u0440.testlang",
"file:///dir/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80.testlang".toUri.toUriString)
}
@Test
def void testFolderIsPrefix() {
var directory = new File("./test-data2/test-project")
directory.mkdirs
assertTrue(directory.exists)
assertTrue(directory.directory)
var uri = createFileURI(directory.absolutePath + "/").toUriString.toUri
assertTrue(uri.isPrefix)
}
@Test
def void testFolderIsPrefixWithWhitespace() {
var directory = createTempDir('some name with whitespaces').toFile;
assertTrue(directory.exists)
assertTrue(directory.directory)
assertTrue(CharMatcher.whitespace.matchesAnyOf(directory.name));
var uri = createFileURI(directory.absolutePath + "/").toUriString.toUri
assertTrue(uri.isPrefix)
}
@Test
def void test_withEmptyAuthority () {
val uriWithoutAuthority = org.eclipse.emf.common.util.URI.createURI("file:/path/to/resource/")
assertNull(uriWithoutAuthority.authority)
val uriWithEmptyAuthority = uriWithoutAuthority.withEmptyAuthority
assertNotSame(uriWithoutAuthority, uriWithEmptyAuthority)
assertEquals("Returned URI is expected to have an empty instead of null authority", "", uriWithEmptyAuthority.authority)
val uriWithAuthority = org.eclipse.emf.common.util.URI.createURI("https://xtext.org/path/to/resource/")
assertNotNull(uriWithAuthority.authority)
assertEquals("xtext.org", uriWithAuthority.authority)
assertSame(uriWithAuthority, uriWithAuthority.withEmptyAuthority)
}
private def createTempDir(String prefix) {
return Files.createTempDirectory(tempDirPath, prefix);
}
private def getTempDirPath() {
return Paths.get(StandardSystemProperty.JAVA_IO_TMPDIR.value);
}
}

View file

@ -0,0 +1,132 @@
/**
* Copyright (c) 2016, 2020 TypeFox GmbH (http://www.typefox.io) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.ide.tests.testlanguage.ide;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import org.eclipse.lsp4j.Position;
import org.eclipse.lsp4j.jsonrpc.Endpoint;
import org.eclipse.lsp4j.jsonrpc.json.JsonRpcMethod;
import org.eclipse.lsp4j.jsonrpc.json.JsonRpcMethodProvider;
import org.eclipse.lsp4j.jsonrpc.services.JsonNotification;
import org.eclipse.lsp4j.jsonrpc.services.JsonRequest;
import org.eclipse.lsp4j.jsonrpc.services.ServiceEndpoints;
import org.eclipse.xtext.ide.server.ILanguageServerAccess;
import org.eclipse.xtext.ide.server.ILanguageServerAccess.IndexContext;
import org.eclipse.xtext.ide.server.ILanguageServerExtension;
import org.eclipse.xtext.ide.tests.testlanguage.testLanguage.TestLanguagePackage;
import org.eclipse.xtext.resource.IEObjectDescription;
import org.eclipse.xtext.resource.IResourceDescription;
import org.eclipse.xtext.xbase.lib.ListExtensions;
import org.eclipse.xtext.xbase.lib.util.ToStringBuilder;
import com.google.common.base.Joiner;
import com.google.inject.ImplementedBy;
/**
* @author efftinge - Initial contribution and API
*/
@ImplementedBy(TestLangLSPExtension.Impl.class)
public interface TestLangLSPExtension extends ILanguageServerExtension {
class TextOfLineResult {
public String text;
}
class TextOfLineParam {
public String uri;
public int line;
}
class BuildNotification {
public String message;
@Override
public String toString() {
ToStringBuilder b = new ToStringBuilder(this);
b.add("message", message);
return b.toString();
}
}
interface CustomClient {
@JsonNotification
void buildHappened(BuildNotification notification);
}
class Impl implements ILanguageServerExtension, TestLangLSPExtension, ILanguageServerAccess.IBuildListener,
JsonRpcMethodProvider {
private ILanguageServerAccess access;
private CustomClient client;
@Override
public CompletableFuture<TextOfLineResult> getTextOfLine(TextOfLineParam param) {
return access.doRead(param.uri, (ILanguageServerAccess.Context ctx) -> {
int start = ctx.getDocument().getOffSet(new Position(param.line, 0));
int end = ctx.getDocument().getOffSet(new Position(param.line + 1, 0))
- System.lineSeparator().length();
TextOfLineResult textOfLineResult = new TextOfLineResult();
textOfLineResult.text = ctx.getDocument().getContents().substring(start, end);
return textOfLineResult;
});
}
@Override
public void initialize(ILanguageServerAccess access) {
this.access = access;
this.access.addBuildListener(this);
this.client = ServiceEndpoints.toServiceObject((Endpoint) access.getLanguageClient(), CustomClient.class);
}
@Override
public void afterBuild(List<IResourceDescription.Delta> deltas) {
BuildNotification buildNotification = new BuildNotification();
buildNotification.message = "Built "
+ Joiner.on(", ").join(ListExtensions.map(deltas, d -> d.getUri().toString()), ", ");
client.buildHappened(buildNotification);
}
@Override
public Map<String, JsonRpcMethod> supportedMethods() {
HashMap<String, JsonRpcMethod> result = new HashMap<>();
result.putAll(ServiceEndpoints.getSupportedMethods(getClass()));
result.putAll(ServiceEndpoints.getSupportedMethods(CustomClient.class));
return result;
}
@Override
public CompletableFuture<Set<String>> getAllOpNames() {
return access
.doReadIndex((Function<IndexContext, Set<String>>) (ILanguageServerAccess.IndexContext context) -> {
Set<String> result = new HashSet<>();
for (IResourceDescription rd : context.getIndex().getAllResourceDescriptions()) {
for (IEObjectDescription o : rd.getExportedObjects()) {
if (TestLanguagePackage.Literals.OPERATION == o.getEClass()) {
result.add(o.getName().getLastSegment());
}
}
}
return result;
});
}
}
@JsonRequest
CompletableFuture<TextOfLineResult> getTextOfLine(TextOfLineParam param);
@JsonRequest
CompletableFuture<Set<String>> getAllOpNames();
}

View file

@ -1,103 +0,0 @@
/*******************************************************************************
* Copyright (c) 2016, 2017 TypeFox GmbH (http://www.typefox.io) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.xtext.ide.tests.testlanguage.ide
import com.google.inject.ImplementedBy
import java.util.List
import java.util.Set
import java.util.concurrent.CompletableFuture
import org.eclipse.lsp4j.Position
import org.eclipse.lsp4j.jsonrpc.Endpoint
import org.eclipse.lsp4j.jsonrpc.json.JsonRpcMethodProvider
import org.eclipse.lsp4j.jsonrpc.services.JsonNotification
import org.eclipse.lsp4j.jsonrpc.services.JsonRequest
import org.eclipse.lsp4j.jsonrpc.services.ServiceEndpoints
import org.eclipse.xtend.lib.annotations.ToString
import org.eclipse.xtext.ide.server.ILanguageServerAccess
import org.eclipse.xtext.ide.server.ILanguageServerAccess.IBuildListener
import org.eclipse.xtext.ide.server.ILanguageServerExtension
import org.eclipse.xtext.resource.IResourceDescription.Delta
import org.eclipse.xtext.ide.tests.testlanguage.testLanguage.TestLanguagePackage
/**
* @author efftinge - Initial contribution and API
*/
@ImplementedBy(TestLangLSPExtension.Impl)
interface TestLangLSPExtension extends ILanguageServerExtension {
@JsonRequest
def CompletableFuture<TextOfLineResult> getTextOfLine(TextOfLineParam param)
@JsonRequest
def CompletableFuture<Set<String>> getAllOpNames()
static class TextOfLineResult {
public String text
}
static class TextOfLineParam {
public String uri
public int line
}
@ToString
static class BuildNotification {
public String message
}
static interface CustomClient {
@JsonNotification
def void buildHappened(BuildNotification notification)
}
static class Impl implements ILanguageServerExtension, TestLangLSPExtension, IBuildListener, JsonRpcMethodProvider {
ILanguageServerAccess access
CustomClient client
override getTextOfLine(TextOfLineParam param) {
return access.doRead(param.uri) [ ctx |
val start = ctx.document.getOffSet(new Position(param.line, 0 ))
val end = ctx.document.getOffSet(new Position(param.line + 1, 0 )) -System.lineSeparator.length
return new TextOfLineResult => [
text = ctx.document.contents.substring(start, end)
]
]
}
override initialize(ILanguageServerAccess access) {
this.access = access
this.access.addBuildListener(this)
this.client = ServiceEndpoints.toServiceObject(access.languageClient as Endpoint, CustomClient)
}
override afterBuild(List<Delta> deltas) {
client.buildHappened(new BuildNotification => [
message = "Built "+deltas.map[uri.toString].join(', ')
])
}
override supportedMethods() {
val result = newHashMap
result.putAll(ServiceEndpoints.getSupportedMethods(this.getClass))
// register client side
result.putAll(ServiceEndpoints.getSupportedMethods(CustomClient))
return result
}
override getAllOpNames() {
return access.doReadIndex([ context |
context.index.allResourceDescriptions.map[exportedObjects].flatten.filter [
EClass === TestLanguagePackage.Literals.OPERATION
].map[name.lastSegment].toSet
])
}
}
}

View file

@ -0,0 +1,41 @@
/**
* Copyright (c) 2018, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.ide.tests.testlanguage.ide;
import org.eclipse.xtend2.lib.StringConcatenation;
import org.eclipse.xtext.RuleCall;
import org.eclipse.xtext.ide.editor.contentassist.ContentAssistContext;
import org.eclipse.xtext.ide.editor.contentassist.IIdeContentProposalAcceptor;
import org.eclipse.xtext.ide.editor.contentassist.IdeContentProposalProvider;
import org.eclipse.xtext.ide.tests.testlanguage.services.TestLanguageGrammarAccess;
import com.google.inject.Inject;
/**
* @author Christian Dietrich - Initial contribution and API
*/
public class TestLanguageIdeContentProposalProvider extends IdeContentProposalProvider {
@Inject
private TestLanguageGrammarAccess testLanguageGrammarAccess;
@Override
protected void _createProposals(RuleCall ruleCall, ContentAssistContext context,
IIdeContentProposalAcceptor acceptor) {
if (testLanguageGrammarAccess.getTypeDeclarationRule().equals(ruleCall.getRule())) {
StringConcatenation builder = new StringConcatenation();
builder.append("type ${1|A,B,C|} {");
builder.newLine();
builder.append("\t");
builder.newLine();
builder.append("}");
acceptor.accept(getProposalCreator().createSnippet(builder.toString(), "Sample Snippet", context), 0);
}
super._createProposals(ruleCall, context, acceptor);
}
}

View file

@ -1,34 +0,0 @@
/*******************************************************************************
* Copyright (c) 2018, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.xtext.ide.tests.testlanguage.ide
import com.google.inject.Inject
import org.eclipse.xtext.RuleCall
import org.eclipse.xtext.ide.editor.contentassist.ContentAssistContext
import org.eclipse.xtext.ide.editor.contentassist.IIdeContentProposalAcceptor
import org.eclipse.xtext.ide.editor.contentassist.IdeContentProposalProvider
import org.eclipse.xtext.ide.tests.testlanguage.services.TestLanguageGrammarAccess
/**
* @author Christian Dietrich - Initial contribution and API
*/
class TestLanguageIdeContentProposalProvider extends IdeContentProposalProvider {
@Inject extension TestLanguageGrammarAccess
override protected _createProposals(RuleCall ruleCall, ContentAssistContext context, IIdeContentProposalAcceptor acceptor) {
if (ruleCall.rule == typeDeclarationRule) {
acceptor.accept(proposalCreator.createSnippet('''type ${1|A,B,C|} {
}''', "Sample Snippet", context), 0)
}
super._createProposals(ruleCall, context, acceptor)
}
}

View file

@ -0,0 +1,114 @@
/**
* Copyright (c) 2017, 2020 TypeFox GmbH (http://www.typefox.io) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.ide.tests.testlanguage.ide.server;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.emf.common.util.ECollections;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.lsp4j.CodeAction;
import org.eclipse.lsp4j.Command;
import org.eclipse.lsp4j.Diagnostic;
import org.eclipse.lsp4j.Range;
import org.eclipse.lsp4j.TextEdit;
import org.eclipse.lsp4j.WorkspaceEdit;
import org.eclipse.lsp4j.jsonrpc.messages.Either;
import org.eclipse.xtext.formatting2.regionaccess.ITextReplacement;
import org.eclipse.xtext.ide.serializer.IChangeSerializer;
import org.eclipse.xtext.ide.serializer.IEmfResourceChange;
import org.eclipse.xtext.ide.serializer.ITextDocumentChange;
import org.eclipse.xtext.ide.server.codeActions.ICodeActionService2;
import org.eclipse.xtext.ide.tests.testlanguage.testLanguage.Member;
import org.eclipse.xtext.ide.tests.testlanguage.testLanguage.Model;
import org.eclipse.xtext.ide.tests.testlanguage.testLanguage.TypeDeclaration;
import org.eclipse.xtext.ide.tests.testlanguage.validation.TestLanguageValidator;
import org.eclipse.xtext.util.CollectionBasedAcceptor;
import org.eclipse.xtext.xbase.lib.ListExtensions;
import org.eclipse.xtext.xbase.lib.StringExtensions;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
/**
* @author Sven Efftinge - Initial contribution and API
*/
public class CodeActionService implements ICodeActionService2 {
@Inject
private IChangeSerializer serializer;
@Override
public List<Either<Command, CodeAction>> getCodeActions(ICodeActionService2.Options options) {
List<Either<Command, CodeAction>> actions = new ArrayList<>();
for (Diagnostic d : options.getCodeActionParams().getContext().getDiagnostics()) {
Object code = d.getCode().get();
if (TestLanguageValidator.INVALID_NAME.equals(code)) {
actions.add(Either.forLeft(fixInvalidName(d, options)));
} else if (TestLanguageValidator.UNSORTED_MEMBERS.equals(code)) {
actions.add(Either.forRight(fixUnsortedMembers(d, options)));
}
}
return actions;
}
private Command fixInvalidName(Diagnostic d, ICodeActionService2.Options options) {
String string = options.getDocument().getSubstring(d.getRange());
Command command = new Command();
command.setCommand("my.textedit.command");
command.setTitle("Make '" + string + "' upper case");
WorkspaceEdit workspaceEdit = new WorkspaceEdit();
TextEdit textEdit = new TextEdit();
textEdit.setNewText(StringExtensions.toFirstUpper(string));
textEdit.setRange(d.getRange());
workspaceEdit.getChanges().put(options.getCodeActionParams().getTextDocument().getUri(),
Lists.newArrayList(textEdit));
command.setArguments(Lists.newArrayList(workspaceEdit));
return command;
}
private CodeAction fixUnsortedMembers(Diagnostic d, ICodeActionService2.Options options) {
WorkspaceEdit wsEdit = recordWorkspaceEdit(options, (Resource copiedResource) -> {
Model model = Iterables.getFirst(Iterables.filter(copiedResource.getContents(), Model.class), null);
if (model != null) {
for (TypeDeclaration type : Iterables.filter(model.getElements(), TypeDeclaration.class)) {
ECollections.sort(type.getMembers(), (Member a, Member b) -> a.getName().compareTo(b.getName()));
}
}
});
CodeAction codeAction = new CodeAction();
codeAction.setTitle("Sort Members");
codeAction.setDiagnostics(Lists.newArrayList(d));
codeAction.setEdit(wsEdit);
return codeAction;
}
private WorkspaceEdit recordWorkspaceEdit(ICodeActionService2.Options options,
IChangeSerializer.IModification<Resource> mod) {
ResourceSet rs = options.getLanguageServerAccess().newLiveScopeResourceSet(options.getResource().getURI());
Resource copy = rs.getResource(options.getResource().getURI(), true);
serializer.addModification(copy, mod);
List<IEmfResourceChange> documentchanges = new ArrayList<>();
serializer.applyModifications(CollectionBasedAcceptor.of(documentchanges));
WorkspaceEdit workspaceEdit = new WorkspaceEdit();
for (ITextDocumentChange documentchange : Iterables.filter(documentchanges, ITextDocumentChange.class)) {
List<TextEdit> edits = ListExtensions.map(documentchange.getReplacements(),
(ITextReplacement replacement) -> {
TextEdit textEdit = new TextEdit();
textEdit.setNewText(replacement.getReplacementText());
textEdit.setRange(new Range(options.getDocument().getPosition(replacement.getOffset()),
options.getDocument().getPosition(replacement.getEndOffset())));
return textEdit;
});
workspaceEdit.getChanges().put(documentchange.getNewURI().toString(), edits);
}
return workspaceEdit;
}
}

View file

@ -1,98 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 TypeFox GmbH (http://www.typefox.io) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.xtext.ide.tests.testlanguage.ide.server
import com.google.inject.Inject
import org.eclipse.emf.common.util.ECollections
import org.eclipse.emf.ecore.resource.Resource
import org.eclipse.lsp4j.CodeAction
import org.eclipse.lsp4j.Command
import org.eclipse.lsp4j.Diagnostic
import org.eclipse.lsp4j.Range
import org.eclipse.lsp4j.TextEdit
import org.eclipse.lsp4j.WorkspaceEdit
import org.eclipse.lsp4j.jsonrpc.messages.Either
import org.eclipse.xtext.ide.serializer.IChangeSerializer
import org.eclipse.xtext.ide.serializer.IEmfResourceChange
import org.eclipse.xtext.ide.serializer.ITextDocumentChange
import org.eclipse.xtext.ide.server.codeActions.ICodeActionService2
import org.eclipse.xtext.ide.tests.testlanguage.testLanguage.Model
import org.eclipse.xtext.ide.tests.testlanguage.testLanguage.TypeDeclaration
import org.eclipse.xtext.util.CollectionBasedAcceptor
import static org.eclipse.xtext.ide.tests.testlanguage.validation.TestLanguageValidator.*
/**
* @author Sven Efftinge - Initial contribution and API
*/
class CodeActionService implements ICodeActionService2 {
@Inject IChangeSerializer serializer
override getCodeActions(Options options) {
val actions = newArrayList
for (d : options.codeActionParams.context.diagnostics) {
switch d.code.get {
case INVALID_NAME: actions += Either.forLeft(d.fixInvalidName(options))
case UNSORTED_MEMBERS: actions += Either.forRight(d.fixUnsortedMembers(options))
}
}
return actions
}
def private Command fixInvalidName(Diagnostic d, Options options) {
val string = options.document.getSubstring(d.range)
return new Command => [
command = 'my.textedit.command'
title = '''Make '«string»' upper case'''
arguments = #[
new WorkspaceEdit => [
changes.put(options.codeActionParams.textDocument.uri, #[new TextEdit => [
newText = string.toFirstUpper
range = d.range
]])
]
]
]
}
def private CodeAction fixUnsortedMembers(Diagnostic d, Options options) {
val wsEdit = recordWorkspaceEdit(options) [ copiedResource |
val model = copiedResource.contents.filter(Model).head
for (type : model.elements.filter(TypeDeclaration)) {
ECollections.sort(type.members, [a, b|a.name <=> b.name])
}
]
return new CodeAction => [
title = '''Sort Members'''
diagnostics = #[d]
edit = wsEdit
]
}
def private WorkspaceEdit recordWorkspaceEdit(Options options, IChangeSerializer.IModification<Resource> mod) {
val rs = options.languageServerAccess.newLiveScopeResourceSet(options.resource.URI)
val copy = rs.getResource(options.resource.URI, true)
serializer.addModification(copy, mod)
val documentchanges = <IEmfResourceChange>newArrayList()
serializer.applyModifications(CollectionBasedAcceptor.of(documentchanges))
return new WorkspaceEdit => [
for (documentchange : documentchanges.filter(ITextDocumentChange)) {
val edits = documentchange.replacements.map [ replacement |
new TextEdit => [
newText = replacement.replacementText
range = new Range(options.document.getPosition(replacement.offset), options.document.getPosition(replacement.endOffset))
]
]
changes.put(documentchange.newURI.toString, edits)
}
]
}
}

View file

@ -1,5 +1,5 @@
/**
* Copyright (c) 2017 TypeFox GmbH (http://www.typefox.io) and others.
* Copyright (c) 2017, 2020 TypeFox GmbH (http://www.typefox.io) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.

View file

@ -1,5 +1,5 @@
/**
* Copyright (c) 2016 TypeFox GmbH (http://www.typefox.io) and others.
* Copyright (c) 2016, 2020 TypeFox GmbH (http://www.typefox.io) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
@ -64,7 +64,6 @@ public class CompletionTest extends AbstractTestLangLanguageServerTest {
_builder.newLine();
_builder.append(" ");
_builder.newLine();
_builder.append(" ");
_builder.append("} [[0, 0] .. [0, 0]]");
_builder.newLine();
it.setExpectedCompletionItems(_builder.toString());
@ -214,7 +213,6 @@ public class CompletionTest extends AbstractTestLangLanguageServerTest {
_builder_1.newLine();
_builder_1.append(" ");
_builder_1.newLine();
_builder_1.append(" ");
_builder_1.append("} [[1, 0] .. [1, 0]]");
_builder_1.newLine();
it.setExpectedCompletionItems(_builder_1.toString());

View file

@ -1,288 +0,0 @@
/**
* Copyright (c) 2017 TypeFox GmbH (http://www.typefox.io) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.ide.tests.server;
import com.google.common.base.CharMatcher;
import com.google.common.base.StandardSystemProperty;
import com.google.inject.Inject;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.eclipse.emf.common.util.URI;
import org.eclipse.xtext.ide.server.UriExtensions;
import org.eclipse.xtext.ide.tests.testlanguage.TestLanguageIdeInjectorProvider;
import org.eclipse.xtext.testing.InjectWith;
import org.eclipse.xtext.testing.XtextRunner;
import org.eclipse.xtext.xbase.lib.Exceptions;
import org.eclipse.xtext.xbase.lib.Extension;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(XtextRunner.class)
@InjectWith(TestLanguageIdeInjectorProvider.class)
@SuppressWarnings("all")
public class UriExtensionsTest {
@Inject
@Extension
private UriExtensions _uriExtensions;
@Test
public void test_toUri01() {
Assert.assertEquals(
URI.createURI("file://path/to/resource"),
this._uriExtensions.toUri("file://path/to/resource"));
}
@Test
public void test_toUri_02() {
Assert.assertEquals(
URI.createURI("file:///path/to/resource"),
this._uriExtensions.toUri("file:///path/to/resource"));
}
@Test
public void test_toUri03() {
Assert.assertEquals(
URI.createURI("file://path%20with%20whitespaces/to/resource"),
this._uriExtensions.toUri("file://path%20with%20whitespaces/to/resource"));
}
@Test
public void test_toUri_04() {
Assert.assertEquals(
URI.createURI("file:///path%20with%20whitespaces/to/resource"),
this._uriExtensions.toUri("file:///path%20with%20whitespaces/to/resource"));
}
@Test
public void test_toUri_05() {
Assert.assertEquals(
URI.createURI("file:///dir/\u0424\u0443%20\u0411\u0430\u0440"),
this._uriExtensions.toUri("file:///dir/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80"));
}
@Test
public void test_toUri_06() {
Assert.assertEquals(
URI.createURI("file://dir/\u0424\u0443%20\u0411\u0430\u0440"),
this._uriExtensions.toUri("file://dir/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80"));
}
@Test
public void test_toUri_07() {
Assert.assertEquals(
URI.createURI("something:/path/to/resource"),
this._uriExtensions.toUri("something:/path/to/resource"));
}
@Test
public void test_toUri_08() {
Assert.assertEquals(
URI.createURI("something://path/to/resource"),
this._uriExtensions.toUri("something://path/to/resource"));
}
@Test
public void test_toUri_09() {
Assert.assertEquals(
URI.createURI("something:/dir/\u0424\u0443%20\u0411\u0430\u0440"),
this._uriExtensions.toUri("something:/dir/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80"));
}
@Test
public void test_toUri_10() {
Assert.assertEquals(
URI.createURI("something://dir/\u0424\u0443%20\u0411\u0430\u0440"),
this._uriExtensions.toUri("something://dir/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80"));
}
@Test
public void test_toUri_11() {
Assert.assertEquals(
URI.createURI("something:/path%20with%20whitespaces/to/resource"),
this._uriExtensions.toUri("something:/path%20with%20whitespaces/to/resource"));
}
@Test
public void test_toUri_12() {
Assert.assertEquals(
URI.createURI("something://path%20with%20whitespaces/to/resource"),
this._uriExtensions.toUri("something://path%20with%20whitespaces/to/resource"));
}
@Test
public void test_toUri_13() {
Assert.assertEquals(
URI.createURI("file:///c:/Users/dietrich/git/MyDSL_Imports/mydsl/workspace/src/something.mydsl"),
this._uriExtensions.toUri("file:///c%3A/Users/dietrich/git/MyDSL_Imports/mydsl/workspace/src/something.mydsl"));
}
@Test
public void test_toUri_14() {
Assert.assertEquals(
URI.createURI("file:///c:/Users/dietrich/\u0424\u0443%20\u0411\u0430\u0440.mydsl"),
this._uriExtensions.toUri("file:///c%3A/Users/dietrich/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80.mydsl"));
}
@Test
public void test_toUriString_01() {
Assert.assertEquals(
"file:///path/to/resource",
this._uriExtensions.toUriString(java.net.URI.create("file:///path/to/resource")));
}
@Test
public void test_toUriString_02() {
Assert.assertEquals(
"file://path/to/resource",
this._uriExtensions.toUriString(java.net.URI.create("file://path/to/resource")));
}
@Test
public void test_toUriString_03() {
Assert.assertEquals(
"file:///dir/\u0424\u0443%20\u0411\u0430\u0440",
this._uriExtensions.toUriString(java.net.URI.create("file:/dir/\u0424\u0443%20\u0411\u0430\u0440")));
}
@Test
public void test_toUriString_04() {
Assert.assertEquals(
"file://dir/\u0424\u0443%20\u0411\u0430\u0440",
this._uriExtensions.toUriString(java.net.URI.create("file://dir/\u0424\u0443%20\u0411\u0430\u0440")));
}
@Test
public void test_toUriString_05() {
Assert.assertEquals(
"file://path/to/resource/",
this._uriExtensions.toUriString(java.net.URI.create("file://path/to/resource/")));
}
@Test
public void test_toUriString_06() {
Assert.assertEquals(
"file:///path/to/resource/",
this._uriExtensions.toUriString(java.net.URI.create("file:/path/to/resource/")));
}
@Test
public void test_toUriString_07() {
Assert.assertEquals(
"file:///path/to/resource/",
this._uriExtensions.toUriString(java.net.URI.create("file:///path/to/resource/")));
}
@Test
public void test_symmetric_01() {
Assert.assertEquals(
URI.createURI("file:///path/to/resource"),
this._uriExtensions.toUri(this._uriExtensions.toUriString(java.net.URI.create("file:///path/to/resource"))));
}
@Test
public void test_symmetric_02() {
Assert.assertEquals(
URI.createURI("file://path/to/resource"),
this._uriExtensions.toUri(this._uriExtensions.toUriString(java.net.URI.create("file://path/to/resource"))));
}
@Test
public void test_symmetric_03() {
Assert.assertEquals(
URI.createURI("something:/path/to/resource"),
this._uriExtensions.toUri(this._uriExtensions.toUriString(java.net.URI.create("something:/path/to/resource"))));
}
@Test
public void test_symmetric_04() {
Assert.assertEquals(
URI.createURI("something://path/to/resource"),
this._uriExtensions.toUri(this._uriExtensions.toUriString(java.net.URI.create("something://path/to/resource"))));
}
@Test
public void testConversion() {
Assert.assertEquals("file:///dir/name.ext", this._uriExtensions.toUriString(this._uriExtensions.toUri("file:///dir/name.ext")));
}
@Test
public void testFileUriConversion() {
try {
final String expected = Paths.get(new File(".").getCanonicalPath()).resolve("dir").resolve("name.ext").toUri().toString();
Assert.assertEquals(expected, this._uriExtensions.toUriString(URI.createFileURI(new File("dir/name.ext").getAbsolutePath())));
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testFilesWithSpaces() {
final URI x = this._uriExtensions.toUri("file:///dir/Foo%20Bar.testlang");
final String y = this._uriExtensions.toUriString(x);
Assert.assertEquals("file:///dir/Foo%20Bar.testlang", y);
}
@Test
public void testFilesWithCyrillicSymbols() {
Assert.assertEquals("file:///dir/\u0424\u0443%20\u0411\u0430\u0440.testlang",
this._uriExtensions.toUriString(this._uriExtensions.toUri("file:///dir/%D0%A4%D1%83%20%D0%91%D0%B0%D1%80.testlang")));
}
@Test
public void testFolderIsPrefix() {
File directory = new File("./test-data2/test-project");
directory.mkdirs();
Assert.assertTrue(directory.exists());
Assert.assertTrue(directory.isDirectory());
String _absolutePath = directory.getAbsolutePath();
String _plus = (_absolutePath + "/");
URI uri = this._uriExtensions.toUri(this._uriExtensions.toUriString(URI.createFileURI(_plus)));
Assert.assertTrue(uri.isPrefix());
}
@Test
public void testFolderIsPrefixWithWhitespace() {
File directory = this.createTempDir("some name with whitespaces").toFile();
Assert.assertTrue(directory.exists());
Assert.assertTrue(directory.isDirectory());
Assert.assertTrue(CharMatcher.whitespace().matchesAnyOf(directory.getName()));
String _absolutePath = directory.getAbsolutePath();
String _plus = (_absolutePath + "/");
URI uri = this._uriExtensions.toUri(this._uriExtensions.toUriString(URI.createFileURI(_plus)));
Assert.assertTrue(uri.isPrefix());
}
@Test
public void test_withEmptyAuthority() {
final URI uriWithoutAuthority = URI.createURI("file:/path/to/resource/");
Assert.assertNull(uriWithoutAuthority.authority());
final URI uriWithEmptyAuthority = this._uriExtensions.withEmptyAuthority(uriWithoutAuthority);
Assert.assertNotSame(uriWithoutAuthority, uriWithEmptyAuthority);
Assert.assertEquals("Returned URI is expected to have an empty instead of null authority", "", uriWithEmptyAuthority.authority());
final URI uriWithAuthority = URI.createURI("https://xtext.org/path/to/resource/");
Assert.assertNotNull(uriWithAuthority.authority());
Assert.assertEquals("xtext.org", uriWithAuthority.authority());
Assert.assertSame(uriWithAuthority, this._uriExtensions.withEmptyAuthority(uriWithAuthority));
}
private Path createTempDir(final String prefix) {
try {
return Files.createTempDirectory(this.getTempDirPath(), prefix);
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
private Path getTempDirPath() {
return Paths.get(StandardSystemProperty.JAVA_IO_TMPDIR.value());
}
}

View file

@ -1,158 +0,0 @@
/**
* Copyright (c) 2016, 2017 TypeFox GmbH (http://www.typefox.io) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.ide.tests.testlanguage.ide;
import com.google.common.collect.Iterables;
import com.google.inject.ImplementedBy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.lsp4j.Position;
import org.eclipse.lsp4j.jsonrpc.Endpoint;
import org.eclipse.lsp4j.jsonrpc.json.JsonRpcMethod;
import org.eclipse.lsp4j.jsonrpc.json.JsonRpcMethodProvider;
import org.eclipse.lsp4j.jsonrpc.services.JsonNotification;
import org.eclipse.lsp4j.jsonrpc.services.JsonRequest;
import org.eclipse.lsp4j.jsonrpc.services.ServiceEndpoints;
import org.eclipse.lsp4j.services.LanguageClient;
import org.eclipse.xtend.lib.annotations.ToString;
import org.eclipse.xtext.ide.server.Document;
import org.eclipse.xtext.ide.server.ILanguageServerAccess;
import org.eclipse.xtext.ide.server.ILanguageServerExtension;
import org.eclipse.xtext.ide.tests.testlanguage.testLanguage.TestLanguagePackage;
import org.eclipse.xtext.resource.IEObjectDescription;
import org.eclipse.xtext.resource.IResourceDescription;
import org.eclipse.xtext.xbase.lib.CollectionLiterals;
import org.eclipse.xtext.xbase.lib.Functions.Function1;
import org.eclipse.xtext.xbase.lib.IterableExtensions;
import org.eclipse.xtext.xbase.lib.ListExtensions;
import org.eclipse.xtext.xbase.lib.ObjectExtensions;
import org.eclipse.xtext.xbase.lib.Procedures.Procedure1;
import org.eclipse.xtext.xbase.lib.Pure;
import org.eclipse.xtext.xbase.lib.util.ToStringBuilder;
/**
* @author efftinge - Initial contribution and API
*/
@ImplementedBy(TestLangLSPExtension.Impl.class)
@SuppressWarnings("all")
public interface TestLangLSPExtension extends ILanguageServerExtension {
class TextOfLineResult {
public String text;
}
class TextOfLineParam {
public String uri;
public int line;
}
@ToString
class BuildNotification {
public String message;
@Override
@Pure
public String toString() {
ToStringBuilder b = new ToStringBuilder(this);
b.add("message", this.message);
return b.toString();
}
}
interface CustomClient {
@JsonNotification
void buildHappened(final TestLangLSPExtension.BuildNotification notification);
}
class Impl implements ILanguageServerExtension, TestLangLSPExtension, ILanguageServerAccess.IBuildListener, JsonRpcMethodProvider {
private ILanguageServerAccess access;
private TestLangLSPExtension.CustomClient client;
@Override
public CompletableFuture<TestLangLSPExtension.TextOfLineResult> getTextOfLine(final TestLangLSPExtension.TextOfLineParam param) {
final Function<ILanguageServerAccess.Context, TestLangLSPExtension.TextOfLineResult> _function = (ILanguageServerAccess.Context ctx) -> {
Document _document = ctx.getDocument();
Position _position = new Position(param.line, 0);
final int start = _document.getOffSet(_position);
Document _document_1 = ctx.getDocument();
Position _position_1 = new Position((param.line + 1), 0);
int _offSet = _document_1.getOffSet(_position_1);
int _length = System.lineSeparator().length();
final int end = (_offSet - _length);
TestLangLSPExtension.TextOfLineResult _textOfLineResult = new TestLangLSPExtension.TextOfLineResult();
final Procedure1<TestLangLSPExtension.TextOfLineResult> _function_1 = (TestLangLSPExtension.TextOfLineResult it) -> {
it.text = ctx.getDocument().getContents().substring(start, end);
};
return ObjectExtensions.<TestLangLSPExtension.TextOfLineResult>operator_doubleArrow(_textOfLineResult, _function_1);
};
return this.access.<TestLangLSPExtension.TextOfLineResult>doRead(param.uri, _function);
}
@Override
public void initialize(final ILanguageServerAccess access) {
this.access = access;
this.access.addBuildListener(this);
LanguageClient _languageClient = access.getLanguageClient();
this.client = ServiceEndpoints.<TestLangLSPExtension.CustomClient>toServiceObject(((Endpoint) _languageClient), TestLangLSPExtension.CustomClient.class);
}
@Override
public void afterBuild(final List<IResourceDescription.Delta> deltas) {
TestLangLSPExtension.BuildNotification _buildNotification = new TestLangLSPExtension.BuildNotification();
final Procedure1<TestLangLSPExtension.BuildNotification> _function = (TestLangLSPExtension.BuildNotification it) -> {
final Function1<IResourceDescription.Delta, String> _function_1 = (IResourceDescription.Delta it_1) -> {
return it_1.getUri().toString();
};
String _join = IterableExtensions.join(ListExtensions.<IResourceDescription.Delta, String>map(deltas, _function_1), ", ");
String _plus = ("Built " + _join);
it.message = _plus;
};
TestLangLSPExtension.BuildNotification _doubleArrow = ObjectExtensions.<TestLangLSPExtension.BuildNotification>operator_doubleArrow(_buildNotification, _function);
this.client.buildHappened(_doubleArrow);
}
@Override
public Map<String, JsonRpcMethod> supportedMethods() {
final HashMap<String, JsonRpcMethod> result = CollectionLiterals.<String, JsonRpcMethod>newHashMap();
result.putAll(ServiceEndpoints.getSupportedMethods(this.getClass()));
result.putAll(ServiceEndpoints.getSupportedMethods(TestLangLSPExtension.CustomClient.class));
return result;
}
@Override
public CompletableFuture<Set<String>> getAllOpNames() {
final Function<ILanguageServerAccess.IndexContext, Set<String>> _function = (ILanguageServerAccess.IndexContext context) -> {
final Function1<IResourceDescription, Iterable<IEObjectDescription>> _function_1 = (IResourceDescription it) -> {
return it.getExportedObjects();
};
final Function1<IEObjectDescription, Boolean> _function_2 = (IEObjectDescription it) -> {
EClass _eClass = it.getEClass();
return Boolean.valueOf((_eClass == TestLanguagePackage.Literals.OPERATION));
};
final Function1<IEObjectDescription, String> _function_3 = (IEObjectDescription it) -> {
return it.getName().getLastSegment();
};
return IterableExtensions.<String>toSet(IterableExtensions.<IEObjectDescription, String>map(IterableExtensions.<IEObjectDescription>filter(Iterables.<IEObjectDescription>concat(IterableExtensions.<IResourceDescription, Iterable<IEObjectDescription>>map(context.getIndex().getAllResourceDescriptions(), _function_1)), _function_2), _function_3));
};
return this.access.<Set<String>>doReadIndex(_function);
}
}
@JsonRequest
CompletableFuture<TestLangLSPExtension.TextOfLineResult> getTextOfLine(final TestLangLSPExtension.TextOfLineParam param);
@JsonRequest
CompletableFuture<Set<String>> getAllOpNames();
}

View file

@ -1,51 +0,0 @@
/**
* Copyright (c) 2018, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.ide.tests.testlanguage.ide;
import com.google.common.base.Objects;
import com.google.inject.Inject;
import org.eclipse.xtend2.lib.StringConcatenation;
import org.eclipse.xtext.AbstractRule;
import org.eclipse.xtext.ParserRule;
import org.eclipse.xtext.RuleCall;
import org.eclipse.xtext.ide.editor.contentassist.ContentAssistContext;
import org.eclipse.xtext.ide.editor.contentassist.IIdeContentProposalAcceptor;
import org.eclipse.xtext.ide.editor.contentassist.IdeContentProposalCreator;
import org.eclipse.xtext.ide.editor.contentassist.IdeContentProposalProvider;
import org.eclipse.xtext.ide.tests.testlanguage.services.TestLanguageGrammarAccess;
import org.eclipse.xtext.xbase.lib.Extension;
/**
* @author Christian Dietrich - Initial contribution and API
*/
@SuppressWarnings("all")
public class TestLanguageIdeContentProposalProvider extends IdeContentProposalProvider {
@Inject
@Extension
private TestLanguageGrammarAccess _testLanguageGrammarAccess;
@Override
protected void _createProposals(final RuleCall ruleCall, final ContentAssistContext context, final IIdeContentProposalAcceptor acceptor) {
AbstractRule _rule = ruleCall.getRule();
ParserRule _typeDeclarationRule = this._testLanguageGrammarAccess.getTypeDeclarationRule();
boolean _equals = Objects.equal(_rule, _typeDeclarationRule);
if (_equals) {
IdeContentProposalCreator _proposalCreator = this.getProposalCreator();
StringConcatenation _builder = new StringConcatenation();
_builder.append("type ${1|A,B,C|} {");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("}");
acceptor.accept(_proposalCreator.createSnippet(_builder.toString(), "Sample Snippet", context), 0);
}
super._createProposals(ruleCall, context, acceptor);
}
}

View file

@ -1,159 +0,0 @@
/**
* Copyright (c) 2017 TypeFox GmbH (http://www.typefox.io) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.ide.tests.testlanguage.ide.server;
import com.google.common.base.Objects;
import com.google.common.collect.Iterables;
import com.google.inject.Inject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.eclipse.emf.common.util.ECollections;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.lsp4j.CodeAction;
import org.eclipse.lsp4j.Command;
import org.eclipse.lsp4j.Diagnostic;
import org.eclipse.lsp4j.Position;
import org.eclipse.lsp4j.Range;
import org.eclipse.lsp4j.TextEdit;
import org.eclipse.lsp4j.WorkspaceEdit;
import org.eclipse.lsp4j.jsonrpc.messages.Either;
import org.eclipse.xtend2.lib.StringConcatenation;
import org.eclipse.xtext.formatting2.regionaccess.ITextReplacement;
import org.eclipse.xtext.ide.serializer.IChangeSerializer;
import org.eclipse.xtext.ide.serializer.IEmfResourceChange;
import org.eclipse.xtext.ide.serializer.ITextDocumentChange;
import org.eclipse.xtext.ide.server.codeActions.ICodeActionService2;
import org.eclipse.xtext.ide.tests.testlanguage.testLanguage.Member;
import org.eclipse.xtext.ide.tests.testlanguage.testLanguage.Model;
import org.eclipse.xtext.ide.tests.testlanguage.testLanguage.TypeDeclaration;
import org.eclipse.xtext.ide.tests.testlanguage.validation.TestLanguageValidator;
import org.eclipse.xtext.util.CollectionBasedAcceptor;
import org.eclipse.xtext.xbase.lib.CollectionLiterals;
import org.eclipse.xtext.xbase.lib.Functions.Function1;
import org.eclipse.xtext.xbase.lib.IterableExtensions;
import org.eclipse.xtext.xbase.lib.ListExtensions;
import org.eclipse.xtext.xbase.lib.ObjectExtensions;
import org.eclipse.xtext.xbase.lib.Procedures.Procedure1;
import org.eclipse.xtext.xbase.lib.StringExtensions;
/**
* @author Sven Efftinge - Initial contribution and API
*/
@SuppressWarnings("all")
public class CodeActionService implements ICodeActionService2 {
@Inject
private IChangeSerializer serializer;
@Override
public List<Either<Command, CodeAction>> getCodeActions(final ICodeActionService2.Options options) {
final ArrayList<Either<Command, CodeAction>> actions = CollectionLiterals.<Either<Command, CodeAction>>newArrayList();
List<Diagnostic> _diagnostics = options.getCodeActionParams().getContext().getDiagnostics();
for (final Diagnostic d : _diagnostics) {
Object _get = d.getCode().get();
boolean _matched = false;
if (Objects.equal(_get, TestLanguageValidator.INVALID_NAME)) {
_matched=true;
Either<Command, CodeAction> _forLeft = Either.<Command, CodeAction>forLeft(this.fixInvalidName(d, options));
actions.add(_forLeft);
}
if (!_matched) {
if (Objects.equal(_get, TestLanguageValidator.UNSORTED_MEMBERS)) {
_matched=true;
Either<Command, CodeAction> _forRight = Either.<Command, CodeAction>forRight(this.fixUnsortedMembers(d, options));
actions.add(_forRight);
}
}
}
return actions;
}
private Command fixInvalidName(final Diagnostic d, final ICodeActionService2.Options options) {
final String string = options.getDocument().getSubstring(d.getRange());
Command _command = new Command();
final Procedure1<Command> _function = (Command it) -> {
it.setCommand("my.textedit.command");
StringConcatenation _builder = new StringConcatenation();
_builder.append("Make \'");
_builder.append(string);
_builder.append("\' upper case");
it.setTitle(_builder.toString());
WorkspaceEdit _workspaceEdit = new WorkspaceEdit();
final Procedure1<WorkspaceEdit> _function_1 = (WorkspaceEdit it_1) -> {
TextEdit _textEdit = new TextEdit();
final Procedure1<TextEdit> _function_2 = (TextEdit it_2) -> {
it_2.setNewText(StringExtensions.toFirstUpper(string));
it_2.setRange(d.getRange());
};
TextEdit _doubleArrow = ObjectExtensions.<TextEdit>operator_doubleArrow(_textEdit, _function_2);
it_1.getChanges().put(options.getCodeActionParams().getTextDocument().getUri(), Collections.<TextEdit>unmodifiableList(CollectionLiterals.<TextEdit>newArrayList(_doubleArrow)));
};
WorkspaceEdit _doubleArrow = ObjectExtensions.<WorkspaceEdit>operator_doubleArrow(_workspaceEdit, _function_1);
it.setArguments(Collections.<Object>unmodifiableList(CollectionLiterals.<Object>newArrayList(_doubleArrow)));
};
return ObjectExtensions.<Command>operator_doubleArrow(_command, _function);
}
private CodeAction fixUnsortedMembers(final Diagnostic d, final ICodeActionService2.Options options) {
final IChangeSerializer.IModification<Resource> _function = (Resource copiedResource) -> {
final Model model = IterableExtensions.<Model>head(Iterables.<Model>filter(copiedResource.getContents(), Model.class));
Iterable<TypeDeclaration> _filter = Iterables.<TypeDeclaration>filter(model.getElements(), TypeDeclaration.class);
for (final TypeDeclaration type : _filter) {
final Comparator<Member> _function_1 = (Member a, Member b) -> {
String _name = a.getName();
String _name_1 = b.getName();
return (_name.compareTo(_name_1));
};
ECollections.<Member>sort(type.getMembers(), _function_1);
}
};
final WorkspaceEdit wsEdit = this.recordWorkspaceEdit(options, _function);
CodeAction _codeAction = new CodeAction();
final Procedure1<CodeAction> _function_1 = (CodeAction it) -> {
StringConcatenation _builder = new StringConcatenation();
_builder.append("Sort Members");
it.setTitle(_builder.toString());
it.setDiagnostics(Collections.<Diagnostic>unmodifiableList(CollectionLiterals.<Diagnostic>newArrayList(d)));
it.setEdit(wsEdit);
};
return ObjectExtensions.<CodeAction>operator_doubleArrow(_codeAction, _function_1);
}
private WorkspaceEdit recordWorkspaceEdit(final ICodeActionService2.Options options, final IChangeSerializer.IModification<Resource> mod) {
final ResourceSet rs = options.getLanguageServerAccess().newLiveScopeResourceSet(options.getResource().getURI());
final Resource copy = rs.getResource(options.getResource().getURI(), true);
this.serializer.<Resource>addModification(copy, mod);
final ArrayList<IEmfResourceChange> documentchanges = CollectionLiterals.<IEmfResourceChange>newArrayList();
this.serializer.applyModifications(CollectionBasedAcceptor.<IEmfResourceChange>of(documentchanges));
WorkspaceEdit _workspaceEdit = new WorkspaceEdit();
final Procedure1<WorkspaceEdit> _function = (WorkspaceEdit it) -> {
Iterable<ITextDocumentChange> _filter = Iterables.<ITextDocumentChange>filter(documentchanges, ITextDocumentChange.class);
for (final ITextDocumentChange documentchange : _filter) {
{
final Function1<ITextReplacement, TextEdit> _function_1 = (ITextReplacement replacement) -> {
TextEdit _textEdit = new TextEdit();
final Procedure1<TextEdit> _function_2 = (TextEdit it_1) -> {
it_1.setNewText(replacement.getReplacementText());
Position _position = options.getDocument().getPosition(replacement.getOffset());
Position _position_1 = options.getDocument().getPosition(replacement.getEndOffset());
Range _range = new Range(_position, _position_1);
it_1.setRange(_range);
};
return ObjectExtensions.<TextEdit>operator_doubleArrow(_textEdit, _function_2);
};
final List<TextEdit> edits = ListExtensions.<ITextReplacement, TextEdit>map(documentchange.getReplacements(), _function_1);
it.getChanges().put(documentchange.getNewURI().toString(), edits);
}
}
};
return ObjectExtensions.<WorkspaceEdit>operator_doubleArrow(_workspaceEdit, _function);
}
}

View file

@ -0,0 +1,332 @@
/**
* Copyright (c) 2015, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.formatting2.regionaccess.internal;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.formatting2.regionaccess.IEObjectRegion;
import org.eclipse.xtext.formatting2.regionaccess.ISemanticRegion;
import org.eclipse.xtext.formatting2.regionaccess.ISemanticRegionsFinder;
import org.eclipse.xtext.formatting2.regionaccess.ITextRegionAccess;
import org.eclipse.xtext.formatting2.regionaccess.ITextSegment;
import org.eclipse.xtext.formatting2.regionaccess.TextRegionAccessBuilder;
import org.eclipse.xtext.formatting2.regionaccess.internal.regionaccesstestlanguage.AssignedAction;
import org.eclipse.xtext.formatting2.regionaccess.internal.regionaccesstestlanguage.Expression;
import org.eclipse.xtext.formatting2.regionaccess.internal.regionaccesstestlanguage.Mixed;
import org.eclipse.xtext.formatting2.regionaccess.internal.regionaccesstestlanguage.RegionaccesstestlanguagePackage;
import org.eclipse.xtext.formatting2.regionaccess.internal.regionaccesstestlanguage.Root;
import org.eclipse.xtext.formatting2.regionaccess.internal.services.RegionAccessTestLanguageGrammarAccess;
import org.eclipse.xtext.formatting2.regionaccess.internal.tests.RegionAccessTestLanguageInjectorProvider;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.testing.InjectWith;
import org.eclipse.xtext.testing.XtextRunner;
import org.eclipse.xtext.testing.util.ParseHelper;
import org.eclipse.xtext.testing.validation.ValidationTestHelper;
import org.eclipse.xtext.xbase.lib.Extension;
import org.eclipse.xtext.xbase.lib.Pair;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.inject.Inject;
import com.google.inject.Provider;
/**
* @author Moritz Eysholdt - Initial contribution and API
*/
@RunWith(XtextRunner.class)
@InjectWith(RegionAccessTestLanguageInjectorProvider.class)
public class SemanticRegionFinderTest {
@Inject
private ParseHelper<Root> parseHelper;
@Inject
private Provider<TextRegionAccessBuilder> textRegionAccessBuilder;
@Inject
private ValidationTestHelper validationTestHelper;
@Inject
private RegionAccessTestLanguageGrammarAccess grammarAccess;
@Test
public void regionForFeatureAttribute() throws Exception {
Mixed mixed = parseAs("6 (foo)", Mixed.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed).getRegionFor();
ISemanticRegion actual = finder.feature(RegionaccesstestlanguagePackage.Literals.MIXED__NAME);
List<ISemanticRegion> actuals = finder.features(RegionaccesstestlanguagePackage.Literals.MIXED__NAME);
assertEquals("foo", actual, actuals);
}
@Test
public void regionForFeatureCrossReference() throws Exception {
AssignedAction mixed = parseAs("6 (ref foo) action (foo) end", AssignedAction.class);
IEObjectRegion finder = toAccess(mixed).regionForEObject(mixed.getChild());
ISemanticRegion actual = finder.getRegionFor().feature(RegionaccesstestlanguagePackage.Literals.MIXED__REF);
List<ISemanticRegion> actuals = finder.getRegionFor()
.features(RegionaccesstestlanguagePackage.Literals.MIXED__REF);
assertEquals("foo", actual, actuals);
}
@Test
public void regionForFeatureContainmentReference() throws Exception {
AssignedAction mixed = parseAs("6 (foo) action", AssignedAction.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed).getRegionFor();
try {
finder.feature(RegionaccesstestlanguagePackage.Literals.ASSIGNED_ACTION__CHILD);
Assert.fail();
} catch (IllegalStateException e) {
// ok
}
try {
finder.features(RegionaccesstestlanguagePackage.Literals.ASSIGNED_ACTION__CHILD);
Assert.fail();
} catch (IllegalStateException e) {
// ok
}
}
@Test
public void regionForRuleCallUnassignedTerminal() throws Exception {
Mixed mixed = parseAs("6 (unassigned foo)", Mixed.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed).getRegionFor();
ISemanticRegion actual = finder
.ruleCall(grammarAccess.getMixedAccess().getIDTerminalRuleCall_1_1_0());
List<ISemanticRegion> actuals = finder
.ruleCalls(grammarAccess.getMixedAccess().getIDTerminalRuleCall_1_1_0());
assertEquals("foo", actual, actuals);
}
@Test
public void regionForRuleCallToUnassignedTerminal() throws Exception {
Mixed mixed = parseAs("6 (unassigned foo)", Mixed.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed).getRegionFor();
ISemanticRegion actual = finder.ruleCallTo(grammarAccess.getIDRule());
List<ISemanticRegion> actuals = finder.ruleCallsTo(grammarAccess.getIDRule());
assertEquals("foo", actual, actuals);
}
@Test
public void regionForRuleCallUnassignedDataType() throws Exception {
Mixed mixed = parseAs("6 (unassigned datatype foo)", Mixed.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed).getRegionFor();
ISemanticRegion actual = finder.ruleCall(
grammarAccess.getMixedAccess().getDatatypeParserRuleCall_1_1_1());
List<ISemanticRegion> actuals = finder.ruleCalls(
grammarAccess.getMixedAccess().getDatatypeParserRuleCall_1_1_1());
assertEquals("datatype foo", actual, actuals);
}
@Test
public void regionForRuleCallToUnassignedDataType() throws Exception {
Mixed mixed = parseAs("6 (unassigned datatype foo)", Mixed.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed).getRegionFor();
ISemanticRegion actual = finder.ruleCallTo(grammarAccess.getDatatypeRule());
List<ISemanticRegion> actuals = finder
.ruleCallsTo(grammarAccess.getDatatypeRule());
assertEquals("datatype foo", actual, actuals);
}
@Test
public void regionForRuleCallAssignedTerminal() throws Exception {
Mixed mixed = parseAs("6 (foo)", Mixed.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed).getRegionFor();
ISemanticRegion actual = finder.ruleCall(
grammarAccess.getMixedAccess().getNameIDTerminalRuleCall_2_2_0_0());
ISemanticRegion actuals = finder.ruleCall(
grammarAccess.getMixedAccess().getNameIDTerminalRuleCall_2_2_0_0());
Assert.assertEquals("foo", actual, actuals);
}
@Test
public void regionForRuleCallToAssignedTerminal() throws Exception {
Mixed mixed = parseAs("6 (foo)", Mixed.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed).getRegionFor();
ISemanticRegion actual = finder.ruleCallTo(grammarAccess.getIDRule());
ISemanticRegion actuals = finder.ruleCallTo(grammarAccess.getIDRule());
Assert.assertEquals("foo", actual, actuals);
}
@Test
public void regionForRuleCallAssignedDataType() throws Exception {
Mixed mixed = parseAs("6 (datatype foo)", Mixed.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed).getRegionFor();
ISemanticRegion actual = finder.ruleCall(grammarAccess.getMixedAccess()
.getDatatypeDatatypeParserRuleCall_2_2_2_0());
ISemanticRegion actuals = finder.ruleCall(grammarAccess.getMixedAccess()
.getDatatypeDatatypeParserRuleCall_2_2_2_0());
Assert.assertEquals("datatype foo", actual, actuals);
}
@Test
public void regionForRuleCallToAssignedDataType() throws Exception {
Mixed mixed = parseAs("6 (datatype foo)", Mixed.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed).getRegionFor();
ISemanticRegion actual = finder.ruleCallTo(grammarAccess.getDatatypeRule());
ISemanticRegion actuals = finder.ruleCallTo(grammarAccess.getDatatypeRule());
Assert.assertEquals("datatype foo", actual, actuals);
}
@Test
public void regionForRuleCallCrossReference() throws Exception {
AssignedAction mixed = parseAs("6 (ref foo) action (foo) end", AssignedAction.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed.getChild()).getRegionFor();
ISemanticRegion actual = finder.ruleCall(grammarAccess.getMixedAccess()
.getRefMixedIDTerminalRuleCall_2_2_3_1_0_1());
List<ISemanticRegion> actuals = finder.ruleCalls(grammarAccess.getMixedAccess()
.getRefMixedIDTerminalRuleCall_2_2_3_1_0_1());
assertEquals("foo", actual, actuals);
}
@Test
public void regionForRuleCallToCrossReference() throws Exception {
AssignedAction mixed = parseAs("6 (ref foo) action (foo) end", AssignedAction.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed.getChild()).getRegionFor();
ISemanticRegion actual = finder.ruleCallTo(grammarAccess.getIDRule());
List<ISemanticRegion> actuals = finder.ruleCallsTo(grammarAccess.getIDRule());
assertEquals("foo", actual, actuals);
}
@Test
public void regionForRuleCallEObjectParserRule() throws Exception {
Mixed mixed = parseAs("6 (child (foo))", Mixed.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed).getRegionFor();
try {
finder.ruleCall(grammarAccess.getMixedAccess()
.getEobjMixedParserRuleCall_2_2_1_1_0());
Assert.fail();
} catch (IllegalStateException e) {
// ok
}
try {
finder.ruleCalls(grammarAccess.getMixedAccess()
.getEobjMixedParserRuleCall_2_2_1_1_0());
Assert.fail();
} catch (IllegalStateException e) {
// ok
}
}
@Test
public void regionForRuleCallToEObjectParserRule() throws Exception {
Mixed mixed = parseAs("6 (child (foo))", Mixed.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed).getRegionFor();
try {
finder.ruleCallTo(grammarAccess.getMixedRule());
Assert.fail();
} catch (IllegalStateException e) {
// ok
}
try {
finder.ruleCallsTo(grammarAccess.getMixedRule());
Assert.fail();
} catch (IllegalStateException e) {
// ok
}
}
@Test
public void regionForKeywordString() throws Exception {
Mixed mixed = parseAs("6 (foo)", Mixed.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed).getRegionFor();
ISemanticRegion actual = finder.keyword("(");
List<ISemanticRegion> actuals = finder.keywords("(");
assertEquals("(", actual, actuals);
}
@Test
public void regionForKeyword() throws Exception {
Mixed mixed = parseAs("6 (foo)", Mixed.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed).getRegionFor();
ISemanticRegion actual = finder
.keyword(grammarAccess.getMixedAccess().getLeftParenthesisKeyword_0());
List<ISemanticRegion> actuals = finder
.keywords(grammarAccess.getMixedAccess().getLeftParenthesisKeyword_0());
assertEquals("(", actual, actuals);
}
@Test
public void regionForCrossReference() throws Exception {
AssignedAction mixed = parseAs("6 (ref foo) action (foo) end", AssignedAction.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed.getChild()).getRegionFor();
ISemanticRegion actual = finder.crossRef(
grammarAccess.getMixedAccess().getRefMixedCrossReference_2_2_3_1_0());
List<ISemanticRegion> actuals = finder.crossRefs(
grammarAccess.getMixedAccess().getRefMixedCrossReference_2_2_3_1_0());
assertEquals("foo", actual, actuals);
}
@Test
public void regionForAssignment() throws Exception {
Mixed mixed = parseAs("6 (foo)", Mixed.class);
ISemanticRegionsFinder finder = toAccess(mixed).regionForEObject(mixed).getRegionFor();
ISemanticRegion actual = finder
.assignment(grammarAccess.getMixedAccess().getNameAssignment_2_2_0());
List<ISemanticRegion> actuals = finder
.assignments(grammarAccess.getMixedAccess().getNameAssignment_2_2_0());
assertEquals("foo", actual, actuals);
}
@Test
public void regionForKeywordPairs() throws Exception {
@Extension
RegionAccessTestLanguageGrammarAccess.ParenthesizedElements rule = grammarAccess
.getParenthesizedAccess();
Expression expr = parseAs("5 (foo)", Expression.class);
ISemanticRegionsFinder finder = toAccess(expr).regionForEObject(expr).getRegionFor();
String actual1 = pairsToString(finder.keywordPairs("(", ")"));
String actual2 = pairsToString(
finder.keywordPairs(rule.getLeftParenthesisKeyword_0(), rule.getRightParenthesisKeyword_2()));
String expected = "(foo)";
Assert.assertEquals(expected, actual1);
Assert.assertEquals(expected, actual2);
}
@Test
public void regionForKeywordPairs2() throws Exception {
@Extension
RegionAccessTestLanguageGrammarAccess.ParenthesizedElements rule = grammarAccess
.getParenthesizedAccess();
Expression expr = parseAs("5 (a + ((b) + c) + d)", Expression.class);
ISemanticRegionsFinder finder = toAccess(expr).regionForRootEObject().getAllRegionsFor();
String actual1 = pairsToString(finder.keywordPairs("(", ")"));
String actual2 = pairsToString(
finder.keywordPairs(rule.getLeftParenthesisKeyword_0(), rule.getRightParenthesisKeyword_2()));
String expected = "(b); ((b) + c); (a + ((b) + c) + d)";
Assert.assertEquals(expected, actual1);
Assert.assertEquals(expected, actual2);
}
private String pairsToString(Iterable<Pair<ISemanticRegion, ISemanticRegion>> pairs) {
return Joiner.on("; ")
.join(Iterables.transform(pairs, it -> it.getKey().merge(it.getValue()).getText()));
}
private <T extends EObject> T parseAs(CharSequence seq, Class<T> cls) throws Exception {
Root result = parseHelper.parse(seq);
validationTestHelper.assertNoErrors(result);
return cls.cast(result);
}
private ITextRegionAccess toAccess(EObject obj) {
return textRegionAccessBuilder.get().forNodeModel((XtextResource) obj.eResource()).create();
}
private void assertEquals(String expected, ITextSegment single, Collection<? extends ITextSegment> regions) {
Assert.assertEquals(expected, single.getText());
Assert.assertEquals(1, regions.size());
Assert.assertEquals(expected, Iterables.getFirst(regions, null).getText());
Assert.assertTrue(regions instanceof ImmutableList<?>);
}
}

View file

@ -1,263 +0,0 @@
/*******************************************************************************
* Copyright (c) 2015, 2017 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.xtext.formatting2.regionaccess.internal
import com.google.common.collect.ImmutableList
import com.google.inject.Inject
import com.google.inject.Provider
import java.util.Collection
import org.eclipse.emf.ecore.EObject
import org.eclipse.xtext.formatting2.regionaccess.ISemanticRegion
import org.eclipse.xtext.formatting2.regionaccess.ITextRegionAccess
import org.eclipse.xtext.formatting2.regionaccess.ITextSegment
import org.eclipse.xtext.formatting2.regionaccess.TextRegionAccessBuilder
import org.eclipse.xtext.formatting2.regionaccess.internal.regionaccesstestlanguage.AssignedAction
import org.eclipse.xtext.formatting2.regionaccess.internal.regionaccesstestlanguage.Expression
import org.eclipse.xtext.formatting2.regionaccess.internal.regionaccesstestlanguage.Mixed
import org.eclipse.xtext.formatting2.regionaccess.internal.regionaccesstestlanguage.Root
import org.eclipse.xtext.formatting2.regionaccess.internal.services.RegionAccessTestLanguageGrammarAccess
import org.eclipse.xtext.formatting2.regionaccess.internal.tests.RegionAccessTestLanguageInjectorProvider
import org.eclipse.xtext.resource.XtextResource
import org.eclipse.xtext.testing.InjectWith
import org.eclipse.xtext.testing.XtextRunner
import org.eclipse.xtext.testing.util.ParseHelper
import org.eclipse.xtext.testing.validation.ValidationTestHelper
import org.junit.Test
import org.junit.runner.RunWith
import static org.eclipse.xtext.formatting2.regionaccess.internal.regionaccesstestlanguage.RegionaccesstestlanguagePackage.Literals.*
import static org.junit.Assert.*
/**
* @author Moritz Eysholdt - Initial contribution and API
*/
@RunWith(XtextRunner)
@InjectWith(RegionAccessTestLanguageInjectorProvider)
class SemanticRegionFinderTest {
@Inject extension ParseHelper<Root> parseHelper
@Inject Provider<TextRegionAccessBuilder> textRegionAccessBuilder
@Inject extension ValidationTestHelper validationTestHelper
@Inject extension RegionAccessTestLanguageGrammarAccess
@Test def void regionForFeatureAttribute() {
val mixed = '''6 (foo)'''.parseAs(Mixed)
val finder = mixed.toAccess.regionForEObject(mixed).regionFor
val actual = finder.feature(MIXED__NAME)
val actuals = finder.features(MIXED__NAME)
assertEquals("foo", actual, actuals)
}
@Test def void regionForFeatureCrossReference() {
val mixed = '''6 (ref foo) action (foo) end'''.parseAs(AssignedAction)
val finder = mixed.toAccess.regionForEObject(mixed.child)
val actual = finder.regionFor.feature(MIXED__REF)
val actuals = finder.regionFor.features(MIXED__REF)
assertEquals("foo", actual, actuals)
}
@Test def void regionForFeatureContainmentReference() {
val mixed = '''6 (foo) action'''.parseAs(AssignedAction)
val finder = mixed.toAccess.regionForEObject(mixed).regionFor
try {
finder.feature(ASSIGNED_ACTION__CHILD)
fail()
} catch (IllegalStateException e) {
}
try {
finder.features(ASSIGNED_ACTION__CHILD)
fail()
} catch (IllegalStateException e) {
}
}
@Test def void regionForRuleCallUnassignedTerminal() {
val mixed = '''6 (unassigned foo)'''.parseAs(Mixed)
val finder = mixed.toAccess.regionForEObject(mixed).regionFor
val actual = finder.ruleCall(mixedAccess.IDTerminalRuleCall_1_1_0)
val actuals = finder.ruleCalls(mixedAccess.IDTerminalRuleCall_1_1_0)
assertEquals("foo", actual, actuals)
}
@Test def void regionForRuleCallToUnassignedTerminal() {
val mixed = '''6 (unassigned foo)'''.parseAs(Mixed)
val finder = mixed.toAccess.regionForEObject(mixed).regionFor
val actual = finder.ruleCallTo(IDRule)
val actuals = finder.ruleCallsTo(IDRule)
assertEquals("foo", actual, actuals)
}
@Test def void regionForRuleCallUnassignedDataType() {
val mixed = '''6 (unassigned datatype foo)'''.parseAs(Mixed)
val finder = mixed.toAccess.regionForEObject(mixed).regionFor
val actual = finder.ruleCall(mixedAccess.datatypeParserRuleCall_1_1_1)
val actuals = finder.ruleCalls(mixedAccess.datatypeParserRuleCall_1_1_1)
assertEquals("datatype foo", actual, actuals)
}
@Test def void regionForRuleCallToUnassignedDataType() {
val mixed = '''6 (unassigned datatype foo)'''.parseAs(Mixed)
val finder = mixed.toAccess.regionForEObject(mixed).regionFor
val actual = finder.ruleCallTo(datatypeRule)
val actuals = finder.ruleCallsTo(datatypeRule)
assertEquals("datatype foo", actual, actuals)
}
@Test def void regionForRuleCallAssignedTerminal() {
val mixed = '''6 (foo)'''.parseAs(Mixed)
val finder = mixed.toAccess.regionForEObject(mixed).regionFor
val actual = finder.ruleCall(mixedAccess.nameIDTerminalRuleCall_2_2_0_0)
val actuals = finder.ruleCall(mixedAccess.nameIDTerminalRuleCall_2_2_0_0)
assertEquals("foo", actual, actuals)
}
@Test def void regionForRuleCallToAssignedTerminal() {
val mixed = '''6 (foo)'''.parseAs(Mixed)
val finder = mixed.toAccess.regionForEObject(mixed).regionFor
val actual = finder.ruleCallTo(IDRule)
val actuals = finder.ruleCallTo(IDRule)
assertEquals("foo", actual, actuals)
}
@Test def void regionForRuleCallAssignedDataType() {
val mixed = '''6 (datatype foo)'''.parseAs(Mixed)
val finder = mixed.toAccess.regionForEObject(mixed).regionFor
val actual = finder.ruleCall(mixedAccess.datatypeDatatypeParserRuleCall_2_2_2_0)
val actuals = finder.ruleCall(mixedAccess.datatypeDatatypeParserRuleCall_2_2_2_0)
assertEquals("datatype foo", actual, actuals)
}
@Test def void regionForRuleCallToAssignedDataType() {
val mixed = '''6 (datatype foo)'''.parseAs(Mixed)
val finder = mixed.toAccess.regionForEObject(mixed).regionFor
val actual = finder.ruleCallTo(datatypeRule)
val actuals = finder.ruleCallTo(datatypeRule)
assertEquals("datatype foo", actual, actuals)
}
@Test def void regionForRuleCallCrossReference() {
val mixed = '''6 (ref foo) action (foo) end'''.parseAs(AssignedAction)
val finder = mixed.toAccess.regionForEObject(mixed.child).regionFor
val actual = finder.ruleCall(mixedAccess.refMixedIDTerminalRuleCall_2_2_3_1_0_1)
val actuals = finder.ruleCalls(mixedAccess.refMixedIDTerminalRuleCall_2_2_3_1_0_1)
assertEquals("foo", actual, actuals)
}
@Test def void regionForRuleCallToCrossReference() {
val mixed = '''6 (ref foo) action (foo) end'''.parseAs(AssignedAction)
val finder = mixed.toAccess.regionForEObject(mixed.child).regionFor
val actual = finder.ruleCallTo(IDRule)
val actuals = finder.ruleCallsTo(IDRule)
assertEquals("foo", actual, actuals)
}
@Test def void regionForRuleCallEObjectParserRule() {
val mixed = '''6 (child (foo))'''.parseAs(Mixed)
val finder = mixed.toAccess.regionForEObject(mixed).regionFor
try {
finder.ruleCall(mixedAccess.eobjMixedParserRuleCall_2_2_1_1_0)
fail()
} catch (IllegalStateException e) {
}
try {
finder.ruleCalls(mixedAccess.eobjMixedParserRuleCall_2_2_1_1_0)
fail()
} catch (IllegalStateException e) {
}
}
@Test def void regionForRuleCallToEObjectParserRule() {
val mixed = '''6 (child (foo))'''.parseAs(Mixed)
val finder = mixed.toAccess.regionForEObject(mixed).regionFor
try {
finder.ruleCallTo(mixedRule)
fail()
} catch (IllegalStateException e) {
}
try {
finder.ruleCallsTo(mixedRule)
fail()
} catch (IllegalStateException e) {
}
}
@Test def void regionForKeywordString() {
val mixed = '''6 (foo)'''.parseAs(Mixed)
val finder = mixed.toAccess.regionForEObject(mixed).regionFor
val actual = finder.keyword("(")
val actuals = finder.keywords("(")
assertEquals("(", actual, actuals)
}
@Test def void regionForKeyword() {
val mixed = '''6 (foo)'''.parseAs(Mixed)
val finder = mixed.toAccess.regionForEObject(mixed).regionFor
val actual = finder.keyword(mixedAccess.leftParenthesisKeyword_0)
val actuals = finder.keywords(mixedAccess.leftParenthesisKeyword_0)
assertEquals("(", actual, actuals)
}
@Test def void regionForCrossReference() {
val mixed = '''6 (ref foo) action (foo) end'''.parseAs(AssignedAction)
val finder = mixed.toAccess.regionForEObject(mixed.child).regionFor
val actual = finder.crossRef(mixedAccess.refMixedCrossReference_2_2_3_1_0)
val actuals = finder.crossRefs(mixedAccess.refMixedCrossReference_2_2_3_1_0)
assertEquals("foo", actual, actuals)
}
@Test def void regionForAssignment() {
val mixed = '''6 (foo)'''.parseAs(Mixed)
val finder = mixed.toAccess.regionForEObject(mixed).regionFor
val actual = finder.assignment(mixedAccess.nameAssignment_2_2_0)
val actuals = finder.assignments(mixedAccess.nameAssignment_2_2_0)
assertEquals("foo", actual, actuals)
}
@Test def void regionForKeywordPairs() {
val extension rule = parenthesizedAccess
val expr = '''5 (foo)'''.parseAs(Expression)
val finder = expr.toAccess.regionForEObject(expr).regionFor
val actual1 = finder.keywordPairs("(", ")").pairsToString
val actual2 = finder.keywordPairs(leftParenthesisKeyword_0, rightParenthesisKeyword_2).pairsToString
val expected = "(foo)"
assertEquals(expected, actual1)
assertEquals(expected, actual2)
}
@Test def void regionForKeywordPairs2() {
val extension rule = parenthesizedAccess
val expr = '''5 (a + ((b) + c) + d)'''.parseAs(Expression)
val finder = expr.toAccess.regionForRootEObject.allRegionsFor
val actual1 = finder.keywordPairs("(", ")").pairsToString
val actual2 = finder.keywordPairs(leftParenthesisKeyword_0, rightParenthesisKeyword_2).pairsToString
val expected = "(b); ((b) + c); (a + ((b) + c) + d)"
assertEquals(expected, actual1)
assertEquals(expected, actual2)
}
def private String pairsToString(Iterable<Pair<ISemanticRegion, ISemanticRegion>> pairs) {
pairs.map[key.merge(value).text].join("; ")
}
def private <T extends EObject> parseAs(CharSequence seq, Class<T> cls) {
val result = seq.parse
result.assertNoErrors
return cls.cast(result)
}
def private ITextRegionAccess toAccess(EObject obj) {
return textRegionAccessBuilder.get.forNodeModel(obj.eResource as XtextResource).create
}
def private void assertEquals(String expected, ITextSegment single, Collection<? extends ITextSegment> regions) {
assertEquals(expected, single.text)
assertEquals(1, regions.size)
assertEquals(expected, regions.head.text)
assertTrue(regions instanceof ImmutableList<?>)
}
}

View file

@ -0,0 +1,194 @@
/**
* Copyright (c) 2015, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.parser.parameters;
import org.eclipse.xtext.parser.parameters.parametersTestLanguage.ParserRuleParameters;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.tests.AbstractXtextTests;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.collect.Iterables;
import com.google.inject.Injector;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
public abstract class AbstractParametersParsingTest extends AbstractXtextTests {
@Override
protected void setInjector(Injector injector) {
super.setInjector(injector);
injectMembers(this);
}
@Override
protected boolean shouldTestSerializer(XtextResource resource) {
return false;
}
@Override
public ParserRuleParameters getModel(String model) throws Exception {
return (ParserRuleParameters) super.getModel(model);
}
protected ParserRuleParameters getModelWithErrors(String model) throws Exception {
return (ParserRuleParameters) getModelAndExpect(model, AbstractXtextTests.EXPECT_ERRORS);
}
@Test
public void testScenario1_first() throws Exception {
ParserRuleParameters instance = getModel("#1 first");
Assert.assertEquals("first", instance.getScenario().getFirst());
}
@Test
public void testScenario2_second() throws Exception {
ParserRuleParameters instance = getModel("#2 second");
Assert.assertEquals("second", instance.getScenario().getSecond());
}
@Test
public void testScenario3_keyword() throws Exception {
ParserRuleParameters instance = getModel("#3 keyword");
Assert.assertEquals("keyword", instance.getScenario().getFirst());
}
@Test
public void testScenario3_id() throws Exception {
ParserRuleParameters instance = getModel("#3 id");
Assert.assertEquals("id", instance.getScenario().getFirst());
}
@Test
public void testScenario4_keyword() throws Exception {
ParserRuleParameters instance = getModelWithErrors("#4 keyword");
Assert.assertEquals(null, instance.getScenario().getFirst());
Assert.assertEquals(1, instance.eResource().getErrors().size());
Assert.assertEquals("mismatched input 'keyword' expecting RULE_ID",
Iterables.getFirst(instance.eResource().getErrors(), null).getMessage());
}
@Test
public void testScenario4_id() throws Exception {
ParserRuleParameters instance = getModel("#4 id");
Assert.assertEquals("id", instance.getScenario().getFirst());
}
@Test
public void testScenario5_keyword() throws Exception {
ParserRuleParameters instance = getModel("#5 keyword");
Assert.assertEquals("keyword", instance.getScenario().getFirst());
}
@Test
public void testScenario5_id() throws Exception {
ParserRuleParameters instance = getModel("#5 id");
Assert.assertEquals("id", instance.getScenario().getFirst());
}
@Test
public void testScenario6_keyword() throws Exception {
ParserRuleParameters instance = getModelWithErrors("#6 keyword");
Assert.assertEquals(null, instance.getScenario());
Assert.assertEquals("no viable alternative at input '#6'",
Iterables.getFirst(instance.eResource().getErrors(), null).getMessage());
}
@Test
public void testScenario6_id() throws Exception {
ParserRuleParameters instance = getModel("#6 id");
Assert.assertEquals("id", instance.getScenario().getFirst());
}
@Test
public void testScenario7_keyword() throws Exception {
ParserRuleParameters instance = getModel("#7 keyword");
Assert.assertEquals("keyword", instance.getScenario().getFirst());
}
@Test
public void testScenario7_id() throws Exception {
ParserRuleParameters instance = getModel("#7 id");
Assert.assertEquals("id", instance.getScenario().getFirst());
}
@Test
public void testScenario8_keyword() throws Exception {
ParserRuleParameters instance = getModel("#8 keyword");
Assert.assertEquals("keyword", instance.getScenario().getSecond());
}
@Test
public void testScenario8_id() throws Exception {
ParserRuleParameters instance = getModel("#8 id");
Assert.assertEquals("id", instance.getScenario().getFirst());
}
@Test
public void testScenario9_keyword_keyword() throws Exception {
ParserRuleParameters instance = getModel("#9 keyword keyword");
Assert.assertEquals("keyword", instance.getScenario().getSecond());
}
@Test
public void testScenario9_id_keyword() throws Exception {
ParserRuleParameters instance = getModel("#9 id keyword");
Assert.assertEquals("id", instance.getScenario().getSecond());
}
@Test
public void testScenario9_id() throws Exception {
ParserRuleParameters instance = getModel("#9 id");
Assert.assertEquals("id", instance.getScenario().getFirst());
}
@Test
public void testScenario9_keyword() throws Exception {
ParserRuleParameters instance = getModel("#9 keyword");
Assert.assertEquals("keyword", instance.getScenario().getFirst());
}
@Test
public void testScenario10_keyword_keyword() throws Exception {
ParserRuleParameters instance = getModel("#10 keyword keyword");
Assert.assertEquals("keyword", instance.getScenario().getSecond());
}
@Test
public void testScenario10_id_keyword() throws Exception {
ParserRuleParameters instance = getModel("#10 id keyword");
Assert.assertEquals("id", instance.getScenario().getSecond());
}
@Test
public void testScenario10_id() throws Exception {
ParserRuleParameters instance = getModel("#10 id");
Assert.assertEquals("id", instance.getScenario().getFirst());
}
@Test
public void testScenario10_keyword() throws Exception {
ParserRuleParameters instance = getModelWithErrors("#10 keyword");
Assert.assertEquals("keyword", instance.getScenario().getSecond());
Assert.assertEquals("mismatched input '<EOF>' expecting 'keyword'",
Iterables.getFirst(instance.eResource().getErrors(), null).getMessage());
}
@Test
public void testScenario11_keyword_keyword() throws Exception {
ParserRuleParameters instance = getModel("#11 keyword keyword");
Assert.assertEquals("keyword", instance.getScenario().getFirst());
}
@Test
public void testScenario11_id_keyword() throws Exception {
ParserRuleParameters instance = getModel("#11 id keyword");
Assert.assertEquals("id", instance.getScenario().getSecond());
}
}

View file

@ -1,187 +0,0 @@
/*******************************************************************************
* Copyright (c) 2015 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.xtext.parser.parameters
import com.google.inject.Injector
import org.eclipse.xtext.parser.parameters.parametersTestLanguage.ParserRuleParameters
import org.eclipse.xtext.resource.XtextResource
import org.eclipse.xtext.tests.AbstractXtextTests
import org.junit.Test
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
abstract class AbstractParametersParsingTest extends AbstractXtextTests {
override protected setInjector(Injector injector) {
super.setInjector(injector)
injectMembers(this)
}
override protected shouldTestSerializer(XtextResource resource) {
// TODO implement serializer support for guard conditions
false
}
override ParserRuleParameters getModel(String model) throws Exception {
return super.getModel(model) as ParserRuleParameters
}
protected def getModelWithErrors(String model) throws Exception {
return getModelAndExpect(model, EXPECT_ERRORS) as ParserRuleParameters
}
@Test
def void testScenario1_first() {
val instance = '#1 first'.model
assertEquals('first', instance.scenario.first)
}
@Test
def void testScenario2_second() {
val instance = '#2 second'.model
assertEquals('second', instance.scenario.second)
}
@Test
def void testScenario3_keyword() {
val instance = '#3 keyword'.model
assertEquals('keyword', instance.scenario.first)
}
@Test
def void testScenario3_id() {
val instance = '#3 id'.model
assertEquals('id', instance.scenario.first)
}
@Test
def void testScenario4_keyword() {
val instance = '#4 keyword'.modelWithErrors
assertEquals(null, instance.scenario.first)
assertEquals(1, instance.eResource.errors.size)
assertEquals("mismatched input 'keyword' expecting RULE_ID", instance.eResource.errors.head.message)
}
@Test
def void testScenario4_id() {
val instance = '#4 id'.model
assertEquals('id', instance.scenario.first)
}
@Test
def void testScenario5_keyword() {
val instance = '#5 keyword'.model
assertEquals('keyword', instance.scenario.first)
}
@Test
def void testScenario5_id() {
val instance = '#5 id'.model
assertEquals('id', instance.scenario.first)
}
@Test
def void testScenario6_keyword() {
val instance = '#6 keyword'.modelWithErrors
assertEquals(null, instance.scenario)
assertEquals("no viable alternative at input '#6'", instance.eResource.errors.head.message)
}
@Test
def void testScenario6_id() {
val instance = '#6 id'.model
assertEquals('id', instance.scenario.first)
}
@Test
def void testScenario7_keyword() {
val instance = '#7 keyword'.model
assertEquals('keyword', instance.scenario.first)
}
@Test
def void testScenario7_id() {
val instance = '#7 id'.model
assertEquals('id', instance.scenario.first)
}
@Test
def void testScenario8_keyword() {
val instance = '#8 keyword'.model
assertEquals('keyword', instance.scenario.second)
}
@Test
def void testScenario8_id() {
val instance = '#8 id'.model
assertEquals('id', instance.scenario.first)
}
@Test
def void testScenario9_keyword_keyword() {
val instance = '#9 keyword keyword'.model
assertEquals('keyword', instance.scenario.second)
}
@Test
def void testScenario9_id_keyword() {
val instance = '#9 id keyword'.model
assertEquals('id', instance.scenario.second)
}
@Test
def void testScenario9_id() {
val instance = '#9 id'.model
assertEquals('id', instance.scenario.first)
}
@Test
def void testScenario9_keyword() {
val instance = '#9 keyword'.model
assertEquals('keyword', instance.scenario.first)
}
@Test
def void testScenario10_keyword_keyword() {
val instance = '#10 keyword keyword'.model
assertEquals('keyword', instance.scenario.second)
}
@Test
def void testScenario10_id_keyword() {
val instance = '#10 id keyword'.model
assertEquals('id', instance.scenario.second)
}
@Test
def void testScenario10_id() {
val instance = '#10 id'.model
assertEquals('id', instance.scenario.first)
}
@Test
def void testScenario10_keyword() {
val instance = '#10 keyword'.modelWithErrors
assertEquals('keyword', instance.scenario.second)
assertEquals("mismatched input '<EOF>' expecting 'keyword'", instance.eResource.errors.head.message)
}
@Test
def void testScenario11_keyword_keyword() {
val instance = '#11 keyword keyword'.model
assertEquals('keyword', instance.scenario.first)
}
@Test
def void testScenario11_id_keyword() {
val instance = '#11 id keyword'.model
assertEquals('id', instance.scenario.second)
}
}

View file

@ -0,0 +1,20 @@
/**
* Copyright (c) 2015, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.parser.parameters;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
public class NoParametersParsingTest extends AbstractParametersParsingTest {
@Override
public void setUp() throws Exception {
super.setUp();
this.with(new NoParametersTestLanguageStandaloneSetup());
}
}

View file

@ -0,0 +1,21 @@
/**
* Copyright (c) 2015, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.parser.parameters;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
public class ParametersParsingTest extends AbstractParametersParsingTest {
@Override
public void setUp() throws Exception {
super.setUp();
with(new ParametersTestLanguageStandaloneSetup());
}
}

View file

@ -0,0 +1,20 @@
/**
* Copyright (c) 2015, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.parser.parameters;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
public class ParametersParsingTestEx extends AbstractParametersParsingTest {
@Override
public void setUp() throws Exception {
super.setUp();
this.with(new ParametersTestLanguageExStandaloneSetup());
}
}

View file

@ -1,49 +0,0 @@
/*******************************************************************************
* Copyright (c) 2015 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.xtext.parser.parameters
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
class ParametersParsingTest extends AbstractParametersParsingTest {
override void setUp() throws Exception {
super.setUp();
with(new ParametersTestLanguageStandaloneSetup);
}
}
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
class TwoParametersParsingTest extends AbstractParametersParsingTest {
override void setUp() throws Exception {
super.setUp();
with(new TwoParametersTestLanguageStandaloneSetup);
}
}
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
class ParametersParsingTestEx extends AbstractParametersParsingTest {
override void setUp() throws Exception {
super.setUp();
with(new ParametersTestLanguageExStandaloneSetup);
}
}
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
class NoParametersParsingTest extends AbstractParametersParsingTest {
override void setUp() throws Exception {
super.setUp();
with(new NoParametersTestLanguageStandaloneSetup);
}
}

View file

@ -0,0 +1,20 @@
/**
* Copyright (c) 2015, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.parser.parameters;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
public class TwoParametersParsingTest extends AbstractParametersParsingTest {
@Override
public void setUp() throws Exception {
super.setUp();
this.with(new TwoParametersTestLanguageStandaloneSetup());
}
}

View file

@ -0,0 +1,73 @@
/**
* Copyright (c) 2012, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.resource;
import java.io.File;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.base.Objects;
/**
* @author Sven Efftinge - Initial contribution and API
*/
public abstract class AbstractResourceSetTest {
protected abstract ResourceSetImpl createEmptyResourceSet();
@Test
public void testDemandLoadedResourcesAreInMap() {
ResourceSetImpl rs = this.createEmptyResourceSet();
Resource.Factory nullFactory = new Resource.Factory() {
@Override
public Resource createResource(URI uri) {
NullResource result = new NullResource();
result.setURI(uri);
return result;
}
};
rs.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi", nullFactory);
Assert.assertEquals(0, rs.getURIResourceMap().size());
URI uri = URI.createURI("file:/does/not/exist.xmi");
Resource demandLoaded = rs.getResource(uri, true);
Assert.assertNotNull(demandLoaded);
Resource second = rs.getResource(uri, true);
Assert.assertSame(demandLoaded, second);
Assert.assertEquals(1, rs.getURIResourceMap().size());
}
@Test
public void testResourceLocatorIsUsed() {
ResourceSetImpl rs = this.createEmptyResourceSet();
XtextResource resource = new XtextResource();
resource.setURI(URI.createFileURI(new File("foo").getAbsolutePath()));
new ResourceSetImpl.ResourceLocator(rs) {
@Override
public Resource getResource(URI uri, boolean loadOnDemand) {
if (Objects.equal(uri, resource.getURI())) {
return resource;
}
throw new IllegalArgumentException(uri.toString());
}
};
Assert.assertSame(resource, rs.getResource(resource.getURI(), true));
Assert.assertTrue(rs.getResources().isEmpty());
Assert.assertNull(resource.getResourceSet());
try {
rs.getResource(resource.getURI().appendSegment("doesNotExist"), true);
Assert.fail();
} catch (IllegalArgumentException e) {
Assert.assertTrue(e.getMessage().endsWith("doesNotExist"));
}
}
}

View file

@ -0,0 +1,47 @@
/**
* Copyright (c) 2014, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.resource;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.testlanguages.OptionalEmptyTestLanguageStandaloneSetup;
import org.eclipse.xtext.tests.AbstractXtextTests;
import org.eclipse.xtext.util.StringInputStream;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Jan Koehnlein - Initial contribution and API
*/
public class Bug451668Test extends AbstractXtextTests {
public static class TestResource extends DerivedStateAwareResource {
private int contentsCalls = 0;
@Override
public synchronized EList<EObject> getContents() {
contentsCalls++;
return super.getContents();
}
}
@Test
public void testUnloadAndGetContents() throws Exception {
with(OptionalEmptyTestLanguageStandaloneSetup.class);
Bug451668Test.TestResource r = get(Bug451668Test.TestResource.class);
r.setURI(URI.createURI("foo.dummy"));
r.load(new StringInputStream(""), null);
Assert.assertTrue(r.isLoaded());
int callsBeforeUnload = r.contentsCalls;
r.unload();
Assert.assertEquals(callsBeforeUnload, r.contentsCalls);
Assert.assertFalse(r.isLoaded());
Assert.assertNull(r.getParseResult());
}
}

View file

@ -1,46 +0,0 @@
/*******************************************************************************
* Copyright (c) 2014, 2017 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.xtext.resource
import java.io.IOException
import org.eclipse.emf.common.util.EList
import org.eclipse.emf.common.util.URI
import org.eclipse.emf.ecore.EObject
import org.eclipse.xtext.testlanguages.OptionalEmptyTestLanguageStandaloneSetup
import org.eclipse.xtext.tests.AbstractXtextTests
import org.eclipse.xtext.util.StringInputStream
import org.junit.Test
/**
* @author Jan Koehnlein - Initial contribution and API
*/
class Bug451668Test extends AbstractXtextTests {
static class TestResource extends DerivedStateAwareResource {
int contentsCalls = 0
override synchronized EList<EObject> getContents() {
contentsCalls++;
return super.getContents()
}
}
@Test def void testUnloadAndGetContents() throws IOException {
with(OptionalEmptyTestLanguageStandaloneSetup)
var r = get(TestResource)
r.setURI(URI.createURI('foo.dummy'))
r.load(new StringInputStream(''), null)
assertTrue(r.isLoaded())
val callsBeforeUnload = r.contentsCalls
r.unload()
assertEquals(callsBeforeUnload, r.contentsCalls)
assertFalse(r.isLoaded)
assertNull(r.parseResult)
}
}

View file

@ -1,5 +1,5 @@
/**
* Copyright (c) 2012, 2018 itemis AG (http://www.itemis.eu) and others.
* Copyright (c) 2012, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
@ -12,9 +12,8 @@ import java.io.IOException;
import java.util.Map;
import org.eclipse.emf.ecore.resource.impl.ResourceImpl;
@SuppressWarnings("all")
public class NullResource extends ResourceImpl {
@Override
public void load(final Map<?, ?> options) throws IOException {
public void load(Map<?, ?> options) throws IOException {
}
}

View file

@ -0,0 +1,22 @@
/**
* Copyright (c) 2012, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.resource;
import java.util.HashMap;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
public class ResourceSetTest extends AbstractResourceSetTest {
@Override
protected ResourceSetImpl createEmptyResourceSet() {
ResourceSetImpl rs = new ResourceSetImpl();
rs.setURIResourceMap(new HashMap<>());
return rs;
}
}

View file

@ -0,0 +1,82 @@
/**
* Copyright (c) 2016, 2020 TypeFox GmbH (http://www.typefox.io/) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.resource;
import java.util.Collections;
import org.eclipse.emf.common.util.URI;
import org.eclipse.xtext.ParserRule;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import org.eclipse.xtext.testlanguages.ActionTestLanguage3StandaloneSetup;
import org.eclipse.xtext.testlanguages.ReferenceGrammarTestLanguageStandaloneSetup;
import org.eclipse.xtext.testlanguages.services.ActionTestLanguage3GrammarAccess;
import org.eclipse.xtext.testlanguages.services.ReferenceGrammarTestLanguageGrammarAccess;
import org.eclipse.xtext.tests.AbstractXtextTests;
import org.eclipse.xtext.util.StringInputStream;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Moritz Eysholdt - Initial contribution and API
*/
public class SetEntryPointOnXtextResourceTest extends AbstractXtextTests {
@Test
public void test1() throws Exception {
with(ReferenceGrammarTestLanguageStandaloneSetup.class);
String model = "kind (Hugo 13)";
ParserRule kindRule = get(ReferenceGrammarTestLanguageGrammarAccess.class).getKindRule();
XtextResource resource = createResource();
// test 1: parse and assume there are no errors
resource.setEntryPoint(kindRule);
resource.load(new StringInputStream(model), Collections.emptyMap());
Assert.assertTrue(resource.getErrors().isEmpty());
Assert.assertEquals(kindRule, NodeModelUtils.getEntryParserRule(resource.getParseResult().getRootNode()));
// test 2: update and assume node model does not change
String originalNodeModel = NodeModelUtils.compactDump(resource.getParseResult().getRootNode(), false);
resource.update(0, model.length(), " " + model + " ");
String reparsedNodeModel = NodeModelUtils.compactDump(resource.getParseResult().getRootNode(), false);
Assert.assertEquals(originalNodeModel, reparsedNodeModel);
// test 3: change parser rule
ParserRule erwachsenerRule = get(ReferenceGrammarTestLanguageGrammarAccess.class).getErwachsenerRule();
resource.setEntryPoint(erwachsenerRule);
resource.update(0, model.length(), "erwachsener (Peter 30)");
Assert.assertEquals(erwachsenerRule,
NodeModelUtils.getEntryParserRule(resource.getParseResult().getRootNode()));
}
@Test
public void test2() throws Exception {
with(ActionTestLanguage3StandaloneSetup.class);
ParserRule rule = get(ActionTestLanguage3GrammarAccess.class).getProductionRule1Rule();
String model = "X \"Y\" 42";
XtextResource resource = createResource();
resource.setEntryPoint(rule);
resource.load(new StringInputStream(model), Collections.emptyMap());
Assert.assertTrue(resource.getErrors().isEmpty());
ParserRule entryRule = NodeModelUtils.getEntryParserRule(resource.getParseResult().getRootNode());
Assert.assertEquals(rule, entryRule);
}
@Test
public void test3() throws Exception {
with(ActionTestLanguage3StandaloneSetup.class);
ParserRule rule = get(ActionTestLanguage3GrammarAccess.class).getProductionRule2Rule();
String model = "\"Y\" X42";
XtextResource resource = createResource();
resource.setEntryPoint(rule);
resource.load(new StringInputStream(model), Collections.emptyMap());
Assert.assertTrue(resource.getErrors().isEmpty());
ParserRule entryRule = NodeModelUtils.getEntryParserRule(resource.getParseResult().getRootNode());
Assert.assertEquals(rule, entryRule);
}
private XtextResource createResource() {
return (XtextResource) get(IResourceFactory.class).createResource(URI.createURI("dummy." + getCurrentFileExtension()));
}
}

View file

@ -1,79 +0,0 @@
/**
* Copyright (c) 2016, 2020 TypeFox GmbH (http://www.typefox.io/) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.resource
import org.eclipse.emf.common.util.URI
import org.eclipse.xtext.nodemodel.util.NodeModelUtils
import org.eclipse.xtext.testlanguages.ActionTestLanguage3StandaloneSetup
import org.eclipse.xtext.testlanguages.ReferenceGrammarTestLanguageStandaloneSetup
import org.eclipse.xtext.testlanguages.services.ReferenceGrammarTestLanguageGrammarAccess
import org.eclipse.xtext.tests.AbstractXtextTests
import org.eclipse.xtext.util.StringInputStream
import org.junit.Test
import org.eclipse.xtext.testlanguages.services.ActionTestLanguage3GrammarAccess
/**
* @author Moritz Eysholdt - Initial contribution and API
*/
class SetEntryPointOnXtextResourceTest extends AbstractXtextTests {
@Test def void test1() {
with(ReferenceGrammarTestLanguageStandaloneSetup)
val model = "kind (Hugo 13)"
val kindRule = get(ReferenceGrammarTestLanguageGrammarAccess).kindRule
val resource = createResource()
// test 1: parse and assume there are no errors
resource.entryPoint = kindRule
resource.load(new StringInputStream(model), emptyMap)
assertTrue(resource.errors.isEmpty)
assertEquals(kindRule, NodeModelUtils.getEntryParserRule(resource.parseResult.rootNode))
// test 2: update and assume node model does not change
val originalNodeModel = NodeModelUtils.compactDump(resource.parseResult.rootNode, false)
resource.update(0, model.length, " " + model + " ")
val reparsedNodeModel = NodeModelUtils.compactDump(resource.parseResult.rootNode, false)
assertEquals(originalNodeModel, reparsedNodeModel)
// test 3: change parser rule
val erwachsenerRule = get(ReferenceGrammarTestLanguageGrammarAccess).erwachsenerRule
resource.entryPoint = erwachsenerRule
resource.update(0, model.length, "erwachsener (Peter 30)")
assertEquals(erwachsenerRule, NodeModelUtils.getEntryParserRule(resource.parseResult.rootNode))
}
@Test def void test2() {
with(ActionTestLanguage3StandaloneSetup)
val rule = get(ActionTestLanguage3GrammarAccess).productionRule1Rule
val model = "X \"Y\" 42"
val resource = createResource()
resource.entryPoint = rule
resource.load(new StringInputStream(model), emptyMap)
assertTrue(resource.errors.isEmpty)
val entryRule = NodeModelUtils.getEntryParserRule(resource.parseResult.rootNode)
assertEquals(rule, entryRule)
}
@Test def void test3() {
with(ActionTestLanguage3StandaloneSetup)
val rule = get(ActionTestLanguage3GrammarAccess).productionRule2Rule
val model = "\"Y\" X42"
val resource = createResource()
resource.entryPoint = rule
resource.load(new StringInputStream(model), emptyMap)
assertTrue(resource.errors.isEmpty)
val entryRule = NodeModelUtils.getEntryParserRule(resource.parseResult.rootNode)
assertEquals(rule, entryRule)
}
def private createResource() {
get(IResourceFactory).createResource(URI.createURI("dummy." + currentFileExtension)) as XtextResource
}
}

View file

@ -1,5 +1,5 @@
/**
* Copyright (c) 2012, 2018 itemis AG (http://www.itemis.eu) and others.
* Copyright (c) 2012, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
@ -8,10 +8,6 @@
*/
package org.eclipse.xtext.resource;
import org.eclipse.xtext.resource.AbstractXtextResourceSetTest;
import org.eclipse.xtext.resource.XtextResourceSet;
@SuppressWarnings("all")
public class XtextResourceSetTest extends AbstractXtextResourceSetTest {
@Override
protected XtextResourceSet createEmptyResourceSet() {

View file

@ -1,5 +1,5 @@
/*******************************************************************************
* Copyright (c) 2012, 2018 itemis AG (http://www.itemis.eu) and others.
* Copyright (c) 2012, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
@ -9,72 +9,11 @@
package org.eclipse.xtext.resource
import java.io.File
import java.io.IOException
import java.util.Map
import org.eclipse.emf.common.util.URI
import org.eclipse.emf.ecore.resource.Resource
import org.eclipse.emf.ecore.resource.impl.ResourceImpl
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl
import org.junit.Test
import static org.junit.Assert.*
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl.ResourceLocator
/**
* @author Sven Efftinge - Initial contribution and API
*/
abstract class AbstractResourceSetTest {
def protected ResourceSetImpl createEmptyResourceSet()
@Test
def void testDemandLoadedResourcesAreInMap() {
val rs = createEmptyResourceSet
val Resource.Factory nullFactory = [ uri |
val result = new NullResource
result.URI = uri
result
]
rs.resourceFactoryRegistry.extensionToFactoryMap.put('xmi', nullFactory)
assertEquals(0, rs.URIResourceMap.size)
val uri = URI.createURI('file:/does/not/exist.xmi')
val demandLoaded = rs.getResource(uri, true)
assertNotNull(demandLoaded)
val second = rs.getResource(uri, true)
assertSame(demandLoaded, second)
assertEquals(1, rs.URIResourceMap.size)
}
@Test
def void testResourceLocatorIsUsed() {
val rs = createEmptyResourceSet
val resource = new XtextResource
resource.URI = URI.createFileURI(new File('foo').absolutePath)
// resource locators register themselves on the resource set as a side effect in their constructor
new ResourceLocator(rs) {
override getResource(URI uri, boolean loadOnDemand) {
if (uri == resource.URI) {
return resource;
}
throw new IllegalArgumentException(uri.toString)
}
}
assertSame(resource, rs.getResource(resource.URI, true))
assertTrue(rs.resources.isEmpty)
assertNull(resource.resourceSet)
try {
rs.getResource(resource.URI.appendSegment("doesNotExist"), true)
fail()
} catch(IllegalArgumentException e) {
assertTrue(e.message.endsWith("doesNotExist"))
}
}
}
abstract class AbstractXtextResourceSetTest extends AbstractResourceSetTest {
@ -320,30 +259,6 @@ abstract class AbstractXtextResourceSetTest extends AbstractResourceSetTest {
}
}
class NullResource extends ResourceImpl {
override load(Map<? extends Object,? extends Object> options) throws IOException {
// don't try to load me
}
}
class ResourceSetTest extends AbstractResourceSetTest {
override protected createEmptyResourceSet() {
return new ResourceSetImpl => [ URIResourceMap = newHashMap ]
}
}
class XtextResourceSetTest extends AbstractXtextResourceSetTest {
override protected createEmptyResourceSet() {
new XtextResourceSet
}
}
class SynchronizedXtextResourceSetTest extends AbstractXtextResourceSetTest {
override protected createEmptyResourceSet() {

View file

@ -0,0 +1,139 @@
/**
* Copyright (c) 2014, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.resource.persistence;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.xtext.naming.QualifiedName;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.collect.Lists;
/**
* @author Sven Efftinge - Initial contribution and API
*/
public class SerializableResourceDescriptionTest {
@Test
public void testSerialization() throws Exception {
URI uri = URI.createURI("file:/foo/bar.baz.foo");
SerializableResourceDescription before = new SerializableResourceDescription();
before.setURI(uri);
SerializableReferenceDescription rd1 = new SerializableReferenceDescription();
rd1.setSourceEObjectUri(uri.appendFragment("foo"));
rd1.setTargetEObjectUri(uri.appendFragment("hubble"));
rd1.setContainerEObjectURI(uri.appendFragment("baz"));
rd1.setEReference(EcorePackage.eINSTANCE.getEAnnotation_Contents());
rd1.setIndexInList(1);
SerializableReferenceDescription rd2 = new SerializableReferenceDescription();
rd2.setSourceEObjectUri(uri.appendFragment("foo2"));
rd2.setTargetEObjectUri(uri.appendFragment("hubble2"));
rd2.setContainerEObjectURI(uri.appendFragment("baz2"));
rd2.setEReference(EcorePackage.eINSTANCE.getEAnnotation_Contents());
rd2.setIndexInList(2);
before.setReferences(Lists.newArrayList(rd1, rd2));
SerializableEObjectDescription od1 = new SerializableEObjectDescription();
od1.setEObjectURI(uri.appendFragment("baz"));
od1.qualifiedName = QualifiedName.create("foo", "baz");
od1.setEClass(EcorePackage.eINSTANCE.getEAttribute());
od1.userData = new HashMap<>();
od1.userData.put("myKey", "myValue");
before.setDescriptions(Lists.newArrayList(od1));
before.setImportedNames(Lists.newArrayList(QualifiedName.create("foo"), QualifiedName.create("foo", "bar")));
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream objectOut = new ObjectOutputStream(bout);
objectOut.writeObject(before);
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray()));
SerializableResourceDescription after = (SerializableResourceDescription) in.readObject();
assertDescriptionsEqual(before, after);
}
public void assertDescriptionsEqual(SerializableResourceDescription before, SerializableResourceDescription after) {
Assert.assertEquals(before.getURI(), after.getURI());
Assert.assertEquals(before.getImportedNames(), after.getImportedNames());
Assert.assertEquals(before.getReferences().size(), after.getReferences().size());
for (int i = 0; i < before.getReferences().size(); i++) {
SerializableReferenceDescription beforeRef = before.getReferences().get(i);
SerializableReferenceDescription afterRef = after.getReferences().get(i);
Assert.assertEquals(beforeRef.getContainerEObjectURI(), afterRef.getContainerEObjectURI());
Assert.assertEquals(beforeRef.getSourceEObjectUri(), afterRef.getSourceEObjectUri());
Assert.assertEquals(beforeRef.getTargetEObjectUri(), afterRef.getTargetEObjectUri());
Assert.assertEquals(beforeRef.getEReference(), afterRef.getEReference());
Assert.assertEquals(beforeRef.getIndexInList(), afterRef.getIndexInList());
}
Assert.assertEquals(before.getDescriptions().size(), after.getDescriptions().size());
for (int i_1 = 0; i_1 < before.getDescriptions().size(); i_1++) {
SerializableEObjectDescription beforeDesc = before.getDescriptions().get(i_1);
SerializableEObjectDescription afterDesc = after.getDescriptions().get(i_1);
Assert.assertEquals(beforeDesc.getEClass(), afterDesc.getEClass());
Assert.assertEquals(beforeDesc.getName(), afterDesc.getName());
Assert.assertEquals(beforeDesc.qualifiedName, afterDesc.qualifiedName);
Assert.assertEquals(beforeDesc.userData, afterDesc.userData);
Assert.assertEquals(beforeDesc.getEObjectURI(), afterDesc.getEObjectURI());
}
}
@Test
public void testNullSafeSerialization() throws Exception {
URI uri = URI.createURI("file:/foo/bar.baz.foo");
SerializableResourceDescription before = new SerializableResourceDescription();
before.setURI(uri);
SerializableReferenceDescription rd1 = new SerializableReferenceDescription();
rd1.setSourceEObjectUri(uri.appendFragment("foo"));
rd1.setTargetEObjectUri(null);
rd1.setContainerEObjectURI(uri.appendFragment("baz"));
rd1.setEReference(EcorePackage.eINSTANCE.getEAnnotation_Contents());
rd1.setIndexInList(1);
SerializableReferenceDescription rd2 = new SerializableReferenceDescription();
rd2.setSourceEObjectUri(null);
rd2.setTargetEObjectUri(uri.appendFragment("hubble2"));
rd2.setContainerEObjectURI(uri.appendFragment("baz2"));
rd2.setEReference(EcorePackage.eINSTANCE.getEAnnotation_Contents());
rd2.setIndexInList(2);
SerializableReferenceDescription rd3 = new SerializableReferenceDescription();
rd3.setSourceEObjectUri(uri.appendFragment("foo"));
rd3.setTargetEObjectUri(uri.appendFragment("hubble2"));
rd3.setContainerEObjectURI(null);
rd3.setEReference(EcorePackage.eINSTANCE.getEAnnotation_Contents());
rd3.setIndexInList(2);
SerializableReferenceDescription rd4 = new SerializableReferenceDescription();
rd4.setSourceEObjectUri(uri.appendFragment("foo"));
rd4.setTargetEObjectUri(null);
rd4.setContainerEObjectURI(null);
rd4.setEReference(EcorePackage.eINSTANCE.getEAnnotation_Contents());
rd4.setIndexInList(2);
SerializableReferenceDescription rd5 = new SerializableReferenceDescription();
rd5.setSourceEObjectUri(null);
rd5.setTargetEObjectUri(null);
rd5.setContainerEObjectURI(null);
rd5.setEReference(EcorePackage.eINSTANCE.getEAnnotation_Contents());
rd5.setIndexInList(2);
before.setReferences(Lists.newArrayList(rd1, rd2, rd3, rd4, rd5));
SerializableEObjectDescription od1 = new SerializableEObjectDescription();
od1.setEObjectURI(uri.appendFragment("baz"));
od1.qualifiedName = QualifiedName.create("foo", "baz");
od1.setEClass(EcorePackage.eINSTANCE.getEAttribute());
od1.userData = new HashMap<>();
od1.userData.put("myKey", "myValue");
before.setDescriptions(Lists.newArrayList(od1));
before.setImportedNames(Lists.newArrayList(QualifiedName.create("foo"), QualifiedName.create("foo", "bar")));
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream objectOut = new ObjectOutputStream(bout);
objectOut.writeObject(before);
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray()));
SerializableResourceDescription after = (SerializableResourceDescription) in.readObject();
assertDescriptionsEqual(before, after);
}
}

View file

@ -1,152 +0,0 @@
/*******************************************************************************
* Copyright (c) 2014 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.xtext.resource.persistence
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import org.eclipse.emf.common.util.URI
import org.eclipse.emf.ecore.EcorePackage
import org.eclipse.xtext.naming.QualifiedName
import org.junit.Test
import static org.junit.Assert.*
/**
* @author Sven Efftinge - Initial contribution and API
*/
class SerializableResourceDescriptionTest {
@Test def void testSerialization() {
val uri = URI::createURI("file:/foo/bar.baz.foo")
val before = new SerializableResourceDescription => [
URI = uri
references = #[
new SerializableReferenceDescription => [
sourceEObjectUri = uri.appendFragment('foo')
targetEObjectUri = uri.appendFragment('hubble')
containerEObjectURI = uri.appendFragment('baz')
EReference = EcorePackage.eINSTANCE.EAnnotation_Contents
indexInList = 1
],
new SerializableReferenceDescription => [
sourceEObjectUri = uri.appendFragment('foo2')
targetEObjectUri = uri.appendFragment('hubble2')
containerEObjectURI = uri.appendFragment('baz2')
EReference = EcorePackage.eINSTANCE.EAnnotation_Contents
indexInList = 2
]
]
descriptions = #[
new SerializableEObjectDescription => [
EObjectURI = uri.appendFragment('baz')
qualifiedName = QualifiedName.create('foo','baz')
EClass = EcorePackage.eINSTANCE.EAttribute
userData = newHashMap('myKey' -> 'myValue')
]
]
importedNames = #[QualifiedName.create('foo'), QualifiedName.create('foo','bar')]
]
val bout = new ByteArrayOutputStream()
val objectOut = new ObjectOutputStream(bout)
objectOut.writeObject(before)
val in = new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray))
val after = in.readObject as SerializableResourceDescription
assertDescriptionsEqual(before, after)
}
def void assertDescriptionsEqual(SerializableResourceDescription before, SerializableResourceDescription after) {
assertEquals(before.URI, after.URI)
assertEquals(before.importedNames, after.importedNames)
assertEquals(before.references.size, after.references.size)
for (int i : 0..<before.references.size) {
val beforeRef = before.references.get(i)
val afterRef = after.references.get(i)
assertEquals(beforeRef.containerEObjectURI, afterRef.containerEObjectURI)
assertEquals(beforeRef.sourceEObjectUri, afterRef.sourceEObjectUri)
assertEquals(beforeRef.targetEObjectUri, afterRef.targetEObjectUri)
assertEquals(beforeRef.EReference, afterRef.EReference)
assertEquals(beforeRef.indexInList, afterRef.indexInList)
}
assertEquals(before.descriptions.size, after.descriptions.size)
for (int i : 0..<before.descriptions.size) {
val beforeDesc = before.descriptions.get(i)
val afterDesc = after.descriptions.get(i)
assertEquals(beforeDesc.EClass, afterDesc.EClass)
assertEquals(beforeDesc.name, afterDesc.name)
assertEquals(beforeDesc.qualifiedName, afterDesc.qualifiedName)
assertEquals(beforeDesc.userData, afterDesc.userData)
assertEquals(beforeDesc.EObjectURI, afterDesc.EObjectURI)
}
}
@Test def void testNullSafeSerialization() {
val uri = URI::createURI("file:/foo/bar.baz.foo")
val before = new SerializableResourceDescription => [
URI = uri
references = #[
new SerializableReferenceDescription => [
sourceEObjectUri = uri.appendFragment('foo')
targetEObjectUri = null
containerEObjectURI = uri.appendFragment('baz')
EReference = EcorePackage.eINSTANCE.EAnnotation_Contents
indexInList = 1
],
new SerializableReferenceDescription => [
sourceEObjectUri = null
targetEObjectUri = uri.appendFragment('hubble2')
containerEObjectURI = uri.appendFragment('baz2')
EReference = EcorePackage.eINSTANCE.EAnnotation_Contents
indexInList = 2
],
new SerializableReferenceDescription => [
sourceEObjectUri = uri.appendFragment('foo')
targetEObjectUri = uri.appendFragment('hubble2')
containerEObjectURI = null
EReference = EcorePackage.eINSTANCE.EAnnotation_Contents
indexInList = 2
],
new SerializableReferenceDescription => [
sourceEObjectUri = uri.appendFragment('foo')
targetEObjectUri = null
containerEObjectURI = null
EReference = EcorePackage.eINSTANCE.EAnnotation_Contents
indexInList = 2
],
new SerializableReferenceDescription => [
sourceEObjectUri = null
targetEObjectUri = null
containerEObjectURI = null
EReference = EcorePackage.eINSTANCE.EAnnotation_Contents
indexInList = 2
]
]
descriptions = #[
new SerializableEObjectDescription => [
EObjectURI = uri.appendFragment('baz')
qualifiedName = QualifiedName.create('foo','baz')
EClass = EcorePackage.eINSTANCE.EAttribute
userData = newHashMap('myKey' -> 'myValue')
]
]
importedNames = #[QualifiedName.create('foo'), QualifiedName.create('foo','bar')]
]
val bout = new ByteArrayOutputStream()
val objectOut = new ObjectOutputStream(bout)
objectOut.writeObject(before)
val in = new ObjectInputStream(new ByteArrayInputStream(bout.toByteArray))
val after = in.readObject as SerializableResourceDescription
assertDescriptionsEqual(before, after)
}
}

View file

@ -0,0 +1,79 @@
/**
* Copyright (c) 2017, 2020 TypeFox GmbH (http://www.typefox.io) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.serializer;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.resource.DefaultFragmentProvider;
import org.eclipse.xtext.resource.FileExtensionProvider;
import org.eclipse.xtext.resource.IFragmentProvider;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.resource.XtextResourceSet;
import org.eclipse.xtext.serializer.syntacticsequencertest.Model;
import org.eclipse.xtext.serializer.syntacticsequencertest.SingleCrossReference;
import org.eclipse.xtext.serializer.syntacticsequencertest.SyntacticsequencertestFactory;
import org.eclipse.xtext.testing.InjectWith;
import org.eclipse.xtext.testing.XtextRunner;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.google.inject.Inject;
import com.google.inject.Provider;
@RunWith(XtextRunner.class)
@InjectWith(SyntacticSequencerTestLanguageInjectorProvider.class)
public class TokenSerializerTest {
@Inject
private ISerializer serializer;
@Inject
private FileExtensionProvider fileExtensionProvider;
@Inject
private Provider<XtextResourceSet> resourceSetProvider;
private SyntacticsequencertestFactory factory = SyntacticsequencertestFactory.eINSTANCE;
private void assertSerializesTo(Model model, CharSequence expectation) {
Assert.assertEquals(expectation.toString().trim(), serializer.serialize(model).trim());
}
private URI getFileURI(String name) {
return URI.createFileURI(name + "." + fileExtensionProvider.getPrimaryFileExtension());
}
@Test
public void testConstructedCrossReferenceWithProxy() {
XtextResourceSet resourceSet = resourceSetProvider.get();
XtextResource resource = (XtextResource) resourceSet.createResource(getFileURI("dummy"));
Model model = factory.createModel();
SingleCrossReference myRef = factory.createSingleCrossReference();
myRef.setName("myref");
model.setX5(myRef);
resource.getContents().add(model);
SingleCrossReference singleRef = model.getX5();
SingleCrossReference fooProxyRef = factory.createSingleCrossReference();
((InternalEObject) fooProxyRef).eSetProxyURI(resource.getURI().appendFragment("foo"));
singleRef.setRef3(fooProxyRef);
resource.setFragmentProvider(new DefaultFragmentProvider() {
@Override
public EObject getEObject(Resource resource, String fragment, IFragmentProvider.Fallback fallback) {
if ("foo".equals(fragment)) {
return model.getX5();
} else {
return super.getEObject(resource, fragment, fallback);
}
}
});
assertSerializesTo(model, "#5 myref kw3 myref");
}
}

View file

@ -1,75 +0,0 @@
/*******************************************************************************
* Copyright (c) 2017 TypeFox GmbH (http://www.typefox.io) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.xtext.serializer
import com.google.inject.Inject
import com.google.inject.Provider
import org.eclipse.emf.common.util.URI
import org.eclipse.emf.ecore.InternalEObject
import org.eclipse.emf.ecore.resource.Resource
import org.eclipse.xtext.resource.DefaultFragmentProvider
import org.eclipse.xtext.resource.FileExtensionProvider
import org.eclipse.xtext.resource.XtextResource
import org.eclipse.xtext.resource.XtextResourceSet
import org.eclipse.xtext.serializer.syntacticsequencertest.Model
import org.eclipse.xtext.serializer.syntacticsequencertest.SyntacticsequencertestFactory
import org.eclipse.xtext.testing.InjectWith
import org.eclipse.xtext.testing.XtextRunner
import org.junit.Test
import org.junit.runner.RunWith
import static org.junit.Assert.*
@RunWith(XtextRunner)
@InjectWith(SyntacticSequencerTestLanguageInjectorProvider)
class TokenSerializerTest {
@Inject extension ISerializer
@Inject FileExtensionProvider fileExtensionProvider
@Inject Provider<XtextResourceSet> resourceSetProvider
val factory = SyntacticsequencertestFactory.eINSTANCE
private def assertSerializesTo(Model model, CharSequence expectation) {
assertEquals(expectation.toString.trim, model.serialize.trim)
}
private def getFileURI(String name) {
URI.createFileURI(name + '.' + fileExtensionProvider.primaryFileExtension)
}
@Test
def void testConstructedCrossReferenceWithProxy() {
val resourceSet = resourceSetProvider.get
val resource = resourceSet.createResource('dummy'.fileURI) as XtextResource
val model = factory.createModel => [
x5 = factory.createSingleCrossReference => [
name = 'myref'
]
]
resource.contents += model
model.x5.ref3 = factory.createSingleCrossReference => [
(it as InternalEObject).eSetProxyURI(resource.URI.appendFragment('foo'))
]
resource.fragmentProvider = new DefaultFragmentProvider {
override getEObject(Resource resource, String fragment, Fallback fallback) {
if (fragment == 'foo')
model.x5
else
super.getEObject(resource, fragment, fallback)
}
}
model.assertSerializesTo('''
#5 myref kw3 myref
''')
}
}

View file

@ -0,0 +1,55 @@
/**
* Copyright (c) 2014, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.tasks;
import java.util.List;
import org.eclipse.xtext.preferences.IPreferenceValuesProvider;
import org.eclipse.xtext.preferences.MapBasedPreferenceValues;
import org.eclipse.xtext.xbase.lib.IterableExtensions;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
/**
* @author Stefan Oehme - Initial contribution and API
*/
public class PreferenceTaskTagProviderTest {
@Test
public void test() {
TaskTag taskTag1 = new TaskTag();
taskTag1.setName("Foo");
taskTag1.setPriority(Priority.LOW);
TaskTag taskTag2 = new TaskTag();
taskTag2.setName("BAR");
taskTag2.setPriority(Priority.NORMAL);
TaskTag taskTag3 = new TaskTag();
taskTag3.setName("baZ");
taskTag3.setPriority(Priority.HIGH);
List<TaskTag> tags = Lists.newArrayList(taskTag1, taskTag2, taskTag3);
String names = PreferenceTaskTagProvider.serializeTags(tags);
String prios = PreferenceTaskTagProvider.serializePriorities(tags);
IPreferenceValuesProvider.SingletonPreferenceValuesProvider valueProvider = new IPreferenceValuesProvider.SingletonPreferenceValuesProvider();
MapBasedPreferenceValues values = valueProvider.getPreferenceValues(null);
values.put(PreferenceTaskTagProvider.TAGS_KEY.getId(), names);
values.put(PreferenceTaskTagProvider.PRIORITIES_KEY.getId(), prios);
values.put(PreferenceTaskTagProvider.CASE_SENSITIVE_KEY.getId(), "false");
PreferenceTaskTagProvider tagProvider = new PreferenceTaskTagProvider();
tagProvider.setPreferenceValuesProvider(valueProvider);
TaskTags parsedTags = tagProvider.getTaskTags(null);
Assert.assertEquals(Boolean.valueOf(false), Boolean.valueOf(parsedTags.isCaseSensitive()));
Assert.assertEquals(tags.size(), IterableExtensions.size(parsedTags));
int _size = tags.size();
for (int i = 0; i < _size; i++) {
Assert.assertEquals(tags.get(i), Iterables.get(parsedTags, i));
}
}
}

View file

@ -1,57 +0,0 @@
/*******************************************************************************
* Copyright (c) 2014 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.xtext.tasks
import org.eclipse.xtext.preferences.IPreferenceValuesProvider.SingletonPreferenceValuesProvider
import org.junit.Test
import static org.junit.Assert.*
/**
* @author Stefan Oehme - Initial contribution and API
*/
class PreferenceTaskTagProviderTest {
@Test
def void test() {
val tags = #[
new TaskTag => [
name = "Foo"
priority = Priority.LOW
],
new TaskTag => [
name = "BAR"
priority = Priority.NORMAL
],
new TaskTag => [
name = "baZ"
priority = Priority.HIGH
]
]
val names = PreferenceTaskTagProvider.serializeTags(tags)
val prios = PreferenceTaskTagProvider.serializePriorities(tags)
val valueProvider = new SingletonPreferenceValuesProvider
val values = valueProvider.getPreferenceValues(null)
values.put(PreferenceTaskTagProvider.TAGS_KEY.id, names)
values.put(PreferenceTaskTagProvider.PRIORITIES_KEY.id, prios)
values.put(PreferenceTaskTagProvider.CASE_SENSITIVE_KEY.id, "false")
val tagProvider = new PreferenceTaskTagProvider
tagProvider.preferenceValuesProvider = valueProvider
val parsedTags = tagProvider.getTaskTags(null)
assertEquals(false, parsedTags.caseSensitive)
assertEquals(tags.size, parsedTags.size)
for (i : 0 ..< tags.size) {
assertEquals(tags.get(i), parsedTags.get(i))
}
}
}

View file

@ -0,0 +1,169 @@
/**
* Copyright (c) 2019, 2020 Malardalen University (http://www.mdh.se) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.xtext;
import org.eclipse.xtext.Grammar;
import org.eclipse.xtext.XtextPackage;
import org.eclipse.xtext.XtextRuntimeModule;
import org.eclipse.xtext.XtextStandaloneSetup;
import org.eclipse.xtext.diagnostics.Severity;
import org.eclipse.xtext.preferences.IPreferenceValuesProvider;
import org.eclipse.xtext.preferences.MapBasedPreferenceValues;
import org.eclipse.xtext.testing.InjectWith;
import org.eclipse.xtext.testing.XtextRunner;
import org.eclipse.xtext.testing.util.ParseHelper;
import org.eclipse.xtext.testing.validation.ValidationTestHelper;
import org.eclipse.xtext.tests.AbstractXtextTests;
import org.eclipse.xtext.tests.XtextInjectorProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
/**
* @author Lorenzo Addazi - Initial contribution and API
*/
@RunWith(XtextRunner.class)
@InjectWith(XtextInjectorProvider.class)
public class Issue1161Test extends AbstractXtextTests {
/**
* @author Lorenzo Addazi - Initial contribution and API
*/
public static class Issue1161StandaloneSetup extends XtextStandaloneSetup {
@Override
public Injector createInjector() {
XtextRuntimeModule module = new XtextRuntimeModule() {
@SuppressWarnings("unused")
public Class<? extends IPreferenceValuesProvider> bindIPreferenceValuesProvider() {
return IPreferenceValuesProvider.SingletonPreferenceValuesProvider.class;
}
};
return Guice.createInjector(module);
}
}
@Inject
private ValidationTestHelper validationTestHelper;
@Inject
private ParseHelper<Grammar> parseHelper;
@Inject
private MapBasedPreferenceValues preferences;
@Override
public void setUp() throws Exception {
super.setUp();
with(Issue1161Test.Issue1161StandaloneSetup.class);
}
@Before
public void setPreferences() {
preferences = get(IPreferenceValuesProvider.SingletonPreferenceValuesProvider.class).getPreferenceValues(null);
}
@After
public void clearPreferences() {
preferences.clear();
}
@Test
public void testValidJavaPackageNamingConventionsWithIgnoreSeverity() throws Exception {
assertNoIssue(grammarWithValidJavaPackageNamingConventions());
}
@Test
public void testInvalidJavaPackageNamingConventionsWithIgnoreSeverity() throws Exception {
assertNoIssue(grammarWithInvalidJavaPackageNamingConventions());
}
@Test
public void testValidJavaPackageNamingConventionsWithErrorSeverity() throws Exception {
setSeverity("error");
assertNoIssue(grammarWithValidJavaPackageNamingConventions());
}
@Test
public void testInvalidJavaPackageNamingConventionsWithErrorSeverity() throws Exception {
setSeverity("error");
assertError(grammarWithInvalidJavaPackageNamingConventions());
}
@Test
public void testValidJavaPackageNamingConventionsWithWarningSeverity() throws Exception {
setSeverity("warning");
assertNoIssue(grammarWithValidJavaPackageNamingConventions());
}
@Test
public void testInvalidJavaPackageNamingConventionsWithWarningSeverity() throws Exception {
setSeverity("warning");
assertWarning(grammarWithInvalidJavaPackageNamingConventions());
}
@Test
public void testValidJavaPackageNamingConventionsWithInfoSeverity() throws Exception {
setSeverity("info");
assertNoIssue(grammarWithValidJavaPackageNamingConventions());
}
@Test
public void testInvalidJavaPackageNamingConventionsWithInfoSeverity() throws Exception {
setSeverity("info");
assertInfo(grammarWithInvalidJavaPackageNamingConventions());
}
private void assertError(final CharSequence grammar) throws Exception {
assertIssue(grammar, Severity.ERROR);
}
private void assertWarning(final CharSequence grammar) throws Exception {
assertIssue(grammar, Severity.WARNING);
}
private void assertInfo(final CharSequence grammar) throws Exception {
assertIssue(grammar, Severity.INFO);
}
private void assertIssue(final CharSequence grammar, final Severity severity) throws Exception {
validationTestHelper.assertIssue(parseHelper.parse(grammar), XtextPackage.Literals.GENERATED_METAMODEL,
XtextConfigurableIssueCodes.INVALID_JAVAPACKAGE_NAME, severity);
}
private void assertNoIssue(final CharSequence grammar) throws Exception {
validationTestHelper.assertNoIssue(parseHelper.parse(grammar), XtextPackage.Literals.GENERATED_METAMODEL,
XtextConfigurableIssueCodes.INVALID_JAVAPACKAGE_NAME);
}
private CharSequence grammarWithValidJavaPackageNamingConventions() {
return grammarWithGeneratedMetamodelName("testissue1161");
}
private CharSequence grammarWithInvalidJavaPackageNamingConventions() {
return grammarWithGeneratedMetamodelName("testIssue1161");
}
private CharSequence grammarWithGeneratedMetamodelName(final String generatedMetamodelName) {
// @formatter:off
String model =
"grammar test.Issue1161 with org.eclipse.xtext.common.Terminals\n" +
"generate " + generatedMetamodelName + " 'http://issue1161'n" +
"A : {A};";
// @formatter:on
return model;
}
private void setSeverity(final String severity) {
preferences.put(XtextConfigurableIssueCodes.INVALID_JAVAPACKAGE_NAME, severity);
}
}

View file

@ -1,151 +0,0 @@
/*******************************************************************************
* Copyright (c) 2019 Malardalen University (http://www.mdh.se) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*******************************************************************************/
package org.eclipse.xtext.xtext
import com.google.inject.Guice
import com.google.inject.Inject
import org.eclipse.xtext.Grammar
import org.eclipse.xtext.XtextPackage
import org.eclipse.xtext.XtextRuntimeModule
import org.eclipse.xtext.XtextStandaloneSetup
import org.eclipse.xtext.diagnostics.Severity
import org.eclipse.xtext.preferences.IPreferenceValuesProvider
import org.eclipse.xtext.preferences.IPreferenceValuesProvider.SingletonPreferenceValuesProvider
import org.eclipse.xtext.preferences.MapBasedPreferenceValues
import org.eclipse.xtext.testing.InjectWith
import org.eclipse.xtext.testing.XtextRunner
import org.eclipse.xtext.testing.util.ParseHelper
import org.eclipse.xtext.testing.validation.ValidationTestHelper
import org.eclipse.xtext.tests.AbstractXtextTests
import org.eclipse.xtext.tests.XtextInjectorProvider
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
/**
* @author Lorenzo Addazi - Initial contribution and API
*/
@RunWith(XtextRunner)
@InjectWith(XtextInjectorProvider)
class Issue1161Test extends AbstractXtextTests {
@Inject extension ValidationTestHelper
@Inject extension ParseHelper<Grammar>
@Inject MapBasedPreferenceValues preferences
override setUp() throws Exception {
super.setUp();
with(Issue1161StandaloneSetup)
}
@Before def void setPreferences() {
preferences = get(SingletonPreferenceValuesProvider).getPreferenceValues(null)
}
@After def void clearPreferences() {
preferences.clear
}
@Test def void testValidJavaPackageNamingConventionsWithIgnoreSeverity() {
grammarWithValidJavaPackageNamingConventions.assertNoIssue
}
@Test def void testInvalidJavaPackageNamingConventionsWithIgnoreSeverity() {
grammarWithInvalidJavaPackageNamingConventions.assertNoIssue
}
@Test def void testValidJavaPackageNamingConventionsWithErrorSeverity() {
severity = "error"
grammarWithValidJavaPackageNamingConventions.assertNoIssue
}
@Test def void testInvalidJavaPackageNamingConventionsWithErrorSeverity() {
severity = "error"
grammarWithInvalidJavaPackageNamingConventions.assertError
}
@Test def void testValidJavaPackageNamingConventionsWithWarningSeverity() {
severity = "warning"
grammarWithValidJavaPackageNamingConventions.assertNoIssue
}
@Test def void testInvalidJavaPackageNamingConventionsWithWarningSeverity() {
severity = "warning"
grammarWithInvalidJavaPackageNamingConventions.assertWarning
}
@Test def void testValidJavaPackageNamingConventionsWithInfoSeverity() {
severity = "info"
grammarWithValidJavaPackageNamingConventions.assertNoIssue
}
@Test def void testInvalidJavaPackageNamingConventionsWithInfoSeverity() {
severity = "info"
grammarWithInvalidJavaPackageNamingConventions.assertInfo
}
private def assertError(CharSequence grammar) {
grammar.assertIssue(Severity.ERROR)
}
private def assertWarning(CharSequence grammar) {
grammar.assertIssue(Severity.WARNING)
}
private def assertInfo(CharSequence grammar) {
grammar.assertIssue(Severity.INFO)
}
private def assertIssue(CharSequence grammar, Severity severity) {
grammar.parse.assertIssue(XtextPackage.Literals.GENERATED_METAMODEL,
XtextConfigurableIssueCodes.INVALID_JAVAPACKAGE_NAME, severity)
}
private def assertNoIssue(CharSequence grammar) {
grammar.parse.assertNoIssue(XtextPackage.Literals.GENERATED_METAMODEL,
XtextConfigurableIssueCodes.INVALID_JAVAPACKAGE_NAME)
}
private def grammarWithValidJavaPackageNamingConventions() {
grammarWithGeneratedMetamodelName("testissue1161")
}
private def grammarWithInvalidJavaPackageNamingConventions() {
grammarWithGeneratedMetamodelName("testIssue1161")
}
private def grammarWithGeneratedMetamodelName(String generatedMetamodelName) '''
grammar test.Issue1161 with org.eclipse.xtext.common.Terminals
generate «generatedMetamodelName» "http://issue1161"
A : {A};
'''
private def setSeverity(String severity) {
preferences.put(XtextConfigurableIssueCodes.INVALID_JAVAPACKAGE_NAME, severity)
}
/**
* @author Lorenzo Addazi - Initial contribution and API
*/
static class Issue1161StandaloneSetup extends XtextStandaloneSetup {
override createInjector() {
return Guice.createInjector(new XtextRuntimeModule() {
def Class<? extends IPreferenceValuesProvider> bindIPreferenceValuesProvider() {
SingletonPreferenceValuesProvider
}
});
}
}
}

View file

@ -1,380 +0,0 @@
/**
* Copyright (c) 2015, 2017 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.formatting2.regionaccess.internal;
import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtend2.lib.StringConcatenation;
import org.eclipse.xtext.formatting2.regionaccess.IEObjectRegion;
import org.eclipse.xtext.formatting2.regionaccess.ISemanticRegion;
import org.eclipse.xtext.formatting2.regionaccess.ISemanticRegionsFinder;
import org.eclipse.xtext.formatting2.regionaccess.ITextRegionAccess;
import org.eclipse.xtext.formatting2.regionaccess.ITextSegment;
import org.eclipse.xtext.formatting2.regionaccess.TextRegionAccessBuilder;
import org.eclipse.xtext.formatting2.regionaccess.internal.regionaccesstestlanguage.AssignedAction;
import org.eclipse.xtext.formatting2.regionaccess.internal.regionaccesstestlanguage.Expression;
import org.eclipse.xtext.formatting2.regionaccess.internal.regionaccesstestlanguage.Mixed;
import org.eclipse.xtext.formatting2.regionaccess.internal.regionaccesstestlanguage.RegionaccesstestlanguagePackage;
import org.eclipse.xtext.formatting2.regionaccess.internal.regionaccesstestlanguage.Root;
import org.eclipse.xtext.formatting2.regionaccess.internal.services.RegionAccessTestLanguageGrammarAccess;
import org.eclipse.xtext.formatting2.regionaccess.internal.tests.RegionAccessTestLanguageInjectorProvider;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.testing.InjectWith;
import org.eclipse.xtext.testing.XtextRunner;
import org.eclipse.xtext.testing.util.ParseHelper;
import org.eclipse.xtext.testing.validation.ValidationTestHelper;
import org.eclipse.xtext.xbase.lib.Exceptions;
import org.eclipse.xtext.xbase.lib.Extension;
import org.eclipse.xtext.xbase.lib.Functions.Function1;
import org.eclipse.xtext.xbase.lib.IterableExtensions;
import org.eclipse.xtext.xbase.lib.Pair;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Moritz Eysholdt - Initial contribution and API
*/
@RunWith(XtextRunner.class)
@InjectWith(RegionAccessTestLanguageInjectorProvider.class)
@SuppressWarnings("all")
public class SemanticRegionFinderTest {
@Inject
@Extension
private ParseHelper<Root> parseHelper;
@Inject
private Provider<TextRegionAccessBuilder> textRegionAccessBuilder;
@Inject
@Extension
private ValidationTestHelper validationTestHelper;
@Inject
@Extension
private RegionAccessTestLanguageGrammarAccess _regionAccessTestLanguageGrammarAccess;
@Test
public void regionForFeatureAttribute() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (foo)");
final Mixed mixed = this.<Mixed>parseAs(_builder, Mixed.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed).getRegionFor();
final ISemanticRegion actual = finder.feature(RegionaccesstestlanguagePackage.Literals.MIXED__NAME);
final List<ISemanticRegion> actuals = finder.features(RegionaccesstestlanguagePackage.Literals.MIXED__NAME);
this.assertEquals("foo", actual, actuals);
}
@Test
public void regionForFeatureCrossReference() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (ref foo) action (foo) end");
final AssignedAction mixed = this.<AssignedAction>parseAs(_builder, AssignedAction.class);
final IEObjectRegion finder = this.toAccess(mixed).regionForEObject(mixed.getChild());
final ISemanticRegion actual = finder.getRegionFor().feature(RegionaccesstestlanguagePackage.Literals.MIXED__REF);
final List<ISemanticRegion> actuals = finder.getRegionFor().features(RegionaccesstestlanguagePackage.Literals.MIXED__REF);
this.assertEquals("foo", actual, actuals);
}
@Test
public void regionForFeatureContainmentReference() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (foo) action");
final AssignedAction mixed = this.<AssignedAction>parseAs(_builder, AssignedAction.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed).getRegionFor();
try {
finder.feature(RegionaccesstestlanguagePackage.Literals.ASSIGNED_ACTION__CHILD);
Assert.fail();
} catch (final Throwable _t) {
if (_t instanceof IllegalStateException) {
} else {
throw Exceptions.sneakyThrow(_t);
}
}
try {
finder.features(RegionaccesstestlanguagePackage.Literals.ASSIGNED_ACTION__CHILD);
Assert.fail();
} catch (final Throwable _t) {
if (_t instanceof IllegalStateException) {
} else {
throw Exceptions.sneakyThrow(_t);
}
}
}
@Test
public void regionForRuleCallUnassignedTerminal() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (unassigned foo)");
final Mixed mixed = this.<Mixed>parseAs(_builder, Mixed.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed).getRegionFor();
final ISemanticRegion actual = finder.ruleCall(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getIDTerminalRuleCall_1_1_0());
final List<ISemanticRegion> actuals = finder.ruleCalls(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getIDTerminalRuleCall_1_1_0());
this.assertEquals("foo", actual, actuals);
}
@Test
public void regionForRuleCallToUnassignedTerminal() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (unassigned foo)");
final Mixed mixed = this.<Mixed>parseAs(_builder, Mixed.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed).getRegionFor();
final ISemanticRegion actual = finder.ruleCallTo(this._regionAccessTestLanguageGrammarAccess.getIDRule());
final List<ISemanticRegion> actuals = finder.ruleCallsTo(this._regionAccessTestLanguageGrammarAccess.getIDRule());
this.assertEquals("foo", actual, actuals);
}
@Test
public void regionForRuleCallUnassignedDataType() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (unassigned datatype foo)");
final Mixed mixed = this.<Mixed>parseAs(_builder, Mixed.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed).getRegionFor();
final ISemanticRegion actual = finder.ruleCall(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getDatatypeParserRuleCall_1_1_1());
final List<ISemanticRegion> actuals = finder.ruleCalls(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getDatatypeParserRuleCall_1_1_1());
this.assertEquals("datatype foo", actual, actuals);
}
@Test
public void regionForRuleCallToUnassignedDataType() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (unassigned datatype foo)");
final Mixed mixed = this.<Mixed>parseAs(_builder, Mixed.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed).getRegionFor();
final ISemanticRegion actual = finder.ruleCallTo(this._regionAccessTestLanguageGrammarAccess.getDatatypeRule());
final List<ISemanticRegion> actuals = finder.ruleCallsTo(this._regionAccessTestLanguageGrammarAccess.getDatatypeRule());
this.assertEquals("datatype foo", actual, actuals);
}
@Test
public void regionForRuleCallAssignedTerminal() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (foo)");
final Mixed mixed = this.<Mixed>parseAs(_builder, Mixed.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed).getRegionFor();
final ISemanticRegion actual = finder.ruleCall(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getNameIDTerminalRuleCall_2_2_0_0());
final ISemanticRegion actuals = finder.ruleCall(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getNameIDTerminalRuleCall_2_2_0_0());
Assert.assertEquals("foo", actual, actuals);
}
@Test
public void regionForRuleCallToAssignedTerminal() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (foo)");
final Mixed mixed = this.<Mixed>parseAs(_builder, Mixed.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed).getRegionFor();
final ISemanticRegion actual = finder.ruleCallTo(this._regionAccessTestLanguageGrammarAccess.getIDRule());
final ISemanticRegion actuals = finder.ruleCallTo(this._regionAccessTestLanguageGrammarAccess.getIDRule());
Assert.assertEquals("foo", actual, actuals);
}
@Test
public void regionForRuleCallAssignedDataType() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (datatype foo)");
final Mixed mixed = this.<Mixed>parseAs(_builder, Mixed.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed).getRegionFor();
final ISemanticRegion actual = finder.ruleCall(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getDatatypeDatatypeParserRuleCall_2_2_2_0());
final ISemanticRegion actuals = finder.ruleCall(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getDatatypeDatatypeParserRuleCall_2_2_2_0());
Assert.assertEquals("datatype foo", actual, actuals);
}
@Test
public void regionForRuleCallToAssignedDataType() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (datatype foo)");
final Mixed mixed = this.<Mixed>parseAs(_builder, Mixed.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed).getRegionFor();
final ISemanticRegion actual = finder.ruleCallTo(this._regionAccessTestLanguageGrammarAccess.getDatatypeRule());
final ISemanticRegion actuals = finder.ruleCallTo(this._regionAccessTestLanguageGrammarAccess.getDatatypeRule());
Assert.assertEquals("datatype foo", actual, actuals);
}
@Test
public void regionForRuleCallCrossReference() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (ref foo) action (foo) end");
final AssignedAction mixed = this.<AssignedAction>parseAs(_builder, AssignedAction.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed.getChild()).getRegionFor();
final ISemanticRegion actual = finder.ruleCall(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getRefMixedIDTerminalRuleCall_2_2_3_1_0_1());
final List<ISemanticRegion> actuals = finder.ruleCalls(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getRefMixedIDTerminalRuleCall_2_2_3_1_0_1());
this.assertEquals("foo", actual, actuals);
}
@Test
public void regionForRuleCallToCrossReference() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (ref foo) action (foo) end");
final AssignedAction mixed = this.<AssignedAction>parseAs(_builder, AssignedAction.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed.getChild()).getRegionFor();
final ISemanticRegion actual = finder.ruleCallTo(this._regionAccessTestLanguageGrammarAccess.getIDRule());
final List<ISemanticRegion> actuals = finder.ruleCallsTo(this._regionAccessTestLanguageGrammarAccess.getIDRule());
this.assertEquals("foo", actual, actuals);
}
@Test
public void regionForRuleCallEObjectParserRule() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (child (foo))");
final Mixed mixed = this.<Mixed>parseAs(_builder, Mixed.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed).getRegionFor();
try {
finder.ruleCall(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getEobjMixedParserRuleCall_2_2_1_1_0());
Assert.fail();
} catch (final Throwable _t) {
if (_t instanceof IllegalStateException) {
} else {
throw Exceptions.sneakyThrow(_t);
}
}
try {
finder.ruleCalls(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getEobjMixedParserRuleCall_2_2_1_1_0());
Assert.fail();
} catch (final Throwable _t) {
if (_t instanceof IllegalStateException) {
} else {
throw Exceptions.sneakyThrow(_t);
}
}
}
@Test
public void regionForRuleCallToEObjectParserRule() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (child (foo))");
final Mixed mixed = this.<Mixed>parseAs(_builder, Mixed.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed).getRegionFor();
try {
finder.ruleCallTo(this._regionAccessTestLanguageGrammarAccess.getMixedRule());
Assert.fail();
} catch (final Throwable _t) {
if (_t instanceof IllegalStateException) {
} else {
throw Exceptions.sneakyThrow(_t);
}
}
try {
finder.ruleCallsTo(this._regionAccessTestLanguageGrammarAccess.getMixedRule());
Assert.fail();
} catch (final Throwable _t) {
if (_t instanceof IllegalStateException) {
} else {
throw Exceptions.sneakyThrow(_t);
}
}
}
@Test
public void regionForKeywordString() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (foo)");
final Mixed mixed = this.<Mixed>parseAs(_builder, Mixed.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed).getRegionFor();
final ISemanticRegion actual = finder.keyword("(");
final List<ISemanticRegion> actuals = finder.keywords("(");
this.assertEquals("(", actual, actuals);
}
@Test
public void regionForKeyword() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (foo)");
final Mixed mixed = this.<Mixed>parseAs(_builder, Mixed.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed).getRegionFor();
final ISemanticRegion actual = finder.keyword(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getLeftParenthesisKeyword_0());
final List<ISemanticRegion> actuals = finder.keywords(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getLeftParenthesisKeyword_0());
this.assertEquals("(", actual, actuals);
}
@Test
public void regionForCrossReference() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (ref foo) action (foo) end");
final AssignedAction mixed = this.<AssignedAction>parseAs(_builder, AssignedAction.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed.getChild()).getRegionFor();
final ISemanticRegion actual = finder.crossRef(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getRefMixedCrossReference_2_2_3_1_0());
final List<ISemanticRegion> actuals = finder.crossRefs(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getRefMixedCrossReference_2_2_3_1_0());
this.assertEquals("foo", actual, actuals);
}
@Test
public void regionForAssignment() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("6 (foo)");
final Mixed mixed = this.<Mixed>parseAs(_builder, Mixed.class);
final ISemanticRegionsFinder finder = this.toAccess(mixed).regionForEObject(mixed).getRegionFor();
final ISemanticRegion actual = finder.assignment(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getNameAssignment_2_2_0());
final List<ISemanticRegion> actuals = finder.assignments(this._regionAccessTestLanguageGrammarAccess.getMixedAccess().getNameAssignment_2_2_0());
this.assertEquals("foo", actual, actuals);
}
@Test
public void regionForKeywordPairs() {
@Extension
final RegionAccessTestLanguageGrammarAccess.ParenthesizedElements rule = this._regionAccessTestLanguageGrammarAccess.getParenthesizedAccess();
StringConcatenation _builder = new StringConcatenation();
_builder.append("5 (foo)");
final Expression expr = this.<Expression>parseAs(_builder, Expression.class);
final ISemanticRegionsFinder finder = this.toAccess(expr).regionForEObject(expr).getRegionFor();
final String actual1 = this.pairsToString(finder.keywordPairs("(", ")"));
final String actual2 = this.pairsToString(finder.keywordPairs(rule.getLeftParenthesisKeyword_0(), rule.getRightParenthesisKeyword_2()));
final String expected = "(foo)";
Assert.assertEquals(expected, actual1);
Assert.assertEquals(expected, actual2);
}
@Test
public void regionForKeywordPairs2() {
@Extension
final RegionAccessTestLanguageGrammarAccess.ParenthesizedElements rule = this._regionAccessTestLanguageGrammarAccess.getParenthesizedAccess();
StringConcatenation _builder = new StringConcatenation();
_builder.append("5 (a + ((b) + c) + d)");
final Expression expr = this.<Expression>parseAs(_builder, Expression.class);
final ISemanticRegionsFinder finder = this.toAccess(expr).regionForRootEObject().getAllRegionsFor();
final String actual1 = this.pairsToString(finder.keywordPairs("(", ")"));
final String actual2 = this.pairsToString(finder.keywordPairs(rule.getLeftParenthesisKeyword_0(), rule.getRightParenthesisKeyword_2()));
final String expected = "(b); ((b) + c); (a + ((b) + c) + d)";
Assert.assertEquals(expected, actual1);
Assert.assertEquals(expected, actual2);
}
private String pairsToString(final Iterable<Pair<ISemanticRegion, ISemanticRegion>> pairs) {
final Function1<Pair<ISemanticRegion, ISemanticRegion>, String> _function = (Pair<ISemanticRegion, ISemanticRegion> it) -> {
return it.getKey().merge(it.getValue()).getText();
};
return IterableExtensions.join(IterableExtensions.<Pair<ISemanticRegion, ISemanticRegion>, String>map(pairs, _function), "; ");
}
private <T extends EObject> T parseAs(final CharSequence seq, final Class<T> cls) {
try {
final Root result = this.parseHelper.parse(seq);
this.validationTestHelper.assertNoErrors(result);
return cls.cast(result);
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
private ITextRegionAccess toAccess(final EObject obj) {
Resource _eResource = obj.eResource();
return this.textRegionAccessBuilder.get().forNodeModel(((XtextResource) _eResource)).create();
}
private void assertEquals(final String expected, final ITextSegment single, final Collection<? extends ITextSegment> regions) {
Assert.assertEquals(expected, single.getText());
Assert.assertEquals(1, regions.size());
Assert.assertEquals(expected, IterableExtensions.head(regions).getText());
Assert.assertTrue((regions instanceof ImmutableList<?>));
}
}

View file

@ -1,292 +0,0 @@
/**
* Copyright (c) 2015 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.parser.parameters;
import com.google.inject.Injector;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.parser.parameters.parametersTestLanguage.ParserRuleParameters;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.tests.AbstractXtextTests;
import org.eclipse.xtext.xbase.lib.Exceptions;
import org.eclipse.xtext.xbase.lib.IterableExtensions;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
@SuppressWarnings("all")
public abstract class AbstractParametersParsingTest extends AbstractXtextTests {
@Override
protected void setInjector(final Injector injector) {
super.setInjector(injector);
this.injectMembers(this);
}
@Override
protected boolean shouldTestSerializer(final XtextResource resource) {
return false;
}
@Override
public ParserRuleParameters getModel(final String model) throws Exception {
EObject _model = super.getModel(model);
return ((ParserRuleParameters) _model);
}
protected ParserRuleParameters getModelWithErrors(final String model) throws Exception {
EObject _modelAndExpect = this.getModelAndExpect(model, AbstractXtextTests.EXPECT_ERRORS);
return ((ParserRuleParameters) _modelAndExpect);
}
@Test
public void testScenario1_first() {
try {
final ParserRuleParameters instance = this.getModel("#1 first");
Assert.assertEquals("first", instance.getScenario().getFirst());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario2_second() {
try {
final ParserRuleParameters instance = this.getModel("#2 second");
Assert.assertEquals("second", instance.getScenario().getSecond());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario3_keyword() {
try {
final ParserRuleParameters instance = this.getModel("#3 keyword");
Assert.assertEquals("keyword", instance.getScenario().getFirst());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario3_id() {
try {
final ParserRuleParameters instance = this.getModel("#3 id");
Assert.assertEquals("id", instance.getScenario().getFirst());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario4_keyword() {
try {
final ParserRuleParameters instance = this.getModelWithErrors("#4 keyword");
Assert.assertEquals(null, instance.getScenario().getFirst());
Assert.assertEquals(1, instance.eResource().getErrors().size());
Assert.assertEquals("mismatched input \'keyword\' expecting RULE_ID", IterableExtensions.<Resource.Diagnostic>head(instance.eResource().getErrors()).getMessage());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario4_id() {
try {
final ParserRuleParameters instance = this.getModel("#4 id");
Assert.assertEquals("id", instance.getScenario().getFirst());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario5_keyword() {
try {
final ParserRuleParameters instance = this.getModel("#5 keyword");
Assert.assertEquals("keyword", instance.getScenario().getFirst());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario5_id() {
try {
final ParserRuleParameters instance = this.getModel("#5 id");
Assert.assertEquals("id", instance.getScenario().getFirst());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario6_keyword() {
try {
final ParserRuleParameters instance = this.getModelWithErrors("#6 keyword");
Assert.assertEquals(null, instance.getScenario());
Assert.assertEquals("no viable alternative at input \'#6\'", IterableExtensions.<Resource.Diagnostic>head(instance.eResource().getErrors()).getMessage());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario6_id() {
try {
final ParserRuleParameters instance = this.getModel("#6 id");
Assert.assertEquals("id", instance.getScenario().getFirst());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario7_keyword() {
try {
final ParserRuleParameters instance = this.getModel("#7 keyword");
Assert.assertEquals("keyword", instance.getScenario().getFirst());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario7_id() {
try {
final ParserRuleParameters instance = this.getModel("#7 id");
Assert.assertEquals("id", instance.getScenario().getFirst());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario8_keyword() {
try {
final ParserRuleParameters instance = this.getModel("#8 keyword");
Assert.assertEquals("keyword", instance.getScenario().getSecond());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario8_id() {
try {
final ParserRuleParameters instance = this.getModel("#8 id");
Assert.assertEquals("id", instance.getScenario().getFirst());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario9_keyword_keyword() {
try {
final ParserRuleParameters instance = this.getModel("#9 keyword keyword");
Assert.assertEquals("keyword", instance.getScenario().getSecond());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario9_id_keyword() {
try {
final ParserRuleParameters instance = this.getModel("#9 id keyword");
Assert.assertEquals("id", instance.getScenario().getSecond());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario9_id() {
try {
final ParserRuleParameters instance = this.getModel("#9 id");
Assert.assertEquals("id", instance.getScenario().getFirst());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario9_keyword() {
try {
final ParserRuleParameters instance = this.getModel("#9 keyword");
Assert.assertEquals("keyword", instance.getScenario().getFirst());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario10_keyword_keyword() {
try {
final ParserRuleParameters instance = this.getModel("#10 keyword keyword");
Assert.assertEquals("keyword", instance.getScenario().getSecond());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario10_id_keyword() {
try {
final ParserRuleParameters instance = this.getModel("#10 id keyword");
Assert.assertEquals("id", instance.getScenario().getSecond());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario10_id() {
try {
final ParserRuleParameters instance = this.getModel("#10 id");
Assert.assertEquals("id", instance.getScenario().getFirst());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario10_keyword() {
try {
final ParserRuleParameters instance = this.getModelWithErrors("#10 keyword");
Assert.assertEquals("keyword", instance.getScenario().getSecond());
Assert.assertEquals("mismatched input \'<EOF>\' expecting \'keyword\'", IterableExtensions.<Resource.Diagnostic>head(instance.eResource().getErrors()).getMessage());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario11_keyword_keyword() {
try {
final ParserRuleParameters instance = this.getModel("#11 keyword keyword");
Assert.assertEquals("keyword", instance.getScenario().getFirst());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testScenario11_id_keyword() {
try {
final ParserRuleParameters instance = this.getModel("#11 id keyword");
Assert.assertEquals("id", instance.getScenario().getSecond());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
}

View file

@ -1,25 +0,0 @@
/**
* Copyright (c) 2015 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.parser.parameters;
import org.eclipse.xtext.parser.parameters.AbstractParametersParsingTest;
import org.eclipse.xtext.parser.parameters.NoParametersTestLanguageStandaloneSetup;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
@SuppressWarnings("all")
public class NoParametersParsingTest extends AbstractParametersParsingTest {
@Override
public void setUp() throws Exception {
super.setUp();
NoParametersTestLanguageStandaloneSetup _noParametersTestLanguageStandaloneSetup = new NoParametersTestLanguageStandaloneSetup();
this.with(_noParametersTestLanguageStandaloneSetup);
}
}

View file

@ -1,25 +0,0 @@
/**
* Copyright (c) 2015 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.parser.parameters;
import org.eclipse.xtext.parser.parameters.AbstractParametersParsingTest;
import org.eclipse.xtext.parser.parameters.ParametersTestLanguageStandaloneSetup;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
@SuppressWarnings("all")
public class ParametersParsingTest extends AbstractParametersParsingTest {
@Override
public void setUp() throws Exception {
super.setUp();
ParametersTestLanguageStandaloneSetup _parametersTestLanguageStandaloneSetup = new ParametersTestLanguageStandaloneSetup();
this.with(_parametersTestLanguageStandaloneSetup);
}
}

View file

@ -1,25 +0,0 @@
/**
* Copyright (c) 2015 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.parser.parameters;
import org.eclipse.xtext.parser.parameters.AbstractParametersParsingTest;
import org.eclipse.xtext.parser.parameters.ParametersTestLanguageExStandaloneSetup;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
@SuppressWarnings("all")
public class ParametersParsingTestEx extends AbstractParametersParsingTest {
@Override
public void setUp() throws Exception {
super.setUp();
ParametersTestLanguageExStandaloneSetup _parametersTestLanguageExStandaloneSetup = new ParametersTestLanguageExStandaloneSetup();
this.with(_parametersTestLanguageExStandaloneSetup);
}
}

View file

@ -1,25 +0,0 @@
/**
* Copyright (c) 2015 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.parser.parameters;
import org.eclipse.xtext.parser.parameters.AbstractParametersParsingTest;
import org.eclipse.xtext.parser.parameters.TwoParametersTestLanguageStandaloneSetup;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
@SuppressWarnings("all")
public class TwoParametersParsingTest extends AbstractParametersParsingTest {
@Override
public void setUp() throws Exception {
super.setUp();
TwoParametersTestLanguageStandaloneSetup _twoParametersTestLanguageStandaloneSetup = new TwoParametersTestLanguageStandaloneSetup();
this.with(_twoParametersTestLanguageStandaloneSetup);
}
}

View file

@ -1,84 +0,0 @@
/**
* Copyright (c) 2012, 2018 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.resource;
import com.google.common.base.Objects;
import java.io.File;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.xtext.resource.NullResource;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.xbase.lib.Exceptions;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Sven Efftinge - Initial contribution and API
*/
@SuppressWarnings("all")
public abstract class AbstractResourceSetTest {
protected abstract ResourceSetImpl createEmptyResourceSet();
@Test
public void testDemandLoadedResourcesAreInMap() {
final ResourceSetImpl rs = this.createEmptyResourceSet();
final Resource.Factory _function = (URI uri) -> {
NullResource _xblockexpression = null;
{
final NullResource result = new NullResource();
result.setURI(uri);
_xblockexpression = result;
}
return _xblockexpression;
};
final Resource.Factory nullFactory = _function;
rs.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi", nullFactory);
Assert.assertEquals(0, rs.getURIResourceMap().size());
final URI uri = URI.createURI("file:/does/not/exist.xmi");
final Resource demandLoaded = rs.getResource(uri, true);
Assert.assertNotNull(demandLoaded);
final Resource second = rs.getResource(uri, true);
Assert.assertSame(demandLoaded, second);
Assert.assertEquals(1, rs.getURIResourceMap().size());
}
@Test
public void testResourceLocatorIsUsed() {
final ResourceSetImpl rs = this.createEmptyResourceSet();
final XtextResource resource = new XtextResource();
resource.setURI(URI.createFileURI(new File("foo").getAbsolutePath()));
new ResourceSetImpl.ResourceLocator(rs) {
@Override
public Resource getResource(final URI uri, final boolean loadOnDemand) {
URI _uRI = resource.getURI();
boolean _equals = Objects.equal(uri, _uRI);
if (_equals) {
return resource;
}
String _string = uri.toString();
throw new IllegalArgumentException(_string);
}
};
Assert.assertSame(resource, rs.getResource(resource.getURI(), true));
Assert.assertTrue(rs.getResources().isEmpty());
Assert.assertNull(resource.getResourceSet());
try {
rs.getResource(resource.getURI().appendSegment("doesNotExist"), true);
Assert.fail();
} catch (final Throwable _t) {
if (_t instanceof IllegalArgumentException) {
final IllegalArgumentException e = (IllegalArgumentException)_t;
Assert.assertTrue(e.getMessage().endsWith("doesNotExist"));
} else {
throw Exceptions.sneakyThrow(_t);
}
}
}
}

View file

@ -1,5 +1,5 @@
/**
* Copyright (c) 2012, 2018 itemis AG (http://www.itemis.eu) and others.
* Copyright (c) 2012, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.

View file

@ -1,56 +0,0 @@
/**
* Copyright (c) 2014, 2017 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.resource;
import java.io.IOException;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.resource.DerivedStateAwareResource;
import org.eclipse.xtext.testlanguages.OptionalEmptyTestLanguageStandaloneSetup;
import org.eclipse.xtext.tests.AbstractXtextTests;
import org.eclipse.xtext.util.StringInputStream;
import org.eclipse.xtext.xbase.lib.Exceptions;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Jan Koehnlein - Initial contribution and API
*/
@SuppressWarnings("all")
public class Bug451668Test extends AbstractXtextTests {
public static class TestResource extends DerivedStateAwareResource {
private int contentsCalls = 0;
@Override
public synchronized EList<EObject> getContents() {
this.contentsCalls++;
return super.getContents();
}
}
@Test
public void testUnloadAndGetContents() throws IOException {
try {
this.with(OptionalEmptyTestLanguageStandaloneSetup.class);
Bug451668Test.TestResource r = this.<Bug451668Test.TestResource>get(Bug451668Test.TestResource.class);
r.setURI(URI.createURI("foo.dummy"));
StringInputStream _stringInputStream = new StringInputStream("");
r.load(_stringInputStream, null);
Assert.assertTrue(r.isLoaded());
final int callsBeforeUnload = r.contentsCalls;
r.unload();
Assert.assertEquals(callsBeforeUnload, r.contentsCalls);
Assert.assertFalse(r.isLoaded());
Assert.assertNull(r.getParseResult());
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
}

View file

@ -1,29 +0,0 @@
/**
* Copyright (c) 2012, 2018 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.resource;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.xtext.resource.AbstractResourceSetTest;
import org.eclipse.xtext.xbase.lib.CollectionLiterals;
import org.eclipse.xtext.xbase.lib.ObjectExtensions;
import org.eclipse.xtext.xbase.lib.Procedures.Procedure1;
@SuppressWarnings("all")
public class ResourceSetTest extends AbstractResourceSetTest {
@Override
protected ResourceSetImpl createEmptyResourceSet() {
ResourceSetImpl _resourceSetImpl = new ResourceSetImpl();
final Procedure1<ResourceSetImpl> _function = (ResourceSetImpl it) -> {
it.setURIResourceMap(CollectionLiterals.<URI, Resource>newHashMap());
};
return ObjectExtensions.<ResourceSetImpl>operator_doubleArrow(_resourceSetImpl, _function);
}
}

View file

@ -1,100 +0,0 @@
/**
* Copyright (c) 2016, 2020 TypeFox GmbH (http://www.typefox.io/) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.resource;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.ParserRule;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import org.eclipse.xtext.resource.IResourceFactory;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.testlanguages.ActionTestLanguage3StandaloneSetup;
import org.eclipse.xtext.testlanguages.ReferenceGrammarTestLanguageStandaloneSetup;
import org.eclipse.xtext.testlanguages.services.ActionTestLanguage3GrammarAccess;
import org.eclipse.xtext.testlanguages.services.ReferenceGrammarTestLanguageGrammarAccess;
import org.eclipse.xtext.tests.AbstractXtextTests;
import org.eclipse.xtext.util.StringInputStream;
import org.eclipse.xtext.xbase.lib.CollectionLiterals;
import org.eclipse.xtext.xbase.lib.Exceptions;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Moritz Eysholdt - Initial contribution and API
*/
@SuppressWarnings("all")
public class SetEntryPointOnXtextResourceTest extends AbstractXtextTests {
@Test
public void test1() {
try {
this.with(ReferenceGrammarTestLanguageStandaloneSetup.class);
final String model = "kind (Hugo 13)";
final ParserRule kindRule = this.<ReferenceGrammarTestLanguageGrammarAccess>get(ReferenceGrammarTestLanguageGrammarAccess.class).getKindRule();
final XtextResource resource = this.createResource();
resource.setEntryPoint(kindRule);
StringInputStream _stringInputStream = new StringInputStream(model);
resource.load(_stringInputStream, CollectionLiterals.<Object, Object>emptyMap());
Assert.assertTrue(resource.getErrors().isEmpty());
Assert.assertEquals(kindRule, NodeModelUtils.getEntryParserRule(resource.getParseResult().getRootNode()));
final String originalNodeModel = NodeModelUtils.compactDump(resource.getParseResult().getRootNode(), false);
resource.update(0, model.length(), ((" " + model) + " "));
final String reparsedNodeModel = NodeModelUtils.compactDump(resource.getParseResult().getRootNode(), false);
Assert.assertEquals(originalNodeModel, reparsedNodeModel);
final ParserRule erwachsenerRule = this.<ReferenceGrammarTestLanguageGrammarAccess>get(ReferenceGrammarTestLanguageGrammarAccess.class).getErwachsenerRule();
resource.setEntryPoint(erwachsenerRule);
resource.update(0, model.length(), "erwachsener (Peter 30)");
Assert.assertEquals(erwachsenerRule, NodeModelUtils.getEntryParserRule(resource.getParseResult().getRootNode()));
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void test2() {
try {
this.with(ActionTestLanguage3StandaloneSetup.class);
final ParserRule rule = this.<ActionTestLanguage3GrammarAccess>get(ActionTestLanguage3GrammarAccess.class).getProductionRule1Rule();
final String model = "X \"Y\" 42";
final XtextResource resource = this.createResource();
resource.setEntryPoint(rule);
StringInputStream _stringInputStream = new StringInputStream(model);
resource.load(_stringInputStream, CollectionLiterals.<Object, Object>emptyMap());
Assert.assertTrue(resource.getErrors().isEmpty());
final ParserRule entryRule = NodeModelUtils.getEntryParserRule(resource.getParseResult().getRootNode());
Assert.assertEquals(rule, entryRule);
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void test3() {
try {
this.with(ActionTestLanguage3StandaloneSetup.class);
final ParserRule rule = this.<ActionTestLanguage3GrammarAccess>get(ActionTestLanguage3GrammarAccess.class).getProductionRule2Rule();
final String model = "\"Y\" X42";
final XtextResource resource = this.createResource();
resource.setEntryPoint(rule);
StringInputStream _stringInputStream = new StringInputStream(model);
resource.load(_stringInputStream, CollectionLiterals.<Object, Object>emptyMap());
Assert.assertTrue(resource.getErrors().isEmpty());
final ParserRule entryRule = NodeModelUtils.getEntryParserRule(resource.getParseResult().getRootNode());
Assert.assertEquals(rule, entryRule);
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
private XtextResource createResource() {
String _currentFileExtension = this.getCurrentFileExtension();
String _plus = ("dummy." + _currentFileExtension);
Resource _createResource = this.<IResourceFactory>get(IResourceFactory.class).createResource(URI.createURI(_plus));
return ((XtextResource) _createResource);
}
}

View file

@ -1,5 +1,5 @@
/**
* Copyright (c) 2012, 2018 itemis AG (http://www.itemis.eu) and others.
* Copyright (c) 2012, 2020 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.

View file

@ -1,205 +0,0 @@
/**
* Copyright (c) 2014 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.resource.persistence;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collections;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.xtext.naming.QualifiedName;
import org.eclipse.xtext.resource.persistence.SerializableEObjectDescription;
import org.eclipse.xtext.resource.persistence.SerializableReferenceDescription;
import org.eclipse.xtext.resource.persistence.SerializableResourceDescription;
import org.eclipse.xtext.xbase.lib.CollectionLiterals;
import org.eclipse.xtext.xbase.lib.Exceptions;
import org.eclipse.xtext.xbase.lib.ExclusiveRange;
import org.eclipse.xtext.xbase.lib.ObjectExtensions;
import org.eclipse.xtext.xbase.lib.Pair;
import org.eclipse.xtext.xbase.lib.Procedures.Procedure1;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Sven Efftinge - Initial contribution and API
*/
@SuppressWarnings("all")
public class SerializableResourceDescriptionTest {
@Test
public void testSerialization() {
try {
final URI uri = URI.createURI("file:/foo/bar.baz.foo");
SerializableResourceDescription _serializableResourceDescription = new SerializableResourceDescription();
final Procedure1<SerializableResourceDescription> _function = (SerializableResourceDescription it) -> {
it.setURI(uri);
SerializableReferenceDescription _serializableReferenceDescription = new SerializableReferenceDescription();
final Procedure1<SerializableReferenceDescription> _function_1 = (SerializableReferenceDescription it_1) -> {
it_1.setSourceEObjectUri(uri.appendFragment("foo"));
it_1.setTargetEObjectUri(uri.appendFragment("hubble"));
it_1.setContainerEObjectURI(uri.appendFragment("baz"));
it_1.setEReference(EcorePackage.eINSTANCE.getEAnnotation_Contents());
it_1.setIndexInList(1);
};
SerializableReferenceDescription _doubleArrow = ObjectExtensions.<SerializableReferenceDescription>operator_doubleArrow(_serializableReferenceDescription, _function_1);
SerializableReferenceDescription _serializableReferenceDescription_1 = new SerializableReferenceDescription();
final Procedure1<SerializableReferenceDescription> _function_2 = (SerializableReferenceDescription it_1) -> {
it_1.setSourceEObjectUri(uri.appendFragment("foo2"));
it_1.setTargetEObjectUri(uri.appendFragment("hubble2"));
it_1.setContainerEObjectURI(uri.appendFragment("baz2"));
it_1.setEReference(EcorePackage.eINSTANCE.getEAnnotation_Contents());
it_1.setIndexInList(2);
};
SerializableReferenceDescription _doubleArrow_1 = ObjectExtensions.<SerializableReferenceDescription>operator_doubleArrow(_serializableReferenceDescription_1, _function_2);
it.setReferences(Collections.<SerializableReferenceDescription>unmodifiableList(CollectionLiterals.<SerializableReferenceDescription>newArrayList(_doubleArrow, _doubleArrow_1)));
SerializableEObjectDescription _serializableEObjectDescription = new SerializableEObjectDescription();
final Procedure1<SerializableEObjectDescription> _function_3 = (SerializableEObjectDescription it_1) -> {
it_1.setEObjectURI(uri.appendFragment("baz"));
it_1.qualifiedName = QualifiedName.create("foo", "baz");
it_1.setEClass(EcorePackage.eINSTANCE.getEAttribute());
Pair<String, String> _mappedTo = Pair.<String, String>of("myKey", "myValue");
it_1.userData = CollectionLiterals.<String, String>newHashMap(_mappedTo);
};
SerializableEObjectDescription _doubleArrow_2 = ObjectExtensions.<SerializableEObjectDescription>operator_doubleArrow(_serializableEObjectDescription, _function_3);
it.setDescriptions(Collections.<SerializableEObjectDescription>unmodifiableList(CollectionLiterals.<SerializableEObjectDescription>newArrayList(_doubleArrow_2)));
QualifiedName _create = QualifiedName.create("foo");
QualifiedName _create_1 = QualifiedName.create("foo", "bar");
it.setImportedNames(Collections.<QualifiedName>unmodifiableList(CollectionLiterals.<QualifiedName>newArrayList(_create, _create_1)));
};
final SerializableResourceDescription before = ObjectExtensions.<SerializableResourceDescription>operator_doubleArrow(_serializableResourceDescription, _function);
final ByteArrayOutputStream bout = new ByteArrayOutputStream();
final ObjectOutputStream objectOut = new ObjectOutputStream(bout);
objectOut.writeObject(before);
byte[] _byteArray = bout.toByteArray();
ByteArrayInputStream _byteArrayInputStream = new ByteArrayInputStream(_byteArray);
final ObjectInputStream in = new ObjectInputStream(_byteArrayInputStream);
Object _readObject = in.readObject();
final SerializableResourceDescription after = ((SerializableResourceDescription) _readObject);
this.assertDescriptionsEqual(before, after);
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
public void assertDescriptionsEqual(final SerializableResourceDescription before, final SerializableResourceDescription after) {
Assert.assertEquals(before.getURI(), after.getURI());
Assert.assertEquals(before.getImportedNames(), after.getImportedNames());
Assert.assertEquals(before.getReferences().size(), after.getReferences().size());
int _size = before.getReferences().size();
ExclusiveRange _doubleDotLessThan = new ExclusiveRange(0, _size, true);
for (final int i : _doubleDotLessThan) {
{
final SerializableReferenceDescription beforeRef = before.getReferences().get(i);
final SerializableReferenceDescription afterRef = after.getReferences().get(i);
Assert.assertEquals(beforeRef.getContainerEObjectURI(), afterRef.getContainerEObjectURI());
Assert.assertEquals(beforeRef.getSourceEObjectUri(), afterRef.getSourceEObjectUri());
Assert.assertEquals(beforeRef.getTargetEObjectUri(), afterRef.getTargetEObjectUri());
Assert.assertEquals(beforeRef.getEReference(), afterRef.getEReference());
Assert.assertEquals(beforeRef.getIndexInList(), afterRef.getIndexInList());
}
}
Assert.assertEquals(before.getDescriptions().size(), after.getDescriptions().size());
int _size_1 = before.getDescriptions().size();
ExclusiveRange _doubleDotLessThan_1 = new ExclusiveRange(0, _size_1, true);
for (final int i_1 : _doubleDotLessThan_1) {
{
final SerializableEObjectDescription beforeDesc = before.getDescriptions().get(i_1);
final SerializableEObjectDescription afterDesc = after.getDescriptions().get(i_1);
Assert.assertEquals(beforeDesc.getEClass(), afterDesc.getEClass());
Assert.assertEquals(beforeDesc.getName(), afterDesc.getName());
Assert.assertEquals(beforeDesc.qualifiedName, afterDesc.qualifiedName);
Assert.assertEquals(beforeDesc.userData, afterDesc.userData);
Assert.assertEquals(beforeDesc.getEObjectURI(), afterDesc.getEObjectURI());
}
}
}
@Test
public void testNullSafeSerialization() {
try {
final URI uri = URI.createURI("file:/foo/bar.baz.foo");
SerializableResourceDescription _serializableResourceDescription = new SerializableResourceDescription();
final Procedure1<SerializableResourceDescription> _function = (SerializableResourceDescription it) -> {
it.setURI(uri);
SerializableReferenceDescription _serializableReferenceDescription = new SerializableReferenceDescription();
final Procedure1<SerializableReferenceDescription> _function_1 = (SerializableReferenceDescription it_1) -> {
it_1.setSourceEObjectUri(uri.appendFragment("foo"));
it_1.setTargetEObjectUri(null);
it_1.setContainerEObjectURI(uri.appendFragment("baz"));
it_1.setEReference(EcorePackage.eINSTANCE.getEAnnotation_Contents());
it_1.setIndexInList(1);
};
SerializableReferenceDescription _doubleArrow = ObjectExtensions.<SerializableReferenceDescription>operator_doubleArrow(_serializableReferenceDescription, _function_1);
SerializableReferenceDescription _serializableReferenceDescription_1 = new SerializableReferenceDescription();
final Procedure1<SerializableReferenceDescription> _function_2 = (SerializableReferenceDescription it_1) -> {
it_1.setSourceEObjectUri(null);
it_1.setTargetEObjectUri(uri.appendFragment("hubble2"));
it_1.setContainerEObjectURI(uri.appendFragment("baz2"));
it_1.setEReference(EcorePackage.eINSTANCE.getEAnnotation_Contents());
it_1.setIndexInList(2);
};
SerializableReferenceDescription _doubleArrow_1 = ObjectExtensions.<SerializableReferenceDescription>operator_doubleArrow(_serializableReferenceDescription_1, _function_2);
SerializableReferenceDescription _serializableReferenceDescription_2 = new SerializableReferenceDescription();
final Procedure1<SerializableReferenceDescription> _function_3 = (SerializableReferenceDescription it_1) -> {
it_1.setSourceEObjectUri(uri.appendFragment("foo"));
it_1.setTargetEObjectUri(uri.appendFragment("hubble2"));
it_1.setContainerEObjectURI(null);
it_1.setEReference(EcorePackage.eINSTANCE.getEAnnotation_Contents());
it_1.setIndexInList(2);
};
SerializableReferenceDescription _doubleArrow_2 = ObjectExtensions.<SerializableReferenceDescription>operator_doubleArrow(_serializableReferenceDescription_2, _function_3);
SerializableReferenceDescription _serializableReferenceDescription_3 = new SerializableReferenceDescription();
final Procedure1<SerializableReferenceDescription> _function_4 = (SerializableReferenceDescription it_1) -> {
it_1.setSourceEObjectUri(uri.appendFragment("foo"));
it_1.setTargetEObjectUri(null);
it_1.setContainerEObjectURI(null);
it_1.setEReference(EcorePackage.eINSTANCE.getEAnnotation_Contents());
it_1.setIndexInList(2);
};
SerializableReferenceDescription _doubleArrow_3 = ObjectExtensions.<SerializableReferenceDescription>operator_doubleArrow(_serializableReferenceDescription_3, _function_4);
SerializableReferenceDescription _serializableReferenceDescription_4 = new SerializableReferenceDescription();
final Procedure1<SerializableReferenceDescription> _function_5 = (SerializableReferenceDescription it_1) -> {
it_1.setSourceEObjectUri(null);
it_1.setTargetEObjectUri(null);
it_1.setContainerEObjectURI(null);
it_1.setEReference(EcorePackage.eINSTANCE.getEAnnotation_Contents());
it_1.setIndexInList(2);
};
SerializableReferenceDescription _doubleArrow_4 = ObjectExtensions.<SerializableReferenceDescription>operator_doubleArrow(_serializableReferenceDescription_4, _function_5);
it.setReferences(Collections.<SerializableReferenceDescription>unmodifiableList(CollectionLiterals.<SerializableReferenceDescription>newArrayList(_doubleArrow, _doubleArrow_1, _doubleArrow_2, _doubleArrow_3, _doubleArrow_4)));
SerializableEObjectDescription _serializableEObjectDescription = new SerializableEObjectDescription();
final Procedure1<SerializableEObjectDescription> _function_6 = (SerializableEObjectDescription it_1) -> {
it_1.setEObjectURI(uri.appendFragment("baz"));
it_1.qualifiedName = QualifiedName.create("foo", "baz");
it_1.setEClass(EcorePackage.eINSTANCE.getEAttribute());
Pair<String, String> _mappedTo = Pair.<String, String>of("myKey", "myValue");
it_1.userData = CollectionLiterals.<String, String>newHashMap(_mappedTo);
};
SerializableEObjectDescription _doubleArrow_5 = ObjectExtensions.<SerializableEObjectDescription>operator_doubleArrow(_serializableEObjectDescription, _function_6);
it.setDescriptions(Collections.<SerializableEObjectDescription>unmodifiableList(CollectionLiterals.<SerializableEObjectDescription>newArrayList(_doubleArrow_5)));
QualifiedName _create = QualifiedName.create("foo");
QualifiedName _create_1 = QualifiedName.create("foo", "bar");
it.setImportedNames(Collections.<QualifiedName>unmodifiableList(CollectionLiterals.<QualifiedName>newArrayList(_create, _create_1)));
};
final SerializableResourceDescription before = ObjectExtensions.<SerializableResourceDescription>operator_doubleArrow(_serializableResourceDescription, _function);
final ByteArrayOutputStream bout = new ByteArrayOutputStream();
final ObjectOutputStream objectOut = new ObjectOutputStream(bout);
objectOut.writeObject(before);
byte[] _byteArray = bout.toByteArray();
ByteArrayInputStream _byteArrayInputStream = new ByteArrayInputStream(_byteArray);
final ObjectInputStream in = new ObjectInputStream(_byteArrayInputStream);
Object _readObject = in.readObject();
final SerializableResourceDescription after = ((SerializableResourceDescription) _readObject);
this.assertDescriptionsEqual(before, after);
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
}

View file

@ -1,107 +0,0 @@
/**
* Copyright (c) 2017 TypeFox GmbH (http://www.typefox.io) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.serializer;
import com.google.common.base.Objects;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtend2.lib.StringConcatenation;
import org.eclipse.xtext.resource.DefaultFragmentProvider;
import org.eclipse.xtext.resource.FileExtensionProvider;
import org.eclipse.xtext.resource.IFragmentProvider;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.resource.XtextResourceSet;
import org.eclipse.xtext.serializer.ISerializer;
import org.eclipse.xtext.serializer.SyntacticSequencerTestLanguageInjectorProvider;
import org.eclipse.xtext.serializer.syntacticsequencertest.Model;
import org.eclipse.xtext.serializer.syntacticsequencertest.SingleCrossReference;
import org.eclipse.xtext.serializer.syntacticsequencertest.SyntacticsequencertestFactory;
import org.eclipse.xtext.testing.InjectWith;
import org.eclipse.xtext.testing.XtextRunner;
import org.eclipse.xtext.xbase.lib.Extension;
import org.eclipse.xtext.xbase.lib.ObjectExtensions;
import org.eclipse.xtext.xbase.lib.Procedures.Procedure1;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(XtextRunner.class)
@InjectWith(SyntacticSequencerTestLanguageInjectorProvider.class)
@SuppressWarnings("all")
public class TokenSerializerTest {
@Inject
@Extension
private ISerializer _iSerializer;
@Inject
private FileExtensionProvider fileExtensionProvider;
@Inject
private Provider<XtextResourceSet> resourceSetProvider;
private final SyntacticsequencertestFactory factory = SyntacticsequencertestFactory.eINSTANCE;
private void assertSerializesTo(final Model model, final CharSequence expectation) {
Assert.assertEquals(expectation.toString().trim(), this._iSerializer.serialize(model).trim());
}
private URI getFileURI(final String name) {
String _primaryFileExtension = this.fileExtensionProvider.getPrimaryFileExtension();
String _plus = ((name + ".") + _primaryFileExtension);
return URI.createFileURI(_plus);
}
@Test
public void testConstructedCrossReferenceWithProxy() {
final XtextResourceSet resourceSet = this.resourceSetProvider.get();
Resource _createResource = resourceSet.createResource(this.getFileURI("dummy"));
final XtextResource resource = ((XtextResource) _createResource);
Model _createModel = this.factory.createModel();
final Procedure1<Model> _function = (Model it) -> {
SingleCrossReference _createSingleCrossReference = this.factory.createSingleCrossReference();
final Procedure1<SingleCrossReference> _function_1 = (SingleCrossReference it_1) -> {
it_1.setName("myref");
};
SingleCrossReference _doubleArrow = ObjectExtensions.<SingleCrossReference>operator_doubleArrow(_createSingleCrossReference, _function_1);
it.setX5(_doubleArrow);
};
final Model model = ObjectExtensions.<Model>operator_doubleArrow(_createModel, _function);
EList<EObject> _contents = resource.getContents();
_contents.add(model);
SingleCrossReference _x5 = model.getX5();
SingleCrossReference _createSingleCrossReference = this.factory.createSingleCrossReference();
final Procedure1<SingleCrossReference> _function_1 = (SingleCrossReference it) -> {
((InternalEObject) it).eSetProxyURI(resource.getURI().appendFragment("foo"));
};
SingleCrossReference _doubleArrow = ObjectExtensions.<SingleCrossReference>operator_doubleArrow(_createSingleCrossReference, _function_1);
_x5.setRef3(_doubleArrow);
resource.setFragmentProvider(new DefaultFragmentProvider() {
@Override
public EObject getEObject(final Resource resource, final String fragment, final IFragmentProvider.Fallback fallback) {
EObject _xifexpression = null;
boolean _equals = Objects.equal(fragment, "foo");
if (_equals) {
_xifexpression = model.getX5();
} else {
_xifexpression = super.getEObject(resource, fragment, fallback);
}
return _xifexpression;
}
});
StringConcatenation _builder = new StringConcatenation();
_builder.append("#5 myref kw3 myref");
_builder.newLine();
this.assertSerializesTo(model, _builder);
}
}

View file

@ -1,72 +0,0 @@
/**
* Copyright (c) 2014 itemis AG (http://www.itemis.eu) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.tasks;
import java.util.Collections;
import java.util.List;
import org.eclipse.xtext.preferences.IPreferenceValuesProvider;
import org.eclipse.xtext.preferences.MapBasedPreferenceValues;
import org.eclipse.xtext.tasks.PreferenceTaskTagProvider;
import org.eclipse.xtext.tasks.Priority;
import org.eclipse.xtext.tasks.TaskTag;
import org.eclipse.xtext.tasks.TaskTags;
import org.eclipse.xtext.xbase.lib.CollectionLiterals;
import org.eclipse.xtext.xbase.lib.Conversions;
import org.eclipse.xtext.xbase.lib.ExclusiveRange;
import org.eclipse.xtext.xbase.lib.IterableExtensions;
import org.eclipse.xtext.xbase.lib.ObjectExtensions;
import org.eclipse.xtext.xbase.lib.Procedures.Procedure1;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Stefan Oehme - Initial contribution and API
*/
@SuppressWarnings("all")
public class PreferenceTaskTagProviderTest {
@Test
public void test() {
TaskTag _taskTag = new TaskTag();
final Procedure1<TaskTag> _function = (TaskTag it) -> {
it.setName("Foo");
it.setPriority(Priority.LOW);
};
TaskTag _doubleArrow = ObjectExtensions.<TaskTag>operator_doubleArrow(_taskTag, _function);
TaskTag _taskTag_1 = new TaskTag();
final Procedure1<TaskTag> _function_1 = (TaskTag it) -> {
it.setName("BAR");
it.setPriority(Priority.NORMAL);
};
TaskTag _doubleArrow_1 = ObjectExtensions.<TaskTag>operator_doubleArrow(_taskTag_1, _function_1);
TaskTag _taskTag_2 = new TaskTag();
final Procedure1<TaskTag> _function_2 = (TaskTag it) -> {
it.setName("baZ");
it.setPriority(Priority.HIGH);
};
TaskTag _doubleArrow_2 = ObjectExtensions.<TaskTag>operator_doubleArrow(_taskTag_2, _function_2);
final List<TaskTag> tags = Collections.<TaskTag>unmodifiableList(CollectionLiterals.<TaskTag>newArrayList(_doubleArrow, _doubleArrow_1, _doubleArrow_2));
final String names = PreferenceTaskTagProvider.serializeTags(tags);
final String prios = PreferenceTaskTagProvider.serializePriorities(tags);
final IPreferenceValuesProvider.SingletonPreferenceValuesProvider valueProvider = new IPreferenceValuesProvider.SingletonPreferenceValuesProvider();
final MapBasedPreferenceValues values = valueProvider.getPreferenceValues(null);
values.put(PreferenceTaskTagProvider.TAGS_KEY.getId(), names);
values.put(PreferenceTaskTagProvider.PRIORITIES_KEY.getId(), prios);
values.put(PreferenceTaskTagProvider.CASE_SENSITIVE_KEY.getId(), "false");
final PreferenceTaskTagProvider tagProvider = new PreferenceTaskTagProvider();
tagProvider.setPreferenceValuesProvider(valueProvider);
final TaskTags parsedTags = tagProvider.getTaskTags(null);
Assert.assertEquals(Boolean.valueOf(false), Boolean.valueOf(parsedTags.isCaseSensitive()));
Assert.assertEquals(tags.size(), IterableExtensions.size(parsedTags));
int _size = tags.size();
ExclusiveRange _doubleDotLessThan = new ExclusiveRange(0, _size, true);
for (final Integer i : _doubleDotLessThan) {
Assert.assertEquals(tags.get((i).intValue()), ((Object[])Conversions.unwrapArray(parsedTags, Object.class))[(i).intValue()]);
}
}
}

View file

@ -1,189 +0,0 @@
/**
* Copyright (c) 2019 Malardalen University (http://www.mdh.se) and others.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.xtext.xtext;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import org.eclipse.xtend2.lib.StringConcatenation;
import org.eclipse.xtext.Grammar;
import org.eclipse.xtext.XtextPackage;
import org.eclipse.xtext.XtextRuntimeModule;
import org.eclipse.xtext.XtextStandaloneSetup;
import org.eclipse.xtext.diagnostics.Severity;
import org.eclipse.xtext.preferences.IPreferenceValuesProvider;
import org.eclipse.xtext.preferences.MapBasedPreferenceValues;
import org.eclipse.xtext.testing.InjectWith;
import org.eclipse.xtext.testing.XtextRunner;
import org.eclipse.xtext.testing.util.ParseHelper;
import org.eclipse.xtext.testing.validation.ValidationTestHelper;
import org.eclipse.xtext.tests.AbstractXtextTests;
import org.eclipse.xtext.tests.XtextInjectorProvider;
import org.eclipse.xtext.xbase.lib.Exceptions;
import org.eclipse.xtext.xbase.lib.Extension;
import org.eclipse.xtext.xtext.XtextConfigurableIssueCodes;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Lorenzo Addazi - Initial contribution and API
*/
@RunWith(XtextRunner.class)
@InjectWith(XtextInjectorProvider.class)
@SuppressWarnings("all")
public class Issue1161Test extends AbstractXtextTests {
/**
* @author Lorenzo Addazi - Initial contribution and API
*/
public static class Issue1161StandaloneSetup extends XtextStandaloneSetup {
@Override
public Injector createInjector() {
abstract class __Issue1161StandaloneSetup_1 extends XtextRuntimeModule {
public abstract Class<? extends IPreferenceValuesProvider> bindIPreferenceValuesProvider();
}
__Issue1161StandaloneSetup_1 ___Issue1161StandaloneSetup_1 = new __Issue1161StandaloneSetup_1() {
public Class<? extends IPreferenceValuesProvider> bindIPreferenceValuesProvider() {
return IPreferenceValuesProvider.SingletonPreferenceValuesProvider.class;
}
};
return Guice.createInjector(___Issue1161StandaloneSetup_1);
}
}
@Inject
@Extension
private ValidationTestHelper _validationTestHelper;
@Inject
@Extension
private ParseHelper<Grammar> _parseHelper;
@Inject
private MapBasedPreferenceValues preferences;
@Override
public void setUp() throws Exception {
super.setUp();
this.with(Issue1161Test.Issue1161StandaloneSetup.class);
}
@Before
public void setPreferences() {
this.preferences = this.<IPreferenceValuesProvider.SingletonPreferenceValuesProvider>get(IPreferenceValuesProvider.SingletonPreferenceValuesProvider.class).getPreferenceValues(null);
}
@After
public void clearPreferences() {
this.preferences.clear();
}
@Test
public void testValidJavaPackageNamingConventionsWithIgnoreSeverity() {
this.assertNoIssue(this.grammarWithValidJavaPackageNamingConventions());
}
@Test
public void testInvalidJavaPackageNamingConventionsWithIgnoreSeverity() {
this.assertNoIssue(this.grammarWithInvalidJavaPackageNamingConventions());
}
@Test
public void testValidJavaPackageNamingConventionsWithErrorSeverity() {
this.setSeverity("error");
this.assertNoIssue(this.grammarWithValidJavaPackageNamingConventions());
}
@Test
public void testInvalidJavaPackageNamingConventionsWithErrorSeverity() {
this.setSeverity("error");
this.assertError(this.grammarWithInvalidJavaPackageNamingConventions());
}
@Test
public void testValidJavaPackageNamingConventionsWithWarningSeverity() {
this.setSeverity("warning");
this.assertNoIssue(this.grammarWithValidJavaPackageNamingConventions());
}
@Test
public void testInvalidJavaPackageNamingConventionsWithWarningSeverity() {
this.setSeverity("warning");
this.assertWarning(this.grammarWithInvalidJavaPackageNamingConventions());
}
@Test
public void testValidJavaPackageNamingConventionsWithInfoSeverity() {
this.setSeverity("info");
this.assertNoIssue(this.grammarWithValidJavaPackageNamingConventions());
}
@Test
public void testInvalidJavaPackageNamingConventionsWithInfoSeverity() {
this.setSeverity("info");
this.assertInfo(this.grammarWithInvalidJavaPackageNamingConventions());
}
private void assertError(final CharSequence grammar) {
this.assertIssue(grammar, Severity.ERROR);
}
private void assertWarning(final CharSequence grammar) {
this.assertIssue(grammar, Severity.WARNING);
}
private void assertInfo(final CharSequence grammar) {
this.assertIssue(grammar, Severity.INFO);
}
private void assertIssue(final CharSequence grammar, final Severity severity) {
try {
this._validationTestHelper.assertIssue(this._parseHelper.parse(grammar), XtextPackage.Literals.GENERATED_METAMODEL,
XtextConfigurableIssueCodes.INVALID_JAVAPACKAGE_NAME, severity);
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
private void assertNoIssue(final CharSequence grammar) {
try {
this._validationTestHelper.assertNoIssue(this._parseHelper.parse(grammar), XtextPackage.Literals.GENERATED_METAMODEL,
XtextConfigurableIssueCodes.INVALID_JAVAPACKAGE_NAME);
} catch (Throwable _e) {
throw Exceptions.sneakyThrow(_e);
}
}
private CharSequence grammarWithValidJavaPackageNamingConventions() {
return this.grammarWithGeneratedMetamodelName("testissue1161");
}
private CharSequence grammarWithInvalidJavaPackageNamingConventions() {
return this.grammarWithGeneratedMetamodelName("testIssue1161");
}
private CharSequence grammarWithGeneratedMetamodelName(final String generatedMetamodelName) {
StringConcatenation _builder = new StringConcatenation();
_builder.append("grammar test.Issue1161 with org.eclipse.xtext.common.Terminals");
_builder.newLine();
_builder.append("generate ");
_builder.append(generatedMetamodelName);
_builder.append(" \"http://issue1161\"");
_builder.newLineIfNotEmpty();
_builder.append("A : {A};");
_builder.newLine();
return _builder;
}
private void setSeverity(final String severity) {
this.preferences.put(XtextConfigurableIssueCodes.INVALID_JAVAPACKAGE_NAME, severity);
}
}