diff --git a/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/commands/CommandRegistryTest.java b/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/commands/CommandRegistryTest.java new file mode 100644 index 000000000..96cc67f7f --- /dev/null +++ b/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/commands/CommandRegistryTest.java @@ -0,0 +1,199 @@ +/** + * 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.commands; + +import java.util.Collections; +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 org.eclipse.emf.common.util.URI; +import org.eclipse.lsp4j.ApplyWorkspaceEditParams; +import org.eclipse.lsp4j.ApplyWorkspaceEditResponse; +import org.eclipse.lsp4j.ClientCapabilities; +import org.eclipse.lsp4j.ConfigurationParams; +import org.eclipse.lsp4j.ExecuteCommandCapabilities; +import org.eclipse.lsp4j.ExecuteCommandParams; +import org.eclipse.lsp4j.MessageActionItem; +import org.eclipse.lsp4j.MessageParams; +import org.eclipse.lsp4j.PublishDiagnosticsParams; +import org.eclipse.lsp4j.Registration; +import org.eclipse.lsp4j.RegistrationParams; +import org.eclipse.lsp4j.SemanticHighlightingParams; +import org.eclipse.lsp4j.ShowMessageRequestParams; +import org.eclipse.lsp4j.Unregistration; +import org.eclipse.lsp4j.UnregistrationParams; +import org.eclipse.lsp4j.WorkspaceClientCapabilities; +import org.eclipse.lsp4j.WorkspaceFolder; +import org.eclipse.lsp4j.services.LanguageClient; +import org.eclipse.xtend.lib.annotations.Delegate; +import org.eclipse.xtext.ide.server.ILanguageServerAccess; +import org.eclipse.xtext.ide.server.commands.ExecutableCommandRegistry; +import org.eclipse.xtext.ide.server.commands.IExecutableCommandService; +import org.eclipse.xtext.parser.IEncodingProvider; +import org.eclipse.xtext.resource.IContainer; +import org.eclipse.xtext.resource.IResourceDescription; +import org.eclipse.xtext.resource.IResourceServiceProvider; +import org.eclipse.xtext.util.CancelIndicator; +import org.eclipse.xtext.util.IDisposable; +import org.eclipse.xtext.validation.IResourceValidator; +import org.eclipse.xtext.xbase.lib.Functions.Function1; +import org.junit.Assert; +import org.junit.Test; + +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +/** + * @author Sven Efftinge - Initial contribution and API + */ +public class CommandRegistryTest implements IResourceServiceProvider, IExecutableCommandService, LanguageClient { + private Function1 register; + + private Set commandsExecuted = new HashSet<>(); + + private Map registered = new HashMap<>(); + + @Test + public void testRegistration() { + ExecutableCommandRegistry reg = new ExecutableCommandRegistry(); + ClientCapabilities cap = new ClientCapabilities(); + WorkspaceClientCapabilities workspaceClientCapabilities = new WorkspaceClientCapabilities(); + ExecuteCommandCapabilities executeCommandCapabilities = new ExecuteCommandCapabilities(); + executeCommandCapabilities.setDynamicRegistration(true); + workspaceClientCapabilities.setExecuteCommand(executeCommandCapabilities); + cap.setWorkspace(workspaceClientCapabilities); + + reg.initialize(Collections.unmodifiableList(Lists.newArrayList(this)), cap, this); + Assert.assertEquals("static-command", Iterables.getFirst(reg.getCommands(), null)); + ExecuteCommandParams staticCommandParams = new ExecuteCommandParams(); + staticCommandParams.setCommand("static-command"); + reg.executeCommand(staticCommandParams, null, null); + + ExecuteCommandParams dynamicCommandParams = new ExecuteCommandParams(); + dynamicCommandParams.setCommand("dynamic-command"); + reg.executeCommand(dynamicCommandParams, null, null); + Assert.assertEquals(Collections.unmodifiableSet(Sets.newHashSet("static-command")), commandsExecuted); + commandsExecuted.clear(); + IDisposable disposable = register.apply("dynamic-command"); + + ExecuteCommandParams dynamicCommandParams2 = new ExecuteCommandParams(); + dynamicCommandParams2.setCommand("dynamic-command"); + reg.executeCommand(dynamicCommandParams2, null, null); + Assert.assertEquals(Collections.unmodifiableSet(Sets.newHashSet("dynamic-command")), commandsExecuted); + commandsExecuted.clear(); + disposable.dispose(); + + ExecuteCommandParams dynamicCommandParams3 = new ExecuteCommandParams(); + dynamicCommandParams3.setCommand("dynamic-command"); + reg.executeCommand(dynamicCommandParams3, null, null); + Assert.assertEquals(Collections.unmodifiableSet(new HashSet<>()), commandsExecuted); + } + + @Override + public List initialize() { + return Collections.unmodifiableList(Lists.newArrayList("static-command")); + } + + @Override + public void initializeDynamicRegistration(Function1 register) { + this.register = register; + } + + @Override + public Object execute(ExecuteCommandParams params, ILanguageServerAccess access, CancelIndicator cancelIndicator) { + return Boolean.valueOf(commandsExecuted.add(params.getCommand())); + } + + @Delegate + private IResourceServiceProvider noImpl; + + @SuppressWarnings("unchecked") + @Override + public T get(Class t) { + return ((T) this); + } + + @Delegate + private LanguageClient noImpl3; + + @Override + public CompletableFuture registerCapability(RegistrationParams params) { + Registration reg = Iterables.getFirst(params.getRegistrations(), null); + registered.put(reg.getId(), reg); + return CompletableFuture.completedFuture(null); + } + + @Override + public CompletableFuture unregisterCapability(UnregistrationParams params) { + Unregistration unreg = Iterables.getFirst(params.getUnregisterations(), null); + registered.remove(unreg.getId()); + return CompletableFuture.completedFuture(null); + } + + public boolean canHandle(URI uri) { + return noImpl.canHandle(uri); + } + + public IContainer.Manager getContainerManager() { + return noImpl.getContainerManager(); + } + + public IEncodingProvider getEncodingProvider() { + return noImpl.getEncodingProvider(); + } + + public IResourceDescription.Manager getResourceDescriptionManager() { + return noImpl.getResourceDescriptionManager(); + } + + public IResourceValidator getResourceValidator() { + return noImpl.getResourceValidator(); + } + + public CompletableFuture applyEdit(ApplyWorkspaceEditParams params) { + return noImpl3.applyEdit(params); + } + + public CompletableFuture> configuration(ConfigurationParams configurationParams) { + return noImpl3.configuration(configurationParams); + } + + public void logMessage(MessageParams message) { + noImpl3.logMessage(message); + } + + public void publishDiagnostics(PublishDiagnosticsParams diagnostics) { + noImpl3.publishDiagnostics(diagnostics); + } + + public void semanticHighlighting(SemanticHighlightingParams params) { + noImpl3.semanticHighlighting(params); + } + + public void showMessage(MessageParams messageParams) { + noImpl3.showMessage(messageParams); + } + + public CompletableFuture showMessageRequest(ShowMessageRequestParams requestParams) { + return noImpl3.showMessageRequest(requestParams); + } + + public void telemetryEvent(Object object) { + noImpl3.telemetryEvent(object); + } + + public CompletableFuture> workspaceFolders() { + return noImpl3.workspaceFolders(); + } +} diff --git a/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/commands/CommandRegistryTest.xtend b/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/commands/CommandRegistryTest.xtend deleted file mode 100644 index 191506bf8..000000000 --- a/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/commands/CommandRegistryTest.xtend +++ /dev/null @@ -1,110 +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.commands - -import java.util.Map -import java.util.Set -import java.util.concurrent.CompletableFuture -import org.eclipse.lsp4j.ClientCapabilities -import org.eclipse.lsp4j.ExecuteCommandCapabilities -import org.eclipse.lsp4j.ExecuteCommandParams -import org.eclipse.lsp4j.Registration -import org.eclipse.lsp4j.RegistrationParams -import org.eclipse.lsp4j.UnregistrationParams -import org.eclipse.lsp4j.WorkspaceClientCapabilities -import org.eclipse.lsp4j.services.LanguageClient -import org.eclipse.xtend.lib.annotations.Delegate -import org.eclipse.xtext.ide.server.ILanguageServerAccess -import org.eclipse.xtext.resource.IResourceServiceProvider -import org.eclipse.xtext.util.CancelIndicator -import org.eclipse.xtext.util.IDisposable -import org.junit.Assert -import org.junit.Test -import org.eclipse.xtext.ide.server.commands.IExecutableCommandService -import org.eclipse.xtext.ide.server.commands.ExecutableCommandRegistry - -/** - * @author Sven Efftinge - Initial contribution and API - */ -class CommandRegistryTest implements IResourceServiceProvider, IExecutableCommandService, LanguageClient { - - (String)=>IDisposable register - Set commandsExecuted = newHashSet - Map registered = newHashMap - - @Test def void testRegistration() { - val reg = new ExecutableCommandRegistry() - val cap = new ClientCapabilities => [ - workspace = new WorkspaceClientCapabilities => [ - executeCommand = new ExecuteCommandCapabilities => [ - dynamicRegistration = true - ] - ] - ] - reg.initialize(#[this], cap, this) - - Assert.assertEquals('static-command', reg.commands.head) - - // should be executed - reg.executeCommand(new ExecuteCommandParams => [ command = 'static-command' ], null, null) - - // should NOT be executed - reg.executeCommand(new ExecuteCommandParams => [ command = 'dynamic-command' ], null, null) - - Assert.assertEquals(#{'static-command'}, this.commandsExecuted) - this.commandsExecuted.clear - - val disposable = register.apply('dynamic-command') - - // should be executed - reg.executeCommand(new ExecuteCommandParams => [ command = 'dynamic-command' ], null, null) - - Assert.assertEquals(#{'dynamic-command'}, this.commandsExecuted) - this.commandsExecuted.clear - - // unregister - disposable.dispose - // should NOT be executed - reg.executeCommand(new ExecuteCommandParams => [ command = 'dynamic-command' ], null, null) - Assert.assertEquals(#{}, this.commandsExecuted) - } - - override initialize() { - #['static-command'] - } - - override initializeDynamicRegistration((String)=>IDisposable register) { - this.register = register - } - - override execute(ExecuteCommandParams params, ILanguageServerAccess access, CancelIndicator cancelIndicator) { - this.commandsExecuted.add(params.command) - } - - @Delegate IResourceServiceProvider noImpl - - override get(Class t) { - return this as T - } - - @Delegate LanguageClient noImpl3 - - override registerCapability(RegistrationParams params) { - val reg = params.registrations.head - registered.put(reg.id, reg) - return CompletableFuture.completedFuture(null) - } - - override unregisterCapability(UnregistrationParams params) { - val unreg = params.unregisterations.head - registered.remove(unreg) - return CompletableFuture.completedFuture(null) - } - -} diff --git a/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/importHandling/ImportTestHelper.java b/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/importHandling/ImportTestHelper.java new file mode 100644 index 000000000..2dfc0873a --- /dev/null +++ b/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/importHandling/ImportTestHelper.java @@ -0,0 +1,122 @@ +/** + * 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.importHandling; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.emf.ecore.resource.ResourceSet; +import org.eclipse.emf.ecore.util.EcoreUtil; +import org.eclipse.xtext.formatting2.debug.TextRegionAccessToString; +import org.eclipse.xtext.formatting2.regionaccess.ITextRegionAccess; +import org.eclipse.xtext.ide.serializer.IChangeSerializer; +import org.eclipse.xtext.ide.serializer.IEmfResourceChange; +import org.eclipse.xtext.ide.serializer.debug.TextDocumentChangeToString; +import org.eclipse.xtext.ide.serializer.impl.TextDocumentChange; +import org.eclipse.xtext.resource.IResourceDescription; +import org.eclipse.xtext.resource.XtextResource; +import org.eclipse.xtext.resource.XtextResourceSet; +import org.eclipse.xtext.resource.impl.ChunkedResourceDescriptions; +import org.eclipse.xtext.resource.impl.ResourceDescriptionsData; +import org.eclipse.xtext.resource.impl.ResourceDescriptionsProvider; +import org.eclipse.xtext.testing.util.InMemoryURIHandler; +import org.eclipse.xtext.testing.validation.ValidationTestHelper; +import org.eclipse.xtext.util.CollectionBasedAcceptor; +import org.eclipse.xtext.util.Strings; +import org.eclipse.xtext.xbase.lib.Pair; +import org.junit.Assert; + +import com.google.common.base.Preconditions; +import com.google.common.collect.Iterables; +import com.google.inject.Inject; + +/** + * TODO: de-duplicate with + * /xtext-core/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/serializer/ChangeSerializerTestHelper.xtend + * + * @author Moritz Eysholdt - Initial contribution and API + */ +public class ImportTestHelper { + @Inject + private IResourceDescription.Manager rdManager; + + @Inject + private ValidationTestHelper validator; + + public void operator_tripleEquals(Collection actual, CharSequence expected) { + String actualString = new TextDocumentChangeToString().add(actual).toString(); + Assert.assertEquals(Strings.toPlatformLineSeparator(expected).trim(), + Strings.toPlatformLineSeparator(actualString).trim()); + } + + public void operator_tripleEquals(ITextRegionAccess actual, CharSequence expected) { + String actualString = new TextRegionAccessToString().withRegionAccess(actual).hideColumnExplanation() + .toString(); + Assert.assertEquals(expected.toString().trim(), actualString.trim()); + } + + public void operator_add(InMemoryURIHandler handler, Pair file) { + InMemoryURIHandler.InMemFile f = handler.getInMemoryFile(URI.createURI(file.getKey())); + f.setContents(Strings.toUnixLineSeparator(file.getValue()).getBytes()); + f.setExists(true); + } + + public ResourceSet createResourceSet(InMemoryURIHandler fs) { + XtextResourceSet idx = new XtextResourceSet(); + idx.getURIConverter().getURIHandlers().add(0, fs); + for (InMemoryURIHandler.InMemFile f : fs.getFiles().values()) { + idx.getResource(f.getUri(), true); + } + EcoreUtil.resolveAll(idx); + for (Resource r : idx.getResources()) { + if (r instanceof XtextResource) { + validator.assertNoErrors(r); + } + } + List rsd = new ArrayList<>(); + for (Resource r : idx.getResources()) { + rsd.add(rdManager.getResourceDescription(r)); + } + ResourceDescriptionsData data = new ResourceDescriptionsData(rsd); + XtextResourceSet r = new XtextResourceSet(); + r.getLoadOptions().put(ResourceDescriptionsProvider.LIVE_SCOPE, Boolean.TRUE); + r.getURIConverter().getURIHandlers().add(0, fs); + ResourceDescriptionsData.ResourceSetAdapter.installResourceDescriptionsData(r, data); + Map dataMap = new HashMap<>(); + dataMap.put("egal", data); + + new ChunkedResourceDescriptions(Collections.unmodifiableMap(dataMap), r); + return r; + } + + public T contents(ResourceSet rs, String fileName, Class type) { + T result = Iterables + .getFirst(Iterables.filter(rs.getResource(URI.createURI(fileName), true).getContents(), type), null); + Preconditions.checkNotNull(result); + return result; + } + + public ITextRegionAccess endRecordChangesToTextRegions(IChangeSerializer ser) { + return Iterables + .getFirst(Iterables.filter(endRecordChangesToTextDocuments(ser), TextDocumentChange.class), null) + .getTextRegionAccess(); + } + + public Collection endRecordChangesToTextDocuments(IChangeSerializer ser) { + ArrayList list = new ArrayList<>(); + ser.applyModifications(CollectionBasedAcceptor.of(list)); + return list; + } +} diff --git a/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/importHandling/ImportTestHelper.xtend b/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/importHandling/ImportTestHelper.xtend deleted file mode 100644 index 602329ff7..000000000 --- a/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/importHandling/ImportTestHelper.xtend +++ /dev/null @@ -1,95 +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.importHandling - -import com.google.common.base.Preconditions -import com.google.inject.Inject -import java.util.Collection -import org.eclipse.emf.common.util.URI -import org.eclipse.emf.ecore.resource.ResourceSet -import org.eclipse.emf.ecore.util.EcoreUtil -import org.eclipse.xtext.formatting2.debug.TextRegionAccessToString -import org.eclipse.xtext.formatting2.regionaccess.ITextRegionAccess -import org.eclipse.xtext.ide.serializer.IChangeSerializer -import org.eclipse.xtext.ide.serializer.IEmfResourceChange -import org.eclipse.xtext.ide.serializer.debug.TextDocumentChangeToString -import org.eclipse.xtext.ide.serializer.impl.TextDocumentChange -import org.eclipse.xtext.resource.IResourceDescription -import org.eclipse.xtext.resource.XtextResource -import org.eclipse.xtext.resource.XtextResourceSet -import org.eclipse.xtext.resource.impl.ChunkedResourceDescriptions -import org.eclipse.xtext.resource.impl.ResourceDescriptionsData -import org.eclipse.xtext.resource.impl.ResourceDescriptionsProvider -import org.eclipse.xtext.testing.util.InMemoryURIHandler -import org.eclipse.xtext.testing.validation.ValidationTestHelper -import org.eclipse.xtext.util.CollectionBasedAcceptor -import org.junit.Assert - -import static extension org.eclipse.xtext.util.Strings.* - -/** - * TODO: de-duplicate with /xtext-core/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/serializer/ChangeSerializerTestHelper.xtend - * - * @author Moritz Eysholdt - Initial contribution and API - */ -class ImportTestHelper { - @Inject IResourceDescription.Manager rdManager - @Inject ValidationTestHelper validator - - def void ===(Collection actual, CharSequence expected) { - val actualString = new TextDocumentChangeToString().add(actual).toString - Assert.assertEquals(expected.toPlatformLineSeparator.trim, actualString.toPlatformLineSeparator.trim) - } - - def void ===(ITextRegionAccess actual, CharSequence expected) { - val actualString = new TextRegionAccessToString().withRegionAccess(actual).hideColumnExplanation().toString - Assert.assertEquals(expected.toString.trim, actualString.trim) - } - - def void +=(InMemoryURIHandler handler, Pair file) { - val f = handler.getInMemoryFile(URI.createURI(file.key)) - f.contents = file.value.toUnixLineSeparator.bytes - f.exists = true - } - - def ResourceSet createResourceSet(InMemoryURIHandler fs) { - val idx = new XtextResourceSet - idx.getURIConverter.getURIHandlers.add(0, fs) - for (f : fs.files.values) { - idx.getResource(f.uri, true) - } - EcoreUtil.resolveAll(idx) - idx.resources.filter(XtextResource).forEach[validator.assertNoErrors(it)] - val rsd = idx.resources.map[rdManager.getResourceDescription(it)] - val data = new ResourceDescriptionsData(rsd) - - val r = new XtextResourceSet - r.getLoadOptions().put(ResourceDescriptionsProvider.LIVE_SCOPE, Boolean.TRUE); - r.getURIConverter.getURIHandlers.add(0, fs) - ResourceDescriptionsData.ResourceSetAdapter.installResourceDescriptionsData(r, data) - new ChunkedResourceDescriptions(#{"egal"->data}, r) - return r; - } - - def T contents(ResourceSet rs, String fileName, Class type) { - val result = rs.getResource(URI.createURI(fileName), true).contents.filter(type).head - Preconditions.checkNotNull(result) - return result - } - - def ITextRegionAccess endRecordChangesToTextRegions(IChangeSerializer ser) { - return ser.endRecordChangesToTextDocuments.filter(TextDocumentChange).head.textRegionAccess - } - - def Collection endRecordChangesToTextDocuments(IChangeSerializer ser) { - val list = newArrayList() - ser.applyModifications(CollectionBasedAcceptor.of(list)) - return list - } -} diff --git a/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/serializer/ChangeSerializerTestHelper.java b/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/serializer/ChangeSerializerTestHelper.java new file mode 100644 index 000000000..9da92f5f2 --- /dev/null +++ b/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/serializer/ChangeSerializerTestHelper.java @@ -0,0 +1,118 @@ +/** + * 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.serializer; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.emf.ecore.resource.ResourceSet; +import org.eclipse.emf.ecore.util.EcoreUtil; +import org.eclipse.xtext.formatting2.debug.TextRegionAccessToString; +import org.eclipse.xtext.formatting2.regionaccess.ITextRegionAccess; +import org.eclipse.xtext.ide.serializer.IChangeSerializer; +import org.eclipse.xtext.ide.serializer.IEmfResourceChange; +import org.eclipse.xtext.ide.serializer.debug.TextDocumentChangeToString; +import org.eclipse.xtext.ide.serializer.impl.ChangeSerializer; +import org.eclipse.xtext.ide.serializer.impl.TextDocumentChange; +import org.eclipse.xtext.resource.IResourceDescription; +import org.eclipse.xtext.resource.XtextResource; +import org.eclipse.xtext.resource.XtextResourceSet; +import org.eclipse.xtext.resource.impl.ResourceDescriptionsData; +import org.eclipse.xtext.resource.impl.ResourceDescriptionsProvider; +import org.eclipse.xtext.testing.util.InMemoryURIHandler; +import org.eclipse.xtext.testing.validation.ValidationTestHelper; +import org.eclipse.xtext.util.CollectionBasedAcceptor; +import org.eclipse.xtext.util.Strings; +import org.eclipse.xtext.xbase.lib.Pair; +import org.junit.Assert; + +import com.google.common.base.Preconditions; +import com.google.common.collect.Iterables; +import com.google.inject.Guice; +import com.google.inject.Inject; + +/** + * @author Moritz Eysholdt - Initial contribution and API + */ +public class ChangeSerializerTestHelper { + @Inject + private IResourceDescription.Manager rdManager; + + @Inject + private ValidationTestHelper validator; + + public void operator_tripleEquals(Collection actual, CharSequence expected) { + String actualString = new TextDocumentChangeToString().add(actual).toString(); + Assert.assertEquals(Strings.toPlatformLineSeparator(expected).trim(), + Strings.toPlatformLineSeparator(actualString).trim()); + } + + public void operator_tripleEquals(ITextRegionAccess actual, CharSequence expected) { + String actualString = new TextRegionAccessToString().withRegionAccess(actual).hideColumnExplanation() + .toString(); + Assert.assertEquals(Strings.toPlatformLineSeparator(expected).trim(), + Strings.toPlatformLineSeparator(actualString).trim()); + } + + public void operator_add(InMemoryURIHandler handler, Pair file) { + InMemoryURIHandler.InMemFile f = handler.getInMemoryFile(URI.createURI(file.getKey())); + f.setContents(Strings.toUnixLineSeparator(file.getValue()).getBytes()); + f.setExists(true); + } + + public ResourceSet createResourceSet(InMemoryURIHandler fs) { + XtextResourceSet idx = new XtextResourceSet(); + idx.getURIConverter().getURIHandlers().add(0, fs); + for (InMemoryURIHandler.InMemFile f : fs.getFiles().values()) { + idx.getResource(f.getUri(), true); + } + EcoreUtil.resolveAll(idx); + for (Resource r : idx.getResources()) { + if (r instanceof XtextResource) { + validator.assertNoErrors(r); + } + } + List rsd = new ArrayList<>(); + for (Resource r : idx.getResources()) { + rsd.add(rdManager.getResourceDescription(r)); + } + ResourceDescriptionsData data = new ResourceDescriptionsData(rsd); + XtextResourceSet r = new XtextResourceSet(); + r.getLoadOptions().put(ResourceDescriptionsProvider.LIVE_SCOPE, Boolean.TRUE); + r.getURIConverter().getURIHandlers().add(0, fs); + ResourceDescriptionsData.ResourceSetAdapter.installResourceDescriptionsData(r, data); + return r; + } + + public T contents(ResourceSet rs, String fileName, Class type) { + T result = Iterables + .getFirst(Iterables.filter(rs.getResource(URI.createURI(fileName), true).getContents(), type), null); + Preconditions.checkNotNull(result); + return result; + } + + public ITextRegionAccess endRecordChangesToTextRegions(IChangeSerializer ser) { + return Iterables + .getFirst(Iterables.filter(endRecordChangesToTextDocuments(ser), TextDocumentChange.class), null) + .getTextRegionAccess(); + } + + public Collection endRecordChangesToTextDocuments(IChangeSerializer ser) { + ArrayList list = new ArrayList<>(); + ser.applyModifications(CollectionBasedAcceptor.of(list)); + return list; + } + + public IChangeSerializer newChangeSerializer() { + return Guice.createInjector().getInstance(ChangeSerializer.class); + } +} diff --git a/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/serializer/ChangeSerializerTestHelper.xtend b/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/serializer/ChangeSerializerTestHelper.xtend deleted file mode 100644 index c5fba87fe..000000000 --- a/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/serializer/ChangeSerializerTestHelper.xtend +++ /dev/null @@ -1,97 +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.serializer - -import com.google.common.base.Preconditions - -import com.google.inject.Inject -import java.util.Collection -import org.eclipse.emf.common.util.URI -import org.eclipse.emf.ecore.resource.ResourceSet -import org.eclipse.emf.ecore.util.EcoreUtil -import org.eclipse.xtext.formatting2.debug.TextRegionAccessToString -import org.eclipse.xtext.formatting2.regionaccess.ITextRegionAccess -import org.eclipse.xtext.ide.serializer.IChangeSerializer -import org.eclipse.xtext.ide.serializer.IEmfResourceChange -import org.eclipse.xtext.ide.serializer.debug.TextDocumentChangeToString -import org.eclipse.xtext.ide.serializer.impl.ChangeSerializer -import org.eclipse.xtext.ide.serializer.impl.TextDocumentChange -import org.eclipse.xtext.resource.IResourceDescription -import org.eclipse.xtext.resource.XtextResource -import org.eclipse.xtext.resource.XtextResourceSet -import org.eclipse.xtext.resource.impl.ResourceDescriptionsData -import org.eclipse.xtext.resource.impl.ResourceDescriptionsProvider -import org.eclipse.xtext.testing.util.InMemoryURIHandler -import org.eclipse.xtext.testing.validation.ValidationTestHelper -import org.eclipse.xtext.util.CollectionBasedAcceptor -import org.junit.Assert -import com.google.inject.Guice -import static extension org.eclipse.xtext.util.Strings.* - -/** - * @author Moritz Eysholdt - Initial contribution and API - */ -class ChangeSerializerTestHelper { - @Inject IResourceDescription.Manager rdManager - @Inject ValidationTestHelper validator - - def void ===(Collection actual, CharSequence expected) { - val actualString = new TextDocumentChangeToString().add(actual).toString - Assert.assertEquals(expected.toPlatformLineSeparator.trim, actualString.toPlatformLineSeparator.trim) - } - - def void ===(ITextRegionAccess actual, CharSequence expected) { - val actualString = new TextRegionAccessToString().withRegionAccess(actual).hideColumnExplanation().toString - Assert.assertEquals(expected.toPlatformLineSeparator.trim, actualString.toPlatformLineSeparator.trim) - } - - def void +=(InMemoryURIHandler handler, Pair file) { - val f = handler.getInMemoryFile(URI.createURI(file.key)) - f.contents = file.value.toUnixLineSeparator.bytes - f.exists = true - } - - def ResourceSet createResourceSet(InMemoryURIHandler fs) { - val idx = new XtextResourceSet - idx.URIConverter.URIHandlers.add(0, fs) - for (f : fs.files.values) { - idx.getResource(f.uri, true) - } - EcoreUtil.resolveAll(idx) - idx.resources.filter(XtextResource).forEach[validator.assertNoErrors(it)] - val rsd = idx.resources.map[rdManager.getResourceDescription(it)] - val data = new ResourceDescriptionsData(rsd) - - val r = new XtextResourceSet - r.getLoadOptions().put(ResourceDescriptionsProvider.LIVE_SCOPE, Boolean.TRUE); - r.URIConverter.URIHandlers.add(0, fs) - ResourceDescriptionsData.ResourceSetAdapter.installResourceDescriptionsData(r, data) - return r; - } - - def T contents(ResourceSet rs, String fileName, Class type) { - val result = rs.getResource(URI.createURI(fileName), true).contents.filter(type).head - Preconditions.checkNotNull(result) - return result - } - - def ITextRegionAccess endRecordChangesToTextRegions(IChangeSerializer ser) { - return ser.endRecordChangesToTextDocuments.filter(TextDocumentChange).head.textRegionAccess - } - - def Collection endRecordChangesToTextDocuments(IChangeSerializer ser) { - val list = newArrayList() - ser.applyModifications(CollectionBasedAcceptor.of(list)) - return list - } - - def IChangeSerializer newChangeSerializer() { - Guice.createInjector().getInstance(ChangeSerializer) - } -} diff --git a/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/server/SourceFolderCustomImplTest.java b/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/server/SourceFolderCustomImplTest.java new file mode 100644 index 000000000..bcda89fad --- /dev/null +++ b/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/server/SourceFolderCustomImplTest.java @@ -0,0 +1,131 @@ +/** + * Copyright (c) 2019, 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.server; + +import java.util.List; +import java.util.Set; + +import org.eclipse.emf.common.util.URI; +import org.eclipse.lsp4j.WorkspaceFolder; +import org.eclipse.xtext.ide.server.IMultiRootWorkspaceConfigFactory; +import org.eclipse.xtext.ide.server.MultiRootWorkspaceConfigFactory; +import org.eclipse.xtext.ide.server.ProjectManager; +import org.eclipse.xtext.ide.server.WorkspaceManager; +import org.eclipse.xtext.util.IFileSystemScanner; +import org.eclipse.xtext.util.Modules2; +import org.eclipse.xtext.workspace.FileProjectConfig; +import org.eclipse.xtext.workspace.FileSourceFolder; +import org.eclipse.xtext.workspace.ISourceFolder; +import org.eclipse.xtext.workspace.WorkspaceConfig; +import org.junit.Assert; +import org.junit.Test; + +import com.google.inject.AbstractModule; +import com.google.inject.Inject; +import com.google.inject.Scopes; + +/** + * Tests customized version of default methods ISourceFolder#contains(URI) and + * ISourceFolder#getAllResources(IFileSystemScanner) + */ +public class SourceFolderCustomImplTest extends AbstractTestLangLanguageServerTest { + public static class CustomWorkspaceConfigFactory extends MultiRootWorkspaceConfigFactory { + @Override + public void addProjectsForWorkspaceFolder(WorkspaceConfig workspaceConfig, WorkspaceFolder workspaceFolder, + Set existingNames) { + if (workspaceFolder != null) { + if (workspaceFolder.getUri() != null) { + SourceFolderCustomImplTest.CustomFileProjectConfig project = new SourceFolderCustomImplTest.CustomFileProjectConfig( + getUriExtensions().toUri(workspaceFolder.getUri()), workspaceConfig); + project.addSourceFolder("."); + workspaceConfig.addProject(project); + } + } + } + } + + public static class CustomFileProjectConfig extends FileProjectConfig { + public CustomFileProjectConfig(URI uri, WorkspaceConfig workspaceConfig) { + super(uri, workspaceConfig); + } + + @Override + public FileSourceFolder addSourceFolder(String relativePath) { + SourceFolderCustomImplTest.CustomFileSourceFolder sourceFolder = new SourceFolderCustomImplTest.CustomFileSourceFolder( + this, relativePath); + getSourceFolders().add(sourceFolder); + return sourceFolder; + } + } + + public static class CustomFileSourceFolder extends FileSourceFolder { + public CustomFileSourceFolder(FileProjectConfig parent, String name) { + super(parent, name); + } + + public boolean filterTheFile(URI uri) { + return uri.toFileString().endsWith("sample.testlang"); + } + + @Override + public boolean contains(URI uri) { + if (filterTheFile(uri)) { + return false; + } + return super.contains(uri); + } + + @Override + public List getAllResources(IFileSystemScanner scanner) { + List allResources = super.getAllResources(scanner); + allResources.removeIf((URI uri) -> filterTheFile(uri)); + return allResources; + } + } + + @Inject + private WorkspaceManager workspaceManager; + + @Inject + private IFileSystemScanner scanner; + + /** + * Asserts that the custom implementation returns not all files of the + * configured source folder + */ + @Test + public void testCustomSourceFolderImplementation() { + writeFile("sample.testlang", "MyContent"); + initialize(); + ProjectManager projectManager = workspaceManager.getProjectManager(""); + Set sourceFolders = projectManager.getProjectConfig().getSourceFolders(); + Assert.assertTrue(sourceFolders.size() == 1); + ISourceFolder sourceFolder = sourceFolders.iterator().next(); + List allResources = sourceFolder.getAllResources(scanner); + Assert.assertTrue( + allResources.stream().anyMatch((URI uri) -> uri.toString().endsWith("test-data/test-project/"))); + Assert.assertFalse(allResources.stream() + .anyMatch((URI uri) -> uri.toString().endsWith("test-data/test-project/sample.testlang"))); + Assert.assertEquals(allResources.size(), 1); + } + + @Override + protected com.google.inject.Module getServerModule() { + com.google.inject.Module defaultModule = super.getServerModule(); + com.google.inject.Module customModule = new AbstractModule() { + @Override + protected void configure() { + bind(IMultiRootWorkspaceConfigFactory.class) + .to(SourceFolderCustomImplTest.CustomWorkspaceConfigFactory.class); + bind(WorkspaceManager.class).in(Scopes.SINGLETON); + } + }; + return Modules2.mixin(defaultModule, customModule); + } +} diff --git a/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/server/SourceFolderCustomImplTest.xtend b/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/server/SourceFolderCustomImplTest.xtend deleted file mode 100644 index 1c2985e73..000000000 --- a/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/server/SourceFolderCustomImplTest.xtend +++ /dev/null @@ -1,119 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019 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.server - -import com.google.inject.AbstractModule -import com.google.inject.Inject -import com.google.inject.Module -import com.google.inject.Scopes -import java.util.Set -import org.eclipse.emf.common.util.URI -import org.eclipse.lsp4j.WorkspaceFolder -import org.eclipse.xtext.ide.server.IMultiRootWorkspaceConfigFactory -import org.eclipse.xtext.ide.server.MultiRootWorkspaceConfigFactory -import org.eclipse.xtext.ide.server.WorkspaceManager -import org.eclipse.xtext.util.IFileSystemScanner -import org.eclipse.xtext.util.Modules2 -import org.eclipse.xtext.workspace.FileProjectConfig -import org.eclipse.xtext.workspace.FileSourceFolder -import org.eclipse.xtext.workspace.WorkspaceConfig -import org.junit.Test - -import static org.junit.Assert.* - -/** - * Tests customized version of default methods ISourceFolder#contains(URI) and ISourceFolder#getAllResources(IFileSystemScanner) - */ -class SourceFolderCustomImplTest extends AbstractTestLangLanguageServerTest { - @Inject - WorkspaceManager workspaceManager; - @Inject - IFileSystemScanner scanner; - - - /** Asserts that the custom implementation returns not all files of the configured source folder */ - @Test - def void testCustomSourceFolderImplementation() { - 'sample.testlang'.writeFile("MyContent") - initialize - - val projectManager = workspaceManager.getProjectManager("") - val sourceFolders = projectManager.projectConfig.sourceFolders - - assertTrue(sourceFolders.size == 1); - val sourceFolder = sourceFolders.get(0); - val allResources = sourceFolder.getAllResources(scanner); - - assertTrue(allResources.exists[uri|uri.toString.endsWith("test-data/test-project/")]); - assertFalse(allResources.exists[uri|uri.toString.endsWith("test-data/test-project/sample.testlang")]); - assertEquals(allResources.size, 1); - } - - static class CustomWorkspaceConfigFactory extends MultiRootWorkspaceConfigFactory { - override addProjectsForWorkspaceFolder(WorkspaceConfig workspaceConfig, WorkspaceFolder workspaceFolder, Set existingNames) { - if (workspaceFolder?.uri !== null) { - val project = new CustomFileProjectConfig(uriExtensions.toUri(workspaceFolder.uri), workspaceConfig) - project.addSourceFolder("."); - workspaceConfig.addProject(project); - } - } - } - - static class CustomFileProjectConfig extends FileProjectConfig { - - new(URI uri, WorkspaceConfig workspaceConfig) { - super(uri, workspaceConfig) - } - - override FileSourceFolder addSourceFolder(String relativePath) { - val sourceFolder = new CustomFileSourceFolder(this, relativePath) - sourceFolders += sourceFolder - sourceFolder - } - } - - static class CustomFileSourceFolder extends FileSourceFolder { - - new(FileProjectConfig parent, String name) { - super(parent, name) - } - - def boolean filterTheFile(URI uri) { - return uri.toFileString.endsWith("sample.testlang"); - } - - override contains(URI uri) { - if (filterTheFile(uri)) { - return false; - } - super.contains(uri) - } - - override getAllResources(IFileSystemScanner scanner) { - val allResources = super.getAllResources(scanner); - allResources.removeIf(uri| filterTheFile(uri)); - return allResources; - } - } - - - override protected getServerModule() { - val defaultModule = super.getServerModule() - val Module customModule = new AbstractModule() { - - override protected configure() { - bind(IMultiRootWorkspaceConfigFactory).to(CustomWorkspaceConfigFactory) - bind(WorkspaceManager).in(Scopes.SINGLETON); - } - - } - - return Modules2.mixin(defaultModule, customModule) - } -} diff --git a/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/server/SourceFolderDefaultImplTest.java b/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/server/SourceFolderDefaultImplTest.java new file mode 100644 index 000000000..400ccc1a8 --- /dev/null +++ b/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/server/SourceFolderDefaultImplTest.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) 2019, 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.server; + +import java.util.List; +import java.util.Set; + +import org.eclipse.emf.common.util.URI; +import org.eclipse.xtext.ide.server.ProjectManager; +import org.eclipse.xtext.ide.server.WorkspaceManager; +import org.eclipse.xtext.util.IFileSystemScanner; +import org.eclipse.xtext.util.Modules2; +import org.eclipse.xtext.workspace.ISourceFolder; +import org.junit.Assert; +import org.junit.Test; + +import com.google.inject.AbstractModule; +import com.google.inject.Inject; +import com.google.inject.Scopes; + +/** + * Tests default methods ISourceFolder#contains(URI) and + * ISourceFolder#getAllResources(IFileSystemScanner) + */ +public class SourceFolderDefaultImplTest extends AbstractTestLangLanguageServerTest { + @Inject + private WorkspaceManager workspaceManager; + + @Inject + private IFileSystemScanner scanner; + + /** + * Asserts that the default implementation returns all files in the + * configured source folder + */ + @Test + public void testDefaultSourceFolderImplementation() { + this.writeFile("sample.testlang", "MyContent"); + this.initialize(); + ProjectManager projectManager = this.workspaceManager.getProjectManager(""); + Set sourceFolders = projectManager.getProjectConfig().getSourceFolders(); + Assert.assertTrue(sourceFolders.size() == 1); + ISourceFolder sourceFolder = sourceFolders.iterator().next(); + List allResources = sourceFolder.getAllResources(this.scanner); + Assert.assertTrue( + allResources.stream().anyMatch((URI uri) -> uri.toString().endsWith("test-data/test-project/"))); + Assert.assertTrue(allResources.stream() + .anyMatch((URI uri) -> uri.toString().endsWith("test-data/test-project/sample.testlang"))); + Assert.assertEquals(allResources.size(), 2); + } + + @Override + protected com.google.inject.Module getServerModule() { + com.google.inject.Module defaultModule = super.getServerModule(); + com.google.inject.Module customModule = new AbstractModule() { + @Override + protected void configure() { + bind(WorkspaceManager.class).in(Scopes.SINGLETON); + } + }; + return Modules2.mixin(defaultModule, customModule); + } +} diff --git a/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/server/SourceFolderDefaultImplTest.xtend b/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/server/SourceFolderDefaultImplTest.xtend deleted file mode 100644 index 59948ac42..000000000 --- a/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/server/SourceFolderDefaultImplTest.xtend +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019 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.server - -import com.google.inject.AbstractModule -import com.google.inject.Inject -import com.google.inject.Module -import com.google.inject.Scopes -import org.eclipse.xtext.ide.server.WorkspaceManager -import org.eclipse.xtext.util.IFileSystemScanner -import org.eclipse.xtext.util.Modules2 -import org.junit.Test - -import static org.junit.Assert.* - -/** - * Tests default methods ISourceFolder#contains(URI) and ISourceFolder#getAllResources(IFileSystemScanner) - */ -class SourceFolderDefaultImplTest extends AbstractTestLangLanguageServerTest { - @Inject - WorkspaceManager workspaceManager; - @Inject - IFileSystemScanner scanner; - - /** Asserts that the default implementation returns all files in the configured source folder */ - @Test - def void testDefaultSourceFolderImplementation() { - 'sample.testlang'.writeFile("MyContent") - initialize - - val projectManager = workspaceManager.getProjectManager("") - val sourceFolders = projectManager.projectConfig.sourceFolders - - assertTrue(sourceFolders.size == 1); - val sourceFolder = sourceFolders.get(0); - val allResources = sourceFolder.getAllResources(scanner); - - assertTrue(allResources.exists[uri|uri.toString.endsWith("test-data/test-project/")]); - assertTrue(allResources.exists[uri|uri.toString.endsWith("test-data/test-project/sample.testlang")]); - assertEquals(allResources.size, 2); - } - - - override protected getServerModule() { - val defaultModule = super.getServerModule() - val Module customModule = new AbstractModule() { - - override protected configure() { - bind(WorkspaceManager).in(Scopes.SINGLETON); - } - } - - return Modules2.mixin(defaultModule, customModule) - } - -} diff --git a/org.eclipse.xtext.ide.tests/testlang-src/org/eclipse/xtext/ide/tests/testlanguage/ide/TestLanguageIdeContentProposalProvider.xtend b/org.eclipse.xtext.ide.tests/testlang-src/org/eclipse/xtext/ide/tests/testlanguage/ide/TestLanguageIdeContentProposalProvider.xtend index 03c70f68a..3133c21b1 100644 --- a/org.eclipse.xtext.ide.tests/testlang-src/org/eclipse/xtext/ide/tests/testlanguage/ide/TestLanguageIdeContentProposalProvider.xtend +++ b/org.eclipse.xtext.ide.tests/testlang-src/org/eclipse/xtext/ide/tests/testlanguage/ide/TestLanguageIdeContentProposalProvider.xtend @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2018 itemis AG (http://www.itemis.eu) and others. + * 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. diff --git a/org.eclipse.xtext.ide.tests/testlang-src/org/eclipse/xtext/ide/tests/testlanguage/rename/TestLanguageRenameService.java b/org.eclipse.xtext.ide.tests/testlang-src/org/eclipse/xtext/ide/tests/testlanguage/rename/TestLanguageRenameService.java new file mode 100644 index 000000000..812a35363 --- /dev/null +++ b/org.eclipse.xtext.ide.tests/testlang-src/org/eclipse/xtext/ide/tests/testlanguage/rename/TestLanguageRenameService.java @@ -0,0 +1,59 @@ +/** + * Copyright (c) 2019, 2020 TypeFox 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.rename; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.xtext.ide.server.rename.RenameService2; +import org.eclipse.xtext.naming.IQualifiedNameProvider; +import org.eclipse.xtext.naming.QualifiedName; +import org.eclipse.xtext.nodemodel.ICompositeNode; +import org.eclipse.xtext.nodemodel.ILeafNode; +import org.eclipse.xtext.nodemodel.util.NodeModelUtils; +import org.eclipse.xtext.parser.IParseResult; +import org.eclipse.xtext.resource.EObjectAtOffsetHelper; +import org.eclipse.xtext.resource.XtextResource; + +import com.google.common.base.Objects; +import com.google.inject.Inject; + +public class TestLanguageRenameService extends RenameService2 { + @Inject + private EObjectAtOffsetHelper eObjectAtOffsetHelper; + + @Override + protected EObject getElementWithIdentifierAt(XtextResource xtextResource, int offset) { + if (offset >= 0) { + if (xtextResource != null) { + IParseResult parseResult = xtextResource.getParseResult(); + if (parseResult != null) { + ICompositeNode rootNode = parseResult.getRootNode(); + if (rootNode != null) { + ILeafNode leaf = NodeModelUtils.findLeafNodeAtOffset(rootNode, offset); + if (leaf != null && isIdentifier(leaf)) { + EObject element = eObjectAtOffsetHelper.resolveElementAt(xtextResource, offset); + if (element != null) { + IQualifiedNameProvider nameProvider = xtextResource.getResourceServiceProvider() + .get(IQualifiedNameProvider.class); + QualifiedName fqn = nameProvider.getFullyQualifiedName(element); + if (fqn != null) { + String leafText = NodeModelUtils.getTokenText(leaf); + if (fqn.getSegmentCount() == 1 && Objects.equal(fqn.toString(), leafText) + || Objects.equal(fqn.getLastSegment(), leafText)) { + return element; + } + } + } + } + } + } + } + } + return null; + } +} diff --git a/org.eclipse.xtext.ide.tests/testlang-src/org/eclipse/xtext/ide/tests/testlanguage/rename/TestLanguageRenameService.xtend b/org.eclipse.xtext.ide.tests/testlang-src/org/eclipse/xtext/ide/tests/testlanguage/rename/TestLanguageRenameService.xtend deleted file mode 100644 index c504a5114..000000000 --- a/org.eclipse.xtext.ide.tests/testlang-src/org/eclipse/xtext/ide/tests/testlanguage/rename/TestLanguageRenameService.xtend +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019 TypeFox 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.rename - -import com.google.inject.Inject -import org.eclipse.xtext.ide.server.rename.RenameService2 -import org.eclipse.xtext.naming.IQualifiedNameProvider -import org.eclipse.xtext.nodemodel.util.NodeModelUtils -import org.eclipse.xtext.resource.EObjectAtOffsetHelper -import org.eclipse.xtext.resource.XtextResource - -class TestLanguageRenameService extends RenameService2 { - - @Inject - extension EObjectAtOffsetHelper - - override protected getElementWithIdentifierAt(XtextResource xtextResource, int offset) { - if (offset >= 0) { - val rootNode = xtextResource?.parseResult?.rootNode - if (rootNode !== null) { - val leaf = NodeModelUtils.findLeafNodeAtOffset(rootNode, offset) - if (leaf !== null && leaf.isIdentifier) { - val element = xtextResource.resolveElementAt(offset) - if (element !== null) { - val nameProvider = xtextResource.resourceServiceProvider.get(IQualifiedNameProvider) - val fqn = nameProvider.getFullyQualifiedName(element) - if (fqn !== null) { - val leafText = NodeModelUtils.getTokenText(leaf) - if ((fqn.segmentCount === 1 && fqn.toString == leafText) || (fqn.lastSegment == leafText)) { - return element - } - } - } - } - } - } - return null - } - -} diff --git a/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/commands/CommandRegistryTest.java b/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/commands/CommandRegistryTest.java deleted file mode 100644 index fd5aa1328..000000000 --- a/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/commands/CommandRegistryTest.java +++ /dev/null @@ -1,213 +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.commands; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import org.eclipse.emf.common.util.URI; -import org.eclipse.lsp4j.ApplyWorkspaceEditParams; -import org.eclipse.lsp4j.ApplyWorkspaceEditResponse; -import org.eclipse.lsp4j.ClientCapabilities; -import org.eclipse.lsp4j.ConfigurationParams; -import org.eclipse.lsp4j.ExecuteCommandCapabilities; -import org.eclipse.lsp4j.ExecuteCommandParams; -import org.eclipse.lsp4j.MessageActionItem; -import org.eclipse.lsp4j.MessageParams; -import org.eclipse.lsp4j.PublishDiagnosticsParams; -import org.eclipse.lsp4j.Registration; -import org.eclipse.lsp4j.RegistrationParams; -import org.eclipse.lsp4j.SemanticHighlightingParams; -import org.eclipse.lsp4j.ShowMessageRequestParams; -import org.eclipse.lsp4j.Unregistration; -import org.eclipse.lsp4j.UnregistrationParams; -import org.eclipse.lsp4j.WorkspaceClientCapabilities; -import org.eclipse.lsp4j.WorkspaceFolder; -import org.eclipse.lsp4j.services.LanguageClient; -import org.eclipse.xtend.lib.annotations.Delegate; -import org.eclipse.xtext.ide.server.ILanguageServerAccess; -import org.eclipse.xtext.ide.server.commands.ExecutableCommandRegistry; -import org.eclipse.xtext.ide.server.commands.IExecutableCommandService; -import org.eclipse.xtext.parser.IEncodingProvider; -import org.eclipse.xtext.resource.IContainer; -import org.eclipse.xtext.resource.IResourceDescription; -import org.eclipse.xtext.resource.IResourceServiceProvider; -import org.eclipse.xtext.util.CancelIndicator; -import org.eclipse.xtext.util.IDisposable; -import org.eclipse.xtext.validation.IResourceValidator; -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.ObjectExtensions; -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 CommandRegistryTest implements IResourceServiceProvider, IExecutableCommandService, LanguageClient { - private Function1 register; - - private Set commandsExecuted = CollectionLiterals.newHashSet(); - - private Map registered = CollectionLiterals.newHashMap(); - - @Test - public void testRegistration() { - final ExecutableCommandRegistry reg = new ExecutableCommandRegistry(); - ClientCapabilities _clientCapabilities = new ClientCapabilities(); - final Procedure1 _function = (ClientCapabilities it) -> { - WorkspaceClientCapabilities _workspaceClientCapabilities = new WorkspaceClientCapabilities(); - final Procedure1 _function_1 = (WorkspaceClientCapabilities it_1) -> { - ExecuteCommandCapabilities _executeCommandCapabilities = new ExecuteCommandCapabilities(); - final Procedure1 _function_2 = (ExecuteCommandCapabilities it_2) -> { - it_2.setDynamicRegistration(Boolean.valueOf(true)); - }; - ExecuteCommandCapabilities _doubleArrow = ObjectExtensions.operator_doubleArrow(_executeCommandCapabilities, _function_2); - it_1.setExecuteCommand(_doubleArrow); - }; - WorkspaceClientCapabilities _doubleArrow = ObjectExtensions.operator_doubleArrow(_workspaceClientCapabilities, _function_1); - it.setWorkspace(_doubleArrow); - }; - final ClientCapabilities cap = ObjectExtensions.operator_doubleArrow(_clientCapabilities, _function); - reg.initialize(Collections.unmodifiableList(CollectionLiterals.newArrayList(this)), cap, this); - Assert.assertEquals("static-command", IterableExtensions.head(reg.getCommands())); - ExecuteCommandParams _executeCommandParams = new ExecuteCommandParams(); - final Procedure1 _function_1 = (ExecuteCommandParams it) -> { - it.setCommand("static-command"); - }; - ExecuteCommandParams _doubleArrow = ObjectExtensions.operator_doubleArrow(_executeCommandParams, _function_1); - reg.executeCommand(_doubleArrow, null, null); - ExecuteCommandParams _executeCommandParams_1 = new ExecuteCommandParams(); - final Procedure1 _function_2 = (ExecuteCommandParams it) -> { - it.setCommand("dynamic-command"); - }; - ExecuteCommandParams _doubleArrow_1 = ObjectExtensions.operator_doubleArrow(_executeCommandParams_1, _function_2); - reg.executeCommand(_doubleArrow_1, null, null); - Assert.assertEquals(Collections.unmodifiableSet(CollectionLiterals.newHashSet("static-command")), this.commandsExecuted); - this.commandsExecuted.clear(); - final IDisposable disposable = this.register.apply("dynamic-command"); - ExecuteCommandParams _executeCommandParams_2 = new ExecuteCommandParams(); - final Procedure1 _function_3 = (ExecuteCommandParams it) -> { - it.setCommand("dynamic-command"); - }; - ExecuteCommandParams _doubleArrow_2 = ObjectExtensions.operator_doubleArrow(_executeCommandParams_2, _function_3); - reg.executeCommand(_doubleArrow_2, null, null); - Assert.assertEquals(Collections.unmodifiableSet(CollectionLiterals.newHashSet("dynamic-command")), this.commandsExecuted); - this.commandsExecuted.clear(); - disposable.dispose(); - ExecuteCommandParams _executeCommandParams_3 = new ExecuteCommandParams(); - final Procedure1 _function_4 = (ExecuteCommandParams it) -> { - it.setCommand("dynamic-command"); - }; - ExecuteCommandParams _doubleArrow_3 = ObjectExtensions.operator_doubleArrow(_executeCommandParams_3, _function_4); - reg.executeCommand(_doubleArrow_3, null, null); - Assert.assertEquals(Collections.unmodifiableSet(CollectionLiterals.newHashSet()), this.commandsExecuted); - } - - @Override - public List initialize() { - return Collections.unmodifiableList(CollectionLiterals.newArrayList("static-command")); - } - - @Override - public void initializeDynamicRegistration(final Function1 register) { - this.register = register; - } - - @Override - public Object execute(final ExecuteCommandParams params, final ILanguageServerAccess access, final CancelIndicator cancelIndicator) { - return Boolean.valueOf(this.commandsExecuted.add(params.getCommand())); - } - - @Delegate - private IResourceServiceProvider noImpl; - - @Override - public T get(final Class t) { - return ((T) this); - } - - @Delegate - private LanguageClient noImpl3; - - @Override - public CompletableFuture registerCapability(final RegistrationParams params) { - final Registration reg = IterableExtensions.head(params.getRegistrations()); - this.registered.put(reg.getId(), reg); - return CompletableFuture.completedFuture(null); - } - - @Override - public CompletableFuture unregisterCapability(final UnregistrationParams params) { - final Unregistration unreg = IterableExtensions.head(params.getUnregisterations()); - this.registered.remove(unreg); - return CompletableFuture.completedFuture(null); - } - - public boolean canHandle(final URI uri) { - return this.noImpl.canHandle(uri); - } - - public IContainer.Manager getContainerManager() { - return this.noImpl.getContainerManager(); - } - - public IEncodingProvider getEncodingProvider() { - return this.noImpl.getEncodingProvider(); - } - - public IResourceDescription.Manager getResourceDescriptionManager() { - return this.noImpl.getResourceDescriptionManager(); - } - - public IResourceValidator getResourceValidator() { - return this.noImpl.getResourceValidator(); - } - - public CompletableFuture applyEdit(final ApplyWorkspaceEditParams params) { - return this.noImpl3.applyEdit(params); - } - - public CompletableFuture> configuration(final ConfigurationParams configurationParams) { - return this.noImpl3.configuration(configurationParams); - } - - public void logMessage(final MessageParams message) { - this.noImpl3.logMessage(message); - } - - public void publishDiagnostics(final PublishDiagnosticsParams diagnostics) { - this.noImpl3.publishDiagnostics(diagnostics); - } - - public void semanticHighlighting(final SemanticHighlightingParams params) { - this.noImpl3.semanticHighlighting(params); - } - - public void showMessage(final MessageParams messageParams) { - this.noImpl3.showMessage(messageParams); - } - - public CompletableFuture showMessageRequest(final ShowMessageRequestParams requestParams) { - return this.noImpl3.showMessageRequest(requestParams); - } - - public void telemetryEvent(final Object object) { - this.noImpl3.telemetryEvent(object); - } - - public CompletableFuture> workspaceFolders() { - return this.noImpl3.workspaceFolders(); - } -} diff --git a/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/importHandling/ImportTestHelper.java b/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/importHandling/ImportTestHelper.java deleted file mode 100644 index 633a66be2..000000000 --- a/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/importHandling/ImportTestHelper.java +++ /dev/null @@ -1,116 +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.importHandling; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Iterables; -import com.google.inject.Inject; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.function.Consumer; -import org.eclipse.emf.common.util.URI; -import org.eclipse.emf.ecore.resource.Resource; -import org.eclipse.emf.ecore.resource.ResourceSet; -import org.eclipse.emf.ecore.util.EcoreUtil; -import org.eclipse.xtext.formatting2.debug.TextRegionAccessToString; -import org.eclipse.xtext.formatting2.regionaccess.ITextRegionAccess; -import org.eclipse.xtext.ide.serializer.IChangeSerializer; -import org.eclipse.xtext.ide.serializer.IEmfResourceChange; -import org.eclipse.xtext.ide.serializer.debug.TextDocumentChangeToString; -import org.eclipse.xtext.ide.serializer.impl.TextDocumentChange; -import org.eclipse.xtext.resource.IResourceDescription; -import org.eclipse.xtext.resource.XtextResource; -import org.eclipse.xtext.resource.XtextResourceSet; -import org.eclipse.xtext.resource.impl.ChunkedResourceDescriptions; -import org.eclipse.xtext.resource.impl.ResourceDescriptionsData; -import org.eclipse.xtext.resource.impl.ResourceDescriptionsProvider; -import org.eclipse.xtext.testing.util.InMemoryURIHandler; -import org.eclipse.xtext.testing.validation.ValidationTestHelper; -import org.eclipse.xtext.util.CollectionBasedAcceptor; -import org.eclipse.xtext.util.Strings; -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.Pair; -import org.junit.Assert; - -/** - * TODO: de-duplicate with /xtext-core/org.eclipse.xtext.ide.tests/src/org/eclipse/xtext/ide/tests/serializer/ChangeSerializerTestHelper.xtend - * - * @author Moritz Eysholdt - Initial contribution and API - */ -@SuppressWarnings("all") -public class ImportTestHelper { - @Inject - private IResourceDescription.Manager rdManager; - - @Inject - private ValidationTestHelper validator; - - public void operator_tripleEquals(final Collection actual, final CharSequence expected) { - final String actualString = new TextDocumentChangeToString().add(actual).toString(); - Assert.assertEquals(Strings.toPlatformLineSeparator(expected).trim(), Strings.toPlatformLineSeparator(actualString).trim()); - } - - public void operator_tripleEquals(final ITextRegionAccess actual, final CharSequence expected) { - final String actualString = new TextRegionAccessToString().withRegionAccess(actual).hideColumnExplanation().toString(); - Assert.assertEquals(expected.toString().trim(), actualString.trim()); - } - - public void operator_add(final InMemoryURIHandler handler, final Pair file) { - final InMemoryURIHandler.InMemFile f = handler.getInMemoryFile(URI.createURI(file.getKey())); - f.setContents(Strings.toUnixLineSeparator(file.getValue()).getBytes()); - f.setExists(true); - } - - public ResourceSet createResourceSet(final InMemoryURIHandler fs) { - final XtextResourceSet idx = new XtextResourceSet(); - idx.getURIConverter().getURIHandlers().add(0, fs); - Collection _values = fs.getFiles().values(); - for (final InMemoryURIHandler.InMemFile f : _values) { - idx.getResource(f.getUri(), true); - } - EcoreUtil.resolveAll(idx); - final Consumer _function = (XtextResource it) -> { - this.validator.assertNoErrors(it); - }; - Iterables.filter(idx.getResources(), XtextResource.class).forEach(_function); - final Function1 _function_1 = (Resource it) -> { - return this.rdManager.getResourceDescription(it); - }; - final List rsd = ListExtensions.map(idx.getResources(), _function_1); - final ResourceDescriptionsData data = new ResourceDescriptionsData(rsd); - final XtextResourceSet r = new XtextResourceSet(); - r.getLoadOptions().put(ResourceDescriptionsProvider.LIVE_SCOPE, Boolean.TRUE); - r.getURIConverter().getURIHandlers().add(0, fs); - ResourceDescriptionsData.ResourceSetAdapter.installResourceDescriptionsData(r, data); - Pair _mappedTo = Pair.of("egal", data); - new ChunkedResourceDescriptions(Collections.unmodifiableMap(CollectionLiterals.newHashMap(_mappedTo)), r); - return r; - } - - public T contents(final ResourceSet rs, final String fileName, final Class type) { - final T result = IterableExtensions.head(Iterables.filter(rs.getResource(URI.createURI(fileName), true).getContents(), type)); - Preconditions.checkNotNull(result); - return result; - } - - public ITextRegionAccess endRecordChangesToTextRegions(final IChangeSerializer ser) { - return IterableExtensions.head(Iterables.filter(this.endRecordChangesToTextDocuments(ser), TextDocumentChange.class)).getTextRegionAccess(); - } - - public Collection endRecordChangesToTextDocuments(final IChangeSerializer ser) { - final ArrayList list = CollectionLiterals.newArrayList(); - ser.applyModifications(CollectionBasedAcceptor.of(list)); - return list; - } -} diff --git a/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/serializer/ChangeSerializerTestHelper.java b/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/serializer/ChangeSerializerTestHelper.java deleted file mode 100644 index b00ef2567..000000000 --- a/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/serializer/ChangeSerializerTestHelper.java +++ /dev/null @@ -1,116 +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.serializer; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Iterables; -import com.google.inject.Guice; -import com.google.inject.Inject; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.function.Consumer; -import org.eclipse.emf.common.util.URI; -import org.eclipse.emf.ecore.resource.Resource; -import org.eclipse.emf.ecore.resource.ResourceSet; -import org.eclipse.emf.ecore.util.EcoreUtil; -import org.eclipse.xtext.formatting2.debug.TextRegionAccessToString; -import org.eclipse.xtext.formatting2.regionaccess.ITextRegionAccess; -import org.eclipse.xtext.ide.serializer.IChangeSerializer; -import org.eclipse.xtext.ide.serializer.IEmfResourceChange; -import org.eclipse.xtext.ide.serializer.debug.TextDocumentChangeToString; -import org.eclipse.xtext.ide.serializer.impl.ChangeSerializer; -import org.eclipse.xtext.ide.serializer.impl.TextDocumentChange; -import org.eclipse.xtext.resource.IResourceDescription; -import org.eclipse.xtext.resource.XtextResource; -import org.eclipse.xtext.resource.XtextResourceSet; -import org.eclipse.xtext.resource.impl.ResourceDescriptionsData; -import org.eclipse.xtext.resource.impl.ResourceDescriptionsProvider; -import org.eclipse.xtext.testing.util.InMemoryURIHandler; -import org.eclipse.xtext.testing.validation.ValidationTestHelper; -import org.eclipse.xtext.util.CollectionBasedAcceptor; -import org.eclipse.xtext.util.Strings; -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.Pair; -import org.junit.Assert; - -/** - * @author Moritz Eysholdt - Initial contribution and API - */ -@SuppressWarnings("all") -public class ChangeSerializerTestHelper { - @Inject - private IResourceDescription.Manager rdManager; - - @Inject - private ValidationTestHelper validator; - - public void operator_tripleEquals(final Collection actual, final CharSequence expected) { - final String actualString = new TextDocumentChangeToString().add(actual).toString(); - Assert.assertEquals(Strings.toPlatformLineSeparator(expected).trim(), Strings.toPlatformLineSeparator(actualString).trim()); - } - - public void operator_tripleEquals(final ITextRegionAccess actual, final CharSequence expected) { - final String actualString = new TextRegionAccessToString().withRegionAccess(actual).hideColumnExplanation().toString(); - Assert.assertEquals(Strings.toPlatformLineSeparator(expected).trim(), Strings.toPlatformLineSeparator(actualString).trim()); - } - - public void operator_add(final InMemoryURIHandler handler, final Pair file) { - final InMemoryURIHandler.InMemFile f = handler.getInMemoryFile(URI.createURI(file.getKey())); - f.setContents(Strings.toUnixLineSeparator(file.getValue()).getBytes()); - f.setExists(true); - } - - public ResourceSet createResourceSet(final InMemoryURIHandler fs) { - final XtextResourceSet idx = new XtextResourceSet(); - idx.getURIConverter().getURIHandlers().add(0, fs); - Collection _values = fs.getFiles().values(); - for (final InMemoryURIHandler.InMemFile f : _values) { - idx.getResource(f.getUri(), true); - } - EcoreUtil.resolveAll(idx); - final Consumer _function = (XtextResource it) -> { - this.validator.assertNoErrors(it); - }; - Iterables.filter(idx.getResources(), XtextResource.class).forEach(_function); - final Function1 _function_1 = (Resource it) -> { - return this.rdManager.getResourceDescription(it); - }; - final List rsd = ListExtensions.map(idx.getResources(), _function_1); - final ResourceDescriptionsData data = new ResourceDescriptionsData(rsd); - final XtextResourceSet r = new XtextResourceSet(); - r.getLoadOptions().put(ResourceDescriptionsProvider.LIVE_SCOPE, Boolean.TRUE); - r.getURIConverter().getURIHandlers().add(0, fs); - ResourceDescriptionsData.ResourceSetAdapter.installResourceDescriptionsData(r, data); - return r; - } - - public T contents(final ResourceSet rs, final String fileName, final Class type) { - final T result = IterableExtensions.head(Iterables.filter(rs.getResource(URI.createURI(fileName), true).getContents(), type)); - Preconditions.checkNotNull(result); - return result; - } - - public ITextRegionAccess endRecordChangesToTextRegions(final IChangeSerializer ser) { - return IterableExtensions.head(Iterables.filter(this.endRecordChangesToTextDocuments(ser), TextDocumentChange.class)).getTextRegionAccess(); - } - - public Collection endRecordChangesToTextDocuments(final IChangeSerializer ser) { - final ArrayList list = CollectionLiterals.newArrayList(); - ser.applyModifications(CollectionBasedAcceptor.of(list)); - return list; - } - - public IChangeSerializer newChangeSerializer() { - return Guice.createInjector().getInstance(ChangeSerializer.class); - } -} diff --git a/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/server/SourceFolderCustomImplTest.java b/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/server/SourceFolderCustomImplTest.java deleted file mode 100644 index 9c699ce4b..000000000 --- a/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/server/SourceFolderCustomImplTest.java +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Copyright (c) 2019 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.server; - -import com.google.inject.AbstractModule; -import com.google.inject.Inject; -import com.google.inject.Scopes; -import java.util.List; -import java.util.Set; -import java.util.function.Predicate; -import org.eclipse.emf.common.util.URI; -import org.eclipse.lsp4j.WorkspaceFolder; -import org.eclipse.xtext.ide.server.IMultiRootWorkspaceConfigFactory; -import org.eclipse.xtext.ide.server.MultiRootWorkspaceConfigFactory; -import org.eclipse.xtext.ide.server.ProjectManager; -import org.eclipse.xtext.ide.server.WorkspaceManager; -import org.eclipse.xtext.ide.tests.server.AbstractTestLangLanguageServerTest; -import org.eclipse.xtext.util.IFileSystemScanner; -import org.eclipse.xtext.util.Modules2; -import org.eclipse.xtext.workspace.FileProjectConfig; -import org.eclipse.xtext.workspace.FileSourceFolder; -import org.eclipse.xtext.workspace.ISourceFolder; -import org.eclipse.xtext.workspace.WorkspaceConfig; -import org.eclipse.xtext.xbase.lib.Conversions; -import org.eclipse.xtext.xbase.lib.Functions.Function1; -import org.eclipse.xtext.xbase.lib.IterableExtensions; -import org.junit.Assert; -import org.junit.Test; - -/** - * Tests customized version of default methods ISourceFolder#contains(URI) and ISourceFolder#getAllResources(IFileSystemScanner) - */ -@SuppressWarnings("all") -public class SourceFolderCustomImplTest extends AbstractTestLangLanguageServerTest { - public static class CustomWorkspaceConfigFactory extends MultiRootWorkspaceConfigFactory { - @Override - public void addProjectsForWorkspaceFolder(final WorkspaceConfig workspaceConfig, final WorkspaceFolder workspaceFolder, final Set existingNames) { - String _uri = null; - if (workspaceFolder!=null) { - _uri=workspaceFolder.getUri(); - } - boolean _tripleNotEquals = (_uri != null); - if (_tripleNotEquals) { - URI _uri_1 = this.getUriExtensions().toUri(workspaceFolder.getUri()); - final SourceFolderCustomImplTest.CustomFileProjectConfig project = new SourceFolderCustomImplTest.CustomFileProjectConfig(_uri_1, workspaceConfig); - project.addSourceFolder("."); - workspaceConfig.addProject(project); - } - } - } - - public static class CustomFileProjectConfig extends FileProjectConfig { - public CustomFileProjectConfig(final URI uri, final WorkspaceConfig workspaceConfig) { - super(uri, workspaceConfig); - } - - @Override - public FileSourceFolder addSourceFolder(final String relativePath) { - SourceFolderCustomImplTest.CustomFileSourceFolder _xblockexpression = null; - { - final SourceFolderCustomImplTest.CustomFileSourceFolder sourceFolder = new SourceFolderCustomImplTest.CustomFileSourceFolder(this, relativePath); - Set _sourceFolders = this.getSourceFolders(); - _sourceFolders.add(sourceFolder); - _xblockexpression = sourceFolder; - } - return _xblockexpression; - } - } - - public static class CustomFileSourceFolder extends FileSourceFolder { - public CustomFileSourceFolder(final FileProjectConfig parent, final String name) { - super(parent, name); - } - - public boolean filterTheFile(final URI uri) { - return uri.toFileString().endsWith("sample.testlang"); - } - - @Override - public boolean contains(final URI uri) { - boolean _xblockexpression = false; - { - boolean _filterTheFile = this.filterTheFile(uri); - if (_filterTheFile) { - return false; - } - _xblockexpression = super.contains(uri); - } - return _xblockexpression; - } - - @Override - public List getAllResources(final IFileSystemScanner scanner) { - final List allResources = super.getAllResources(scanner); - final Predicate _function = (URI uri) -> { - return this.filterTheFile(uri); - }; - allResources.removeIf(_function); - return allResources; - } - } - - @Inject - private WorkspaceManager workspaceManager; - - @Inject - private IFileSystemScanner scanner; - - /** - * Asserts that the custom implementation returns not all files of the configured source folder - */ - @Test - public void testCustomSourceFolderImplementation() { - this.writeFile("sample.testlang", "MyContent"); - this.initialize(); - final ProjectManager projectManager = this.workspaceManager.getProjectManager(""); - final Set sourceFolders = projectManager.getProjectConfig().getSourceFolders(); - int _size = sourceFolders.size(); - boolean _equals = (_size == 1); - Assert.assertTrue(_equals); - final ISourceFolder sourceFolder = ((ISourceFolder[])Conversions.unwrapArray(sourceFolders, ISourceFolder.class))[0]; - final List allResources = sourceFolder.getAllResources(this.scanner); - final Function1 _function = (URI uri) -> { - return Boolean.valueOf(uri.toString().endsWith("test-data/test-project/")); - }; - Assert.assertTrue(IterableExtensions.exists(allResources, _function)); - final Function1 _function_1 = (URI uri) -> { - return Boolean.valueOf(uri.toString().endsWith("test-data/test-project/sample.testlang")); - }; - Assert.assertFalse(IterableExtensions.exists(allResources, _function_1)); - Assert.assertEquals(allResources.size(), 1); - } - - @Override - protected com.google.inject.Module getServerModule() { - final com.google.inject.Module defaultModule = super.getServerModule(); - final com.google.inject.Module customModule = new AbstractModule() { - @Override - protected void configure() { - this.bind(IMultiRootWorkspaceConfigFactory.class).to(SourceFolderCustomImplTest.CustomWorkspaceConfigFactory.class); - this.bind(WorkspaceManager.class).in(Scopes.SINGLETON); - } - }; - return Modules2.mixin(defaultModule, customModule); - } -} diff --git a/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/server/SourceFolderDefaultImplTest.java b/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/server/SourceFolderDefaultImplTest.java deleted file mode 100644 index 71df64961..000000000 --- a/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/server/SourceFolderDefaultImplTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright (c) 2019 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.server; - -import com.google.inject.AbstractModule; -import com.google.inject.Inject; -import com.google.inject.Scopes; -import java.util.List; -import java.util.Set; -import org.eclipse.emf.common.util.URI; -import org.eclipse.xtext.ide.server.ProjectManager; -import org.eclipse.xtext.ide.server.WorkspaceManager; -import org.eclipse.xtext.ide.tests.server.AbstractTestLangLanguageServerTest; -import org.eclipse.xtext.util.IFileSystemScanner; -import org.eclipse.xtext.util.Modules2; -import org.eclipse.xtext.workspace.ISourceFolder; -import org.eclipse.xtext.xbase.lib.Conversions; -import org.eclipse.xtext.xbase.lib.Functions.Function1; -import org.eclipse.xtext.xbase.lib.IterableExtensions; -import org.junit.Assert; -import org.junit.Test; - -/** - * Tests default methods ISourceFolder#contains(URI) and ISourceFolder#getAllResources(IFileSystemScanner) - */ -@SuppressWarnings("all") -public class SourceFolderDefaultImplTest extends AbstractTestLangLanguageServerTest { - @Inject - private WorkspaceManager workspaceManager; - - @Inject - private IFileSystemScanner scanner; - - /** - * Asserts that the default implementation returns all files in the configured source folder - */ - @Test - public void testDefaultSourceFolderImplementation() { - this.writeFile("sample.testlang", "MyContent"); - this.initialize(); - final ProjectManager projectManager = this.workspaceManager.getProjectManager(""); - final Set sourceFolders = projectManager.getProjectConfig().getSourceFolders(); - int _size = sourceFolders.size(); - boolean _equals = (_size == 1); - Assert.assertTrue(_equals); - final ISourceFolder sourceFolder = ((ISourceFolder[])Conversions.unwrapArray(sourceFolders, ISourceFolder.class))[0]; - final List allResources = sourceFolder.getAllResources(this.scanner); - final Function1 _function = (URI uri) -> { - return Boolean.valueOf(uri.toString().endsWith("test-data/test-project/")); - }; - Assert.assertTrue(IterableExtensions.exists(allResources, _function)); - final Function1 _function_1 = (URI uri) -> { - return Boolean.valueOf(uri.toString().endsWith("test-data/test-project/sample.testlang")); - }; - Assert.assertTrue(IterableExtensions.exists(allResources, _function_1)); - Assert.assertEquals(allResources.size(), 2); - } - - @Override - protected com.google.inject.Module getServerModule() { - final com.google.inject.Module defaultModule = super.getServerModule(); - final com.google.inject.Module customModule = new AbstractModule() { - @Override - protected void configure() { - this.bind(WorkspaceManager.class).in(Scopes.SINGLETON); - } - }; - return Modules2.mixin(defaultModule, customModule); - } -} diff --git a/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/testlanguage/ide/TestLanguageIdeContentProposalProvider.java b/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/testlanguage/ide/TestLanguageIdeContentProposalProvider.java index 70d6a8af8..6b41380cd 100644 --- a/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/testlanguage/ide/TestLanguageIdeContentProposalProvider.java +++ b/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/testlanguage/ide/TestLanguageIdeContentProposalProvider.java @@ -1,5 +1,5 @@ /** - * Copyright (c) 2018 itemis AG (http://www.itemis.eu) and others. + * 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. @@ -16,6 +16,7 @@ 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; @@ -35,6 +36,7 @@ public class TestLanguageIdeContentProposalProvider extends IdeContentProposalPr 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(); @@ -42,7 +44,7 @@ public class TestLanguageIdeContentProposalProvider extends IdeContentProposalPr _builder.newLine(); _builder.append("\t\t\t"); _builder.append("}"); - acceptor.accept(this.getProposalCreator().createSnippet(_builder.toString(), "Sample Snippet", context), 0); + acceptor.accept(_proposalCreator.createSnippet(_builder.toString(), "Sample Snippet", context), 0); } super._createProposals(ruleCall, context, acceptor); } diff --git a/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/testlanguage/rename/TestLanguageRenameService.java b/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/testlanguage/rename/TestLanguageRenameService.java deleted file mode 100644 index cc9bd7ab5..000000000 --- a/org.eclipse.xtext.ide.tests/xtend-gen/org/eclipse/xtext/ide/tests/testlanguage/rename/TestLanguageRenameService.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright (c) 2019 TypeFox 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.rename; - -import com.google.common.base.Objects; -import com.google.inject.Inject; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.xtext.ide.server.rename.RenameService2; -import org.eclipse.xtext.naming.IQualifiedNameProvider; -import org.eclipse.xtext.naming.QualifiedName; -import org.eclipse.xtext.nodemodel.ICompositeNode; -import org.eclipse.xtext.nodemodel.ILeafNode; -import org.eclipse.xtext.nodemodel.util.NodeModelUtils; -import org.eclipse.xtext.parser.IParseResult; -import org.eclipse.xtext.resource.EObjectAtOffsetHelper; -import org.eclipse.xtext.resource.XtextResource; -import org.eclipse.xtext.xbase.lib.Extension; - -@SuppressWarnings("all") -public class TestLanguageRenameService extends RenameService2 { - @Inject - @Extension - private EObjectAtOffsetHelper _eObjectAtOffsetHelper; - - @Override - protected EObject getElementWithIdentifierAt(final XtextResource xtextResource, final int offset) { - if ((offset >= 0)) { - IParseResult _parseResult = null; - if (xtextResource!=null) { - _parseResult=xtextResource.getParseResult(); - } - ICompositeNode _rootNode = null; - if (_parseResult!=null) { - _rootNode=_parseResult.getRootNode(); - } - final ICompositeNode rootNode = _rootNode; - if ((rootNode != null)) { - final ILeafNode leaf = NodeModelUtils.findLeafNodeAtOffset(rootNode, offset); - if (((leaf != null) && this.isIdentifier(leaf))) { - final EObject element = this._eObjectAtOffsetHelper.resolveElementAt(xtextResource, offset); - if ((element != null)) { - final IQualifiedNameProvider nameProvider = xtextResource.getResourceServiceProvider().get(IQualifiedNameProvider.class); - final QualifiedName fqn = nameProvider.getFullyQualifiedName(element); - if ((fqn != null)) { - final String leafText = NodeModelUtils.getTokenText(leaf); - if ((((fqn.getSegmentCount() == 1) && Objects.equal(fqn.toString(), leafText)) || Objects.equal(fqn.getLastSegment(), leafText))) { - return element; - } - } - } - } - } - } - return null; - } -} diff --git a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/bracketmatching/DefaultBracePairProvider.java b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/bracketmatching/DefaultBracePairProvider.java index adfbff581..cd63759d9 100644 --- a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/bracketmatching/DefaultBracePairProvider.java +++ b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/bracketmatching/DefaultBracePairProvider.java @@ -11,8 +11,7 @@ package org.eclipse.xtext.ide.editor.bracketmatching; import java.util.Collections; import java.util.Set; -import org.eclipse.xtext.xbase.lib.CollectionLiterals; - +import com.google.common.collect.Sets; import com.google.inject.Singleton; /** @@ -23,7 +22,7 @@ public class DefaultBracePairProvider implements IBracePairProvider { private final Set pairs; public DefaultBracePairProvider() { - this(Collections.unmodifiableSet(CollectionLiterals.newHashSet(new BracePair("(", ")", true), + this(Collections.unmodifiableSet(Sets.newHashSet(new BracePair("(", ")", true), new BracePair("{", "}", true), new BracePair("[", "]", true)))); } diff --git a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/bracketmatching/XtextBracePairProvider.java b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/bracketmatching/XtextBracePairProvider.java index 8b6aa3370..7f5f28064 100644 --- a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/bracketmatching/XtextBracePairProvider.java +++ b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/bracketmatching/XtextBracePairProvider.java @@ -10,8 +10,7 @@ package org.eclipse.xtext.ide.editor.bracketmatching; import java.util.Collections; -import org.eclipse.xtext.xbase.lib.CollectionLiterals; - +import com.google.common.collect.Sets; import com.google.inject.Singleton; /** @@ -20,7 +19,7 @@ import com.google.inject.Singleton; @Singleton public class XtextBracePairProvider extends DefaultBracePairProvider { public XtextBracePairProvider() { - super(Collections.unmodifiableSet(CollectionLiterals.newHashSet(new BracePair(":", ";", true), + super(Collections.unmodifiableSet(Sets.newHashSet(new BracePair(":", ";", true), new BracePair("(", ")", false), new BracePair("{", "}", true), new BracePair("[", "]", false)))); } } diff --git a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/contentassist/FQNPrefixMatcher.java b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/contentassist/FQNPrefixMatcher.java new file mode 100644 index 000000000..f01a1d482 --- /dev/null +++ b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/contentassist/FQNPrefixMatcher.java @@ -0,0 +1,86 @@ +/** + * 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.editor.contentassist; + +import java.util.List; + +import org.eclipse.xtext.naming.IQualifiedNameConverter; +import org.eclipse.xtext.util.Strings; + +import com.google.inject.Inject; + +/** + * Prefix matcher for fully qualified names. + * + * @since 2.10 + * @noreference + */ +public class FQNPrefixMatcher implements IPrefixMatcher { + @Inject + private IPrefixMatcher.IgnoreCase delegate; + + @Inject + private IQualifiedNameConverter qualifiedNameConverter; + + @Override + public boolean isCandidateMatchingPrefix(String name, String prefix) { + if (delegate.isCandidateMatchingPrefix(name, prefix)) { + return true; + } + String delimiter = getDelimiter(); + if (!Strings.isEmpty(delimiter) && name.indexOf(delimiter) >= 0) { + if (prefix.indexOf(delimiter) < 0) { + String lastSegment = getLastSegment(name, delimiter); + if (lastSegment != null && delegate.isCandidateMatchingPrefix(lastSegment, prefix)) { + return true; + } + } else { + List splitPrefix = Strings.split(prefix, delimiter); + if (splitPrefix.isEmpty()) { + return false; + } + List splitName = Strings.split(name, delimiter); + if (splitName.size() < splitPrefix.size()) { + return false; + } + for (int i = 0; i < splitPrefix.size(); i++) { + if (!delegate.isCandidateMatchingPrefix(splitName.get(i), splitPrefix.get(i))) { + return false; + } + } + return true; + } + } + return false; + } + + protected String getLastSegment(String fqn, String delimiter) { + int lastDelimIndex = fqn.lastIndexOf(delimiter); + if (lastDelimIndex >= 0 && lastDelimIndex + delimiter.length() < fqn.length()) { + return fqn.substring(lastDelimIndex + delimiter.length()); + } + return null; + } + + public String getDelimiter() { + if (qualifiedNameConverter instanceof IQualifiedNameConverter.DefaultImpl) { + return ((IQualifiedNameConverter.DefaultImpl) qualifiedNameConverter).getDelimiter(); + } else { + return "."; + } + } + + public IPrefixMatcher.IgnoreCase getDelegate() { + return delegate; + } + + public void setDelegate(IPrefixMatcher.IgnoreCase delegate) { + this.delegate = delegate; + } +} diff --git a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/contentassist/FQNPrefixMatcher.xtend b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/contentassist/FQNPrefixMatcher.xtend deleted file mode 100644 index 5c7bc9653..000000000 --- a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/contentassist/FQNPrefixMatcher.xtend +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016 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.editor.contentassist - -import com.google.inject.Inject -import org.eclipse.xtend.lib.annotations.Accessors -import org.eclipse.xtext.naming.IQualifiedNameConverter -import org.eclipse.xtext.util.Strings - -/** - * Prefix matcher for fully qualified names. - * - * @since 2.10 - * @noreference - */ -class FQNPrefixMatcher implements IPrefixMatcher { - - @Accessors - @Inject IPrefixMatcher.IgnoreCase delegate - - @Inject IQualifiedNameConverter qualifiedNameConverter - - override boolean isCandidateMatchingPrefix(String name, String prefix) { - if (delegate.isCandidateMatchingPrefix(name, prefix)) - return true - val delimiter = getDelimiter - // Assume a FQN if delimiter is present - if (!delimiter.nullOrEmpty && name.indexOf(delimiter) >= 0) { - if (prefix.indexOf(delimiter) < 0) { - // Prefix is without delimiter - either namespace or last segment - val lastSegment = getLastSegment(name, delimiter) - if (lastSegment !== null && delegate.isCandidateMatchingPrefix(lastSegment, prefix)) - return true - } else { - val splitPrefix = Strings.split(prefix, delimiter) - if (splitPrefix.empty) - return false - val splitName = Strings.split(name, delimiter) - if (splitName.size < splitPrefix.size) - return false - for (var i = 0; i < splitPrefix.size; i++) { - if (!delegate.isCandidateMatchingPrefix(splitName.get(i), splitPrefix.get(i))) - return false - } - return true - } - } - return false - } - - def protected String getLastSegment(String fqn, String delimiter) { - val lastDelimIndex = fqn.lastIndexOf(delimiter) - if (lastDelimIndex >= 0 && lastDelimIndex + delimiter.length < fqn.length) - return fqn.substring(lastDelimIndex + delimiter.length) - } - - def String getDelimiter() { - if (qualifiedNameConverter instanceof IQualifiedNameConverter.DefaultImpl) - return qualifiedNameConverter.delimiter - else - return '.' - } - -} diff --git a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/contentassist/IdeContentProposalProvider.java b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/contentassist/IdeContentProposalProvider.java new file mode 100644 index 000000000..b11e784a8 --- /dev/null +++ b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/contentassist/IdeContentProposalProvider.java @@ -0,0 +1,196 @@ +/** + * 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.ide.editor.contentassist; + +import java.util.Arrays; +import java.util.Collection; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EClassifier; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.xtext.AbstractElement; +import org.eclipse.xtext.AbstractRule; +import org.eclipse.xtext.Assignment; +import org.eclipse.xtext.CrossReference; +import org.eclipse.xtext.GrammarUtil; +import org.eclipse.xtext.Keyword; +import org.eclipse.xtext.RuleCall; +import org.eclipse.xtext.TerminalRule; +import org.eclipse.xtext.naming.IQualifiedNameConverter; +import org.eclipse.xtext.resource.IEObjectDescription; +import org.eclipse.xtext.scoping.IScope; +import org.eclipse.xtext.scoping.IScopeProvider; +import org.eclipse.xtext.util.TextRegion; +import org.eclipse.xtext.xtext.CurrentTypeFinder; + +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import com.google.inject.Inject; + +/** + * Generic content proposal provider for use in different IDE contexts. This provider is not used by the + * Eclipse integration, which has its own abstraction for content assist proposals. + * + * @noreference + */ +public class IdeContentProposalProvider { + @Inject + private IScopeProvider scopeProvider; + + @Inject + private IQualifiedNameConverter qualifiedNameConverter; + + @Inject + private IdeCrossrefProposalProvider crossrefProposalProvider; + + @Inject + private IdeContentProposalCreator proposalCreator; + + @Inject + private IdeContentProposalPriorities proposalPriorities; + + @Inject + private CurrentTypeFinder currentTypeFinder; + + /** + * Create content assist proposals and pass them to the given acceptor. + */ + public void createProposals(Collection contexts, IIdeContentProposalAcceptor acceptor) { + for (ContentAssistContext context : getFilteredContexts(contexts)) { + for (AbstractElement element : context.getFirstSetGrammarElements()) { + if (!acceptor.canAcceptMoreProposals()) { + return; + } + createProposals(element, context, acceptor); + } + } + } + + protected Iterable getFilteredContexts(Collection contexts) { + return contexts; + } + + protected void _createProposals(AbstractElement element, ContentAssistContext context, + IIdeContentProposalAcceptor acceptor) { + } + + protected void _createProposals(Assignment assignment, ContentAssistContext context, + IIdeContentProposalAcceptor acceptor) { + AbstractElement terminal = assignment.getTerminal(); + if (terminal instanceof CrossReference) { + createProposals(terminal, context, acceptor); + } else { + if (terminal instanceof RuleCall) { + AbstractRule rule = ((RuleCall) terminal).getRule(); + if (rule instanceof TerminalRule && context.getPrefix().isEmpty()) { + final String proposal; + if ("STRING".equals(rule.getName())) { + proposal = "\"" + assignment.getFeature() + "\""; + } else { + proposal = assignment.getFeature(); + } + ContentAssistEntry entry = proposalCreator.createProposal(proposal, context, + (ContentAssistEntry it) -> { + if ("STRING".equals(rule.getName())) { + it.getEditPositions() + .add(new TextRegion(context.getOffset() + 1, proposal.length() - 2)); + it.setKind(ContentAssistEntry.KIND_TEXT); + } else { + it.getEditPositions().add(new TextRegion(context.getOffset(), proposal.length())); + it.setKind(ContentAssistEntry.KIND_VALUE); + } + it.setDescription(rule.getName()); + }); + acceptor.accept(entry, proposalPriorities.getDefaultPriority(entry)); + } + } + } + } + + protected void _createProposals(Keyword keyword, ContentAssistContext context, + IIdeContentProposalAcceptor acceptor) { + if (filterKeyword(keyword, context)) { + ContentAssistEntry entry = proposalCreator.createProposal(keyword.getValue(), context, + ContentAssistEntry.KIND_KEYWORD, null); + if (entry != null) { + acceptor.accept(entry, proposalPriorities.getKeywordPriority(keyword.getValue(), entry)); + } + } + } + + protected boolean filterKeyword(Keyword keyword, ContentAssistContext context) { + return true; + } + + protected void _createProposals(RuleCall ruleCall, ContentAssistContext context, + IIdeContentProposalAcceptor acceptor) { + } + + protected void _createProposals(CrossReference reference, ContentAssistContext context, + IIdeContentProposalAcceptor acceptor) { + EClassifier type = currentTypeFinder.findCurrentTypeAfter(reference); + if (type instanceof EClass) { + EReference eReference = GrammarUtil.getReference(reference, ((EClass) type)); + EObject currentModel = context.getCurrentModel(); + if (eReference != null && currentModel != null) { + IScope scope = scopeProvider.getScope(currentModel, eReference); + crossrefProposalProvider.lookupCrossReference(scope, reference, context, acceptor, + getCrossrefFilter(reference, context)); + } + } + } + + protected Predicate getCrossrefFilter(CrossReference reference, ContentAssistContext context) { + return Predicates.alwaysTrue(); + } + + protected void createProposals(AbstractElement assignment, ContentAssistContext context, + IIdeContentProposalAcceptor acceptor) { + if (assignment instanceof Assignment) { + _createProposals((Assignment) assignment, context, acceptor); + return; + } else if (assignment instanceof CrossReference) { + _createProposals((CrossReference) assignment, context, acceptor); + return; + } else if (assignment instanceof Keyword) { + _createProposals((Keyword) assignment, context, acceptor); + return; + } else if (assignment instanceof RuleCall) { + _createProposals((RuleCall) assignment, context, acceptor); + return; + } else if (assignment != null) { + _createProposals(assignment, context, acceptor); + return; + } else { + throw new IllegalArgumentException( + "Unhandled parameter types: " + Arrays.asList(assignment, context, acceptor).toString()); + } + } + + protected IScopeProvider getScopeProvider() { + return scopeProvider; + } + + protected IQualifiedNameConverter getQualifiedNameConverter() { + return qualifiedNameConverter; + } + + protected IdeCrossrefProposalProvider getCrossrefProposalProvider() { + return crossrefProposalProvider; + } + + protected IdeContentProposalCreator getProposalCreator() { + return proposalCreator; + } + + protected IdeContentProposalPriorities getProposalPriorities() { + return proposalPriorities; + } +} diff --git a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/contentassist/IdeContentProposalProvider.xtend b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/contentassist/IdeContentProposalProvider.xtend deleted file mode 100644 index 6fee94e00..000000000 --- a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/contentassist/IdeContentProposalProvider.xtend +++ /dev/null @@ -1,144 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015, 2016 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.editor.contentassist - -import com.google.common.base.Predicate -import com.google.common.base.Predicates -import com.google.inject.Inject -import java.util.Collection -import org.eclipse.emf.ecore.EClass -import org.eclipse.xtend.lib.annotations.Accessors -import org.eclipse.xtext.AbstractElement -import org.eclipse.xtext.Assignment -import org.eclipse.xtext.CrossReference -import org.eclipse.xtext.GrammarUtil -import org.eclipse.xtext.Keyword -import org.eclipse.xtext.RuleCall -import org.eclipse.xtext.TerminalRule -import org.eclipse.xtext.naming.IQualifiedNameConverter -import org.eclipse.xtext.resource.IEObjectDescription -import org.eclipse.xtext.scoping.IScopeProvider -import org.eclipse.xtext.util.TextRegion -import org.eclipse.xtext.xtext.CurrentTypeFinder - -/** - * Generic content proposal provider for use in different IDE contexts. This provider is - * not used by the Eclipse integration, which has its own abstraction for - * content assist proposals. - * @noreference - */ -class IdeContentProposalProvider { - - @Accessors(PROTECTED_GETTER) - @Inject IScopeProvider scopeProvider - - @Accessors(PROTECTED_GETTER) - @Inject IQualifiedNameConverter qualifiedNameConverter - - @Accessors(PROTECTED_GETTER) - @Inject IdeCrossrefProposalProvider crossrefProposalProvider - - @Accessors(PROTECTED_GETTER) - @Inject IdeContentProposalCreator proposalCreator - - @Accessors(PROTECTED_GETTER) - @Inject IdeContentProposalPriorities proposalPriorities - - @Inject extension CurrentTypeFinder - - /** - * Create content assist proposals and pass them to the given acceptor. - */ - def void createProposals(Collection contexts, IIdeContentProposalAcceptor acceptor) { - for (context : getFilteredContexts(contexts)) { - for (element : context.firstSetGrammarElements) { - if (!acceptor.canAcceptMoreProposals) { - return - } - createProposals(element, context, acceptor) - } - } - } - - protected def Iterable getFilteredContexts(Collection contexts) { - return contexts - } - - protected def dispatch void createProposals(AbstractElement element, ContentAssistContext context, - IIdeContentProposalAcceptor acceptor) { - // Unsupported element type - } - - protected def dispatch void createProposals(Assignment assignment, ContentAssistContext context, - IIdeContentProposalAcceptor acceptor) { - val terminal = assignment.terminal - if (terminal instanceof CrossReference) { - createProposals(terminal, context, acceptor) - } else if (terminal instanceof RuleCall) { - val rule = terminal.rule - if (rule instanceof TerminalRule && context.prefix.empty) { - val proposal = - if (rule.name == 'STRING') - '"' + assignment.feature + '"' - else - assignment.feature - val entry = proposalCreator.createProposal(proposal, context) [ - if (rule.name == 'STRING') { - editPositions += new TextRegion(context.offset + 1, proposal.length - 2) - kind = ContentAssistEntry.KIND_TEXT - } else { - editPositions += new TextRegion(context.offset, proposal.length) - kind = ContentAssistEntry.KIND_VALUE - } - description = rule.name - ] - acceptor.accept(entry, proposalPriorities.getDefaultPriority(entry)) - } - } - } - - protected def dispatch void createProposals(Keyword keyword, ContentAssistContext context, - IIdeContentProposalAcceptor acceptor) { - if (filterKeyword(keyword, context)) { - val entry = proposalCreator.createProposal(keyword.value, context,ContentAssistEntry.KIND_KEYWORD, null) - if (entry !== null) { - acceptor.accept(entry, proposalPriorities.getKeywordPriority(keyword.value, entry)) - } - } - } - - protected def boolean filterKeyword(Keyword keyword, ContentAssistContext context) { - return true - } - - protected def dispatch void createProposals(RuleCall ruleCall, ContentAssistContext context, - IIdeContentProposalAcceptor acceptor) { - // No default proposals for rule calls - } - - protected def dispatch void createProposals(CrossReference reference, ContentAssistContext context, - IIdeContentProposalAcceptor acceptor) { - val type = findCurrentTypeAfter(reference) - if (type instanceof EClass) { - val ereference = GrammarUtil.getReference(reference, type) - val currentModel = context.currentModel - if (ereference !== null && currentModel !== null) { - val scope = scopeProvider.getScope(currentModel, ereference) - crossrefProposalProvider.lookupCrossReference(scope, reference, context, acceptor, - getCrossrefFilter(reference, context)) - } - } - } - - protected def Predicate getCrossrefFilter(CrossReference reference, - ContentAssistContext context) { - Predicates.alwaysTrue - } - -} diff --git a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/hierarchy/DefaultCallHierarchyBuilder.java b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/hierarchy/DefaultCallHierarchyBuilder.java new file mode 100644 index 000000000..0647825db --- /dev/null +++ b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/hierarchy/DefaultCallHierarchyBuilder.java @@ -0,0 +1,220 @@ +/** + * 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.editor.hierarchy; + +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.util.EcoreUtil; +import org.eclipse.xtext.findReferences.ReferenceAcceptor; +import org.eclipse.xtext.findReferences.TargetURIs; +import org.eclipse.xtext.nodemodel.ICompositeNode; +import org.eclipse.xtext.nodemodel.util.NodeModelUtils; +import org.eclipse.xtext.resource.IEObjectDescription; +import org.eclipse.xtext.resource.IReferenceDescription; +import org.eclipse.xtext.util.ITextRegionWithLineInformation; +import org.eclipse.xtext.xbase.lib.Procedures.Procedure2; + +import com.google.common.collect.Lists; + +/** + *

+ * Default implementation of a call hierarchy builder. + *

+ * + * @author kosyakov - Initial contribution and API + * @since 2.10 + */ +public class DefaultCallHierarchyBuilder extends AbstractHierarchyBuilder implements ICallHierarchyBuilder { + private CallHierarchyType hierarchyType = CallHierarchyType.CALLER; + + @Override + public Collection buildRoots(URI rootURI, IProgressMonitor monitor) { + IEObjectDescription rootDeclaration = findDeclaration(rootURI); + if (rootDeclaration == null) { + return Collections.emptyList(); + } + return Lists.newArrayList(createRoot(rootDeclaration)); + } + + @Override + public Collection buildChildren(IHierarchyNode parent, IProgressMonitor monitor) { + if (!parent.mayHaveChildren()) { + return Collections.emptyList(); + } + Map children = new LinkedHashMap<>(); + findDeclarations(parent, monitor, (IEObjectDescription declaration, IReferenceDescription reference) -> { + IHierarchyNode childNode = createChild(children, declaration, parent); + if (childNode != null) { + IHierarchyNodeReference nodeReference = createNodeReference(reference); + if (nodeReference != null) { + childNode.getReferences().add(nodeReference); + } + } + }); + return children.values(); + } + + protected void findDeclarations(IHierarchyNode parent, IProgressMonitor monitor, + Procedure2 acceptor) { + if (hierarchyType != null) { + switch (hierarchyType) { + case CALLEE: + findTargetDeclarations(parent.getElement().getEObjectURI(), monitor, acceptor); + break; + default: + findSourceDeclarations(parent.getElement().getEObjectURI(), monitor, acceptor); + break; + } + } else { + findSourceDeclarations(parent.getElement().getEObjectURI(), monitor, acceptor); + } + } + + protected void findTargetDeclarations(URI sourceDeclarationURI, IProgressMonitor monitor, + Procedure2 acceptor) { + readOnly(sourceDeclarationURI, (EObject sourceDeclaration) -> { + ReferenceAcceptor referenceAcceptor = new ReferenceAcceptor(getResourceServiceProviderRegistry(), + reference -> { + if (filterReference(reference)) { + IEObjectDescription targetDeclaration = null; + if (reference != null) { + targetDeclaration = findTargetDeclaration(reference); + } + acceptor.apply(targetDeclaration, reference); + } + }); + getReferenceFinder().findAllReferences(sourceDeclaration, referenceAcceptor, monitor); + return null; + }); + } + + protected void findSourceDeclarations(URI targetDeclarationURI, IProgressMonitor monitor, + Procedure2 acceptor) { + TargetURIs targetURIs = collectTargetURIs(targetDeclarationURI); + ReferenceAcceptor referenceAcceptor = new ReferenceAcceptor(getResourceServiceProviderRegistry(), + reference -> { + if (filterReference(reference)) { + IEObjectDescription sourceDeclaration = null; + if (reference != null) { + sourceDeclaration = findSourceDeclaration(reference); + } + acceptor.apply(sourceDeclaration, reference); + } + }); + getReferenceFinder().findAllReferences(targetURIs, getResourceAccess(), getIndexData(), referenceAcceptor, + monitor); + } + + protected TargetURIs collectTargetURIs(URI targetURI) { + TargetURIs targetURIs = getTargetURIProvider().get(); + if (targetURI == null) { + return targetURIs; + } + readOnly(targetURI, (EObject targetObject) -> { + if (targetObject != null) { + getTargetURICollector().add(targetObject, targetURIs); + } + return null; + }); + return targetURIs; + } + + protected boolean filterReference(IReferenceDescription reference) { + return reference != null; + } + + protected IEObjectDescription findDeclaration(URI objectURI) { + return getDescription(objectURI); + } + + protected IEObjectDescription findTargetDeclaration(IReferenceDescription reference) { + return findDeclaration(reference.getTargetEObjectUri()); + } + + protected IEObjectDescription findSourceDeclaration(IReferenceDescription reference) { + return findDeclaration(reference.getContainerEObjectURI()); + } + + /** + * @return a root hierarchy node for the given declaration; cannot be null + */ + protected IHierarchyNode createRoot(IEObjectDescription declaration) { + DefaultHierarchyNode node = new DefaultHierarchyNode(); + node.setElement(declaration); + node.setMayHaveChildren(true); + return node; + } + + /** + * @return a child node for the given declaration and the parent node; cannot be null + */ + protected IHierarchyNode createChild(IEObjectDescription declaration, IHierarchyNode parent) { + DefaultHierarchyNode node = new DefaultHierarchyNode(); + node.setParent(parent); + node.setElement(declaration); + node.setMayHaveChildren(!node.isRecursive()); + return node; + } + + protected IHierarchyNode createChild(Map children, IEObjectDescription declaration, + IHierarchyNode parent) { + if (declaration == null) { + return null; + } + IHierarchyNode childNode = children.get(declaration.getEObjectURI()); + if (childNode == null) { + childNode = createChild(declaration, parent); + children.put(declaration.getEObjectURI(), childNode); + } + return childNode; + } + + /** + * @return a hierarchy node reference for the given reference; cannot be null + */ + protected IHierarchyNodeReference createNodeReference(IReferenceDescription reference) { + return readOnly(reference.getSourceEObjectUri(), (EObject sourceObject) -> { + ITextRegionWithLineInformation textRegion = getTextRegion(sourceObject, reference.getEReference(), + reference.getIndexInList()); + String text = getText(sourceObject, textRegion); + return new DefaultHierarchyNodeReference(text, textRegion, reference); + }); + } + + protected ITextRegionWithLineInformation getTextRegion(EObject obj, EReference reference, int indexInList) { + return getHierarchyNodeLocationProvider().getTextRegion(obj, reference, indexInList); + } + + protected String getText(EObject obj, ITextRegionWithLineInformation textRegion) { + if (obj == null || textRegion == ITextRegionWithLineInformation.EMPTY_REGION) { + return ""; + } + ICompositeNode node = NodeModelUtils.getNode(EcoreUtil.getRootContainer(obj)); + if (node == null) { + return ""; + } + int endOffset = textRegion.getOffset() + textRegion.getLength(); + return node.getRootNode().getText().substring(textRegion.getOffset(), endOffset); + } + + public ICallHierarchyBuilder.CallHierarchyType getHierarchyType() { + return hierarchyType; + } + + public void setHierarchyType(ICallHierarchyBuilder.CallHierarchyType hierarchyType) { + this.hierarchyType = hierarchyType; + } +} diff --git a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/hierarchy/DefaultCallHierarchyBuilder.xtend b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/hierarchy/DefaultCallHierarchyBuilder.xtend deleted file mode 100644 index 5322e2790..000000000 --- a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/editor/hierarchy/DefaultCallHierarchyBuilder.xtend +++ /dev/null @@ -1,206 +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.editor.hierarchy - -import java.util.Map -import org.eclipse.core.runtime.IProgressMonitor -import org.eclipse.emf.common.util.URI -import org.eclipse.emf.ecore.EObject -import org.eclipse.emf.ecore.EReference -import org.eclipse.xtend.lib.annotations.Accessors -import org.eclipse.xtext.findReferences.ReferenceAcceptor -import org.eclipse.xtext.findReferences.TargetURIs -import org.eclipse.xtext.resource.IEObjectDescription -import org.eclipse.xtext.resource.IReferenceDescription -import org.eclipse.xtext.util.ITextRegionWithLineInformation - -import static extension org.eclipse.emf.ecore.util.EcoreUtil.* -import static extension org.eclipse.xtext.nodemodel.util.NodeModelUtils.* - -/** - *

- * Default implementation of a call hierarchy builder. - *

- * - * @author kosyakov - Initial contribution and API - * @since 2.10 - */ -class DefaultCallHierarchyBuilder extends AbstractHierarchyBuilder implements ICallHierarchyBuilder { - - @Accessors - CallHierarchyType hierarchyType = CallHierarchyType.CALLER - - override buildRoots(URI rootURI, IProgressMonitor monitor) { - val rootDeclaration = rootURI.findDeclaration - if(rootDeclaration === null) return emptyList - return #[rootDeclaration.createRoot] - } - - override buildChildren(IHierarchyNode parent, IProgressMonitor monitor) { - if (!parent.mayHaveChildren) - return emptyList - - val children = newLinkedHashMap - findDeclarations(parent, monitor) [ declaration, reference | - val childNode = children.createChild(declaration, parent) - if (childNode !== null) { - val nodeReference = reference.createNodeReference - if (nodeReference !== null) - childNode.references += nodeReference - } - ] - return children.values - } - - protected def void findDeclarations( - IHierarchyNode parent, - IProgressMonitor monitor, - (IEObjectDescription, IReferenceDescription)=>void acceptor - ) { - switch hierarchyType { - case CALLEE: - findTargetDeclarations(parent.element.EObjectURI, monitor, acceptor) - default: - findSourceDeclarations(parent.element.EObjectURI, monitor, acceptor) - } - } - - protected def void findTargetDeclarations( - URI sourceDeclarationURI, - IProgressMonitor monitor, - (IEObjectDescription, IReferenceDescription)=>void acceptor - ) { - readOnly(sourceDeclarationURI) [ sourceDeclaration | - referenceFinder.findAllReferences( - sourceDeclaration, - new ReferenceAcceptor(resourceServiceProviderRegistry) [ reference | - if (reference.filterReference) { - val targetDeclaration = reference?.findTargetDeclaration - acceptor.apply(targetDeclaration, reference) - } - ], - monitor - ) - null - ] - } - - protected def void findSourceDeclarations( - URI targetDeclarationURI, - IProgressMonitor monitor, - (IEObjectDescription, IReferenceDescription)=>void acceptor - ) { - val targetURIs = targetDeclarationURI.collectTargetURIs - referenceFinder.findAllReferences( - targetURIs, - resourceAccess, - indexData, - new ReferenceAcceptor(resourceServiceProviderRegistry) [ reference | - if (reference.filterReference) { - val sourceDeclaration = reference?.findSourceDeclaration - acceptor.apply(sourceDeclaration, reference) - } - ], - monitor - ) - } - - protected def TargetURIs collectTargetURIs(URI targetURI) { - val targetURIs = targetURIProvider.get - if(targetURI === null) return targetURIs - - readOnly(targetURI) [ targetObject | - if(targetObject !== null) { - targetURICollector.add(targetObject, targetURIs) - } - return null - ] - return targetURIs - } - - protected def boolean filterReference(IReferenceDescription reference) { - reference !== null - } - - protected def IEObjectDescription findDeclaration(URI objectURI) { - return objectURI.description - } - - protected def IEObjectDescription findTargetDeclaration(IReferenceDescription reference) { - return reference.targetEObjectUri.findDeclaration - } - - protected def IEObjectDescription findSourceDeclaration(IReferenceDescription reference) { - return reference.containerEObjectURI.findDeclaration - } - - /** - * @return a root hierarchy node for the given declaration; cannot be null - */ - protected def IHierarchyNode createRoot(IEObjectDescription declaration) { - val node = new DefaultHierarchyNode - node.element = declaration - node.mayHaveChildren = true - return node - } - - /** - * @return a child node for the given declaration and the parent node; cannot be null - */ - protected def IHierarchyNode createChild(IEObjectDescription declaration, IHierarchyNode parent) { - val node = new DefaultHierarchyNode - node.parent = parent - node.element = declaration - node.mayHaveChildren = !node.recursive - return node - } - - protected def IHierarchyNode createChild( - Map children, - IEObjectDescription declaration, - IHierarchyNode parent - ) { - if(declaration === null) return null; - - var childNode = children.get(declaration.EObjectURI) - if (childNode === null) { - childNode = createChild(declaration, parent) - children.put(declaration.EObjectURI, childNode) - } - return childNode - } - - /** - * @return a hierarchy node reference for the given reference; cannot be null - */ - protected def IHierarchyNodeReference createNodeReference(IReferenceDescription reference) { - return readOnly(reference.sourceEObjectUri) [ sourceObject | - val textRegion = sourceObject.getTextRegion(reference.EReference, reference.indexInList) - val text = sourceObject.getText(textRegion) - return new DefaultHierarchyNodeReference(text, textRegion, reference) - ] - } - - protected def ITextRegionWithLineInformation getTextRegion(EObject obj, EReference reference, int indexInList) { - return hierarchyNodeLocationProvider.getTextRegion(obj, reference, indexInList) - } - - protected def String getText(EObject obj, ITextRegionWithLineInformation textRegion) { - if (obj === null || textRegion === ITextRegionWithLineInformation.EMPTY_REGION) - return '' - - val node = obj.rootContainer.node - if (node === null) - return '' - - val endOffset = textRegion.offset + textRegion.length - return node.rootNode.text.substring(textRegion.offset, endOffset) - } - -} diff --git a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/server/Document.java b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/server/Document.java new file mode 100644 index 000000000..bd6d4bf57 --- /dev/null +++ b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/server/Document.java @@ -0,0 +1,254 @@ +/** + * 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.server; + +import org.eclipse.lsp4j.DidChangeTextDocumentParams; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.TextDocumentContentChangeEvent; +import org.eclipse.lsp4j.TextEdit; +import org.eclipse.xtext.xbase.lib.util.ToStringBuilder; + +/** + * @author Sven Efftinge - Initial contribution and API + * @since 2.11 + */ +public class Document { + private final Integer version; + + private final String contents; + + private final boolean printSourceOnError; + + public Document(Integer version, String contents) { + this(version, contents, true); + } + + /** + * @since 2.15 + */ + public Document(Integer version, String contents, boolean printSourceOnError) { + this.version = version; + this.contents = contents; + this.printSourceOnError = printSourceOnError; + } + + public int getOffSet(Position position) throws IndexOutOfBoundsException { + int l = contents.length(); + char NL = '\n'; + int line = 0; + int column = 0; + for (int i = 0; i < l; i++) { + char ch = contents.charAt(i); + if (position.getLine() == line && position.getCharacter() == column) { + return i; + } + if (ch == NL) { + line++; + column = 0; + } else { + column++; + } + } + if (position.getLine() == line && position.getCharacter() == column) { + return l; + } + throw new IndexOutOfBoundsException(position.toString() + getSourceOnError()); + } + + public Position getPosition(int offset) throws IndexOutOfBoundsException { + int l = contents.length(); + if (offset < 0 || offset > l) { + throw new IndexOutOfBoundsException(offset + getSourceOnError()); + } + char NL = '\n'; + int line = 0; + int column = 0; + for (int i = 0; i < l; i++) { + char ch = contents.charAt(i); + if (i == offset) { + return new Position(line, column); + } + if (ch == NL) { + line++; + column = 0; + } else { + column++; + } + } + return new Position(line, column); + } + + /** + * Returns with the text for a certain line without the trailing end line marker. Throws an + * {@link IndexOutOfBoundsException} if the zero-based {@code lineNumber} argument is negative or exceeds the number + * of lines in the document. + */ + public String getLineContent(int lineNumber) throws IndexOutOfBoundsException { + if (lineNumber < 0) { + throw new IndexOutOfBoundsException(lineNumber + getSourceOnError()); + } + char NL = '\n'; + char LF = '\r'; + int l = contents.length(); + StringBuilder lineContent = new StringBuilder(); + int line = 0; + for (int i = 0; i < l; i++) { + if (line > lineNumber) { + return lineContent.toString(); + } + char ch = contents.charAt(i); + if (line == lineNumber && ch != NL && ch != LF) { + lineContent.append(ch); + } + if (ch == NL) { + line++; + } + } + if (line < lineNumber) { + throw new IndexOutOfBoundsException(lineNumber + getSourceOnError()); + } + return lineContent.toString(); + } + + /** + * @since 2.22 + */ + protected String getSourceOnError() { + String source = ""; + if (isPrintSourceOnError()) { + source = " text was : " + contents; + } + return source; + } + + /** + * Get the number of lines in the document. Empty document has line count: {@code 1}. + */ + public int getLineCount() { + return getPosition(contents.length()).getLine() + 1; + } + + public String getSubstring(Range range) { + int start = getOffSet(range.getStart()); + int end = getOffSet(range.getEnd()); + return contents.substring(start, end); + } + + /** + * As opposed to {@link TextEdit}[] the positions in the edits of a {@link DidChangeTextDocumentParams} refer to the + * state after applying the preceding edits. See + * https://microsoft.github.io/language-server-protocol/specification#textedit-1 and + * https://github.com/microsoft/vscode/issues/23173#issuecomment-289378160 for details. + * + * @return a new document with an incremented version and the text document changes applied. + * @since 2.18 + */ + public Document applyTextDocumentChanges(Iterable changes) { + Document currentDocument = this; + Integer newVersion = null; + if (currentDocument.version != null) { + newVersion = Integer.valueOf(currentDocument.version.intValue() + 1); + } + for (TextDocumentContentChangeEvent change : changes) { + final String newContent; + if (change.getRange() == null) { + newContent = change.getText(); + } else { + int start = currentDocument.getOffSet(change.getRange().getStart()); + int end = currentDocument.getOffSet(change.getRange().getEnd()); + newContent = currentDocument.contents.substring(0, start) + change.getText() + + currentDocument.contents.substring(end); + } + currentDocument = new Document(newVersion, newContent, printSourceOnError); + } + return currentDocument; + } + + /** + * Only use for testing. + * + * All positions in the {@link TextEdit}s refer to the same original document (this). + */ + public Document applyChanges(Iterable changes) { + String newContent = contents; + for (TextEdit change : changes) { + if (change.getRange() == null) { + newContent = change.getNewText(); + } else { + int start = getOffSet(change.getRange().getStart()); + int end = getOffSet(change.getRange().getEnd()); + newContent = newContent.substring(0, start) + change.getNewText() + newContent.substring(end); + } + } + Integer newVersion = null; + if (version != null) { + newVersion = Integer.valueOf(version.intValue() + 1); + } + return new Document(newVersion, newContent); + } + + /** + * @since 2.15 + */ + public boolean isPrintSourceOnError() { + return printSourceOnError; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((contents == null) ? 0 : contents.hashCode()); + result = prime * result + (printSourceOnError ? 1231 : 1237); + result = prime * result + ((version == null) ? 0 : version.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Document other = (Document) obj; + if (contents == null) { + if (other.contents != null) + return false; + } else if (!contents.equals(other.contents)) + return false; + if (printSourceOnError != other.printSourceOnError) + return false; + if (version == null) { + if (other.version != null) + return false; + } else if (!version.equals(other.version)) + return false; + return true; + } + + @Override + public String toString() { + ToStringBuilder b = new ToStringBuilder(this); + b.add("version", version); + b.add("contents", contents); + b.add("printSourceOnError", printSourceOnError); + return b.toString(); + } + + public Integer getVersion() { + return version; + } + + public String getContents() { + return contents; + } +} diff --git a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/server/Document.xtend b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/server/Document.xtend deleted file mode 100644 index bd8fbd115..000000000 --- a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/server/Document.xtend +++ /dev/null @@ -1,186 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2019 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.server - -import org.eclipse.lsp4j.Position -import org.eclipse.lsp4j.TextEdit -import org.eclipse.xtend.lib.annotations.Data -import org.eclipse.lsp4j.DidChangeTextDocumentParams -import org.eclipse.lsp4j.Range -import org.eclipse.lsp4j.TextDocumentContentChangeEvent - -/** - * @author Sven Efftinge - Initial contribution and API - * @since 2.11 - */ -@Data class Document { - - Integer version - String contents - boolean printSourceOnError - - new(Integer version, String contents) { - this(version, contents, true) - } - - /** - * @since 2.15 - */ - new(Integer version, String contents, boolean printSourceOnError) { - this.version = version - this.contents = contents - this.printSourceOnError = printSourceOnError - } - - def int getOffSet(Position position) throws IndexOutOfBoundsException { - val l = contents.length - val char NL = '\n' - var line = 0 - var column = 0 - for (var i = 0; i < l; i++) { - val ch = contents.charAt(i) - if (position.line === line && position.character === column) { - return i - } - if (ch === NL) { - line++ - column = 0 - } else { - column++ - } - } - if (position.line === line && position.character === column) { - return l - } - throw new IndexOutOfBoundsException(position.toString + if (printSourceOnError) "" else (" text was : " + contents)) - } - - def Position getPosition(int offset) throws IndexOutOfBoundsException{ - val l = contents.length - if (offset < 0 || offset > l) - throw new IndexOutOfBoundsException(offset + if (printSourceOnError) "" else (" text was : " + contents)) - - val char NL = '\n' - var line = 0 - var column = 0 - for (var i = 0; i < l; i++) { - val ch = contents.charAt(i) - if (i === offset) { - return new Position(line, column) - } - if (ch === NL) { - line++ - column = 0 - } else { - column++ - } - } - return new Position(line, column) - } - - /** - * Returns with the text for a certain line without the trailing end line marker. Throws an {@link IndexOutOfBoundsException} if the zero-based {@code lineNumber} - * argument is negative or exceeds the number of lines in the document. - */ - def String getLineContent(int lineNumber) throws IndexOutOfBoundsException { - if (lineNumber < 0) { - throw new IndexOutOfBoundsException(lineNumber + if (printSourceOnError) "" else (" text was : " + contents)); - } - val char NL = '\n'; - val char LF = '\r'; - val l = contents.length; - val lineContent = new StringBuilder; - var line = 0; - for (var i = 0; i < l; i++) { - if (line > lineNumber) { - return lineContent.toString; - } - val ch = contents.charAt(i); - if (line === lineNumber && ch !== NL && ch !== LF) { - lineContent.append(ch); - } - if (ch === NL) { - line++; - } - } - if (line < lineNumber) { - throw new IndexOutOfBoundsException(lineNumber + if (printSourceOnError) "" else (" text was : " + contents)); - } - return lineContent.toString; - } - - /** - * Get the number of lines in the document. Empty document has line count: {@code 1}. - */ - def int getLineCount() { - return getPosition(contents.length).line + 1; - } - - def String getSubstring(Range range) { - val start = getOffSet(range.start) - val end = getOffSet(range.end) - return this.contents.substring(start, end) - } - - /** - * As opposed to {@link TextEdit}[] the positions in the edits of a - * {@link DidChangeTextDocumentParams} refer to the state after applying the preceding edits. See - * https://microsoft.github.io/language-server-protocol/specification#textedit-1 and - * https://github.com/microsoft/vscode/issues/23173#issuecomment-289378160 for details. - * - * @return a new document with an incremented version and the text document changes applied. - * @since 2.18 - */ - def Document applyTextDocumentChanges(Iterable changes) { - var currentDocument = this - val newVersion = if (currentDocument.version !== null) - currentDocument.version + 1 - else - null - for (change : changes) { - val newContent = if (change.range === null) { - change.text - } else { - val start = currentDocument.getOffSet(change.range.start) - val end = currentDocument.getOffSet(change.range.end) - currentDocument.contents.substring(0, start) + change.text + currentDocument.contents.substring(end) - } - currentDocument = new Document(newVersion, newContent, printSourceOnError) - } - return currentDocument - } - - /** - * Only use for testing. - * - * All positions in the {@link TextEdit}s refer to the same original document (this). - */ - def Document applyChanges(Iterable changes) { - var newContent = contents - for (change : changes) { - if (change.range === null) { - newContent = change.newText - } else { - val start = getOffSet(change.range.start) - val end = getOffSet(change.range.end) - newContent = newContent.substring(0, start) + change.newText + newContent.substring(end) - } - } - return new Document(if (version !== null) version + 1 else null, newContent) - } - - /** - * @since 2.15 - */ - @Pure - def boolean isPrintSourceOnError() { - printSourceOnError - } - -} diff --git a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/server/TopologicalSorter.java b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/server/TopologicalSorter.java new file mode 100644 index 000000000..ef1b4ace0 --- /dev/null +++ b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/server/TopologicalSorter.java @@ -0,0 +1,89 @@ +/** + * 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.server; + +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; + +import org.eclipse.xtext.resource.impl.ProjectDescription; +import org.eclipse.xtext.util.IAcceptor; +import org.eclipse.xtext.xbase.lib.Procedures.Procedure1; + +import com.google.common.collect.Lists; + +/** + * @author Jan Koehnlein - Initial contribution and API + * @since 2.11 + */ +public class TopologicalSorter { + protected static class Entry { + private final ProjectDescription description; + + private boolean marked; + + private boolean cyclic; + + @Override + public String toString() { + return description.getName(); + } + + public Entry(ProjectDescription description) { + this.description = description; + } + } + + private LinkedHashSet result; + + private Map name2entry; + + private IAcceptor cyclicAcceptor; + + public List sortByDependencies(Iterable descriptions, + Procedure1 cyclicAcceptor) { + this.cyclicAcceptor = cyclicAcceptor::apply; + name2entry = new LinkedHashMap<>(); + for (ProjectDescription project : descriptions) { + Entry entry = new TopologicalSorter.Entry(project); + name2entry.put(entry.description.getName(), entry); + } + result = new LinkedHashSet<>(); + name2entry.values().forEach(it -> visit(it)); + return Lists.newArrayList(result); + } + + protected boolean visit(TopologicalSorter.Entry current) { + if (!result.contains(current.description) && !current.cyclic) { + if (current.marked) { + markCyclic(current); + return false; + } + current.marked = true; + for (String it : current.description.getDependencies()) { + TopologicalSorter.Entry depEntry = name2entry.get(it); + if (depEntry != null && !visit(depEntry)) { + markCyclic(current); + return false; + } + } + current.marked = false; + result.add(current.description); + } + return true; + } + + protected void markCyclic(TopologicalSorter.Entry it) { + if (!it.cyclic) { + it.cyclic = true; + cyclicAcceptor.accept(it.description); + } + } +} diff --git a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/server/TopologicalSorter.xtend b/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/server/TopologicalSorter.xtend deleted file mode 100644 index 3ec1e81e1..000000000 --- a/org.eclipse.xtext.ide/src/org/eclipse/xtext/ide/server/TopologicalSorter.xtend +++ /dev/null @@ -1,75 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016 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.server - -import java.util.LinkedHashSet -import java.util.List -import java.util.Map -import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor -import org.eclipse.xtext.resource.impl.ProjectDescription -import org.eclipse.xtext.util.IAcceptor - -/** - * @author Jan Koehnlein - Initial contribution and API - * @since 2.11 - */ -class TopologicalSorter { - - LinkedHashSet result - Map name2entry - IAcceptor cyclicAcceptor - - def List sortByDependencies(Iterable descriptions, (ProjectDescription)=>void cyclicAcceptor) { - this.cyclicAcceptor = cyclicAcceptor - name2entry = descriptions.map[new Entry(it)].toMap[description.name] - result = newLinkedHashSet - name2entry.values.forEach [ - visit - ] - result.toList - } - - protected def boolean visit(Entry current) { - if(!result.contains(current.description) && !current.cyclic) { - if(current.marked) { - current.markCyclic - return false - } - current.marked = true - for(it: current.description.dependencies) { - val depEntry = name2entry.get(it) - if(depEntry !== null && !depEntry.visit) { - current.markCyclic - return false - } - } - current.marked = false - result.add(current.description) - } - return true - } - - protected def markCyclic(Entry it) { - if(!cyclic) { - cyclic = true - cyclicAcceptor.accept(description) - } - } - - @FinalFieldsConstructor - protected static class Entry { - val ProjectDescription description - boolean marked - boolean cyclic - - override toString() { - description.name - } - } -} \ No newline at end of file diff --git a/org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/editor/contentassist/FQNPrefixMatcher.java b/org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/editor/contentassist/FQNPrefixMatcher.java deleted file mode 100644 index dba28ee42..000000000 --- a/org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/editor/contentassist/FQNPrefixMatcher.java +++ /dev/null @@ -1,102 +0,0 @@ -/** - * Copyright (c) 2016 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.editor.contentassist; - -import com.google.inject.Inject; -import java.util.List; -import org.eclipse.xtend.lib.annotations.Accessors; -import org.eclipse.xtext.ide.editor.contentassist.IPrefixMatcher; -import org.eclipse.xtext.naming.IQualifiedNameConverter; -import org.eclipse.xtext.util.Strings; -import org.eclipse.xtext.xbase.lib.Pure; -import org.eclipse.xtext.xbase.lib.StringExtensions; - -/** - * Prefix matcher for fully qualified names. - * - * @since 2.10 - * @noreference - */ -@SuppressWarnings("all") -public class FQNPrefixMatcher implements IPrefixMatcher { - @Accessors - @Inject - private IPrefixMatcher.IgnoreCase delegate; - - @Inject - private IQualifiedNameConverter qualifiedNameConverter; - - @Override - public boolean isCandidateMatchingPrefix(final String name, final String prefix) { - boolean _isCandidateMatchingPrefix = this.delegate.isCandidateMatchingPrefix(name, prefix); - if (_isCandidateMatchingPrefix) { - return true; - } - final String delimiter = this.getDelimiter(); - if (((!StringExtensions.isNullOrEmpty(delimiter)) && (name.indexOf(delimiter) >= 0))) { - int _indexOf = prefix.indexOf(delimiter); - boolean _lessThan = (_indexOf < 0); - if (_lessThan) { - final String lastSegment = this.getLastSegment(name, delimiter); - if (((lastSegment != null) && this.delegate.isCandidateMatchingPrefix(lastSegment, prefix))) { - return true; - } - } else { - final List splitPrefix = Strings.split(prefix, delimiter); - boolean _isEmpty = splitPrefix.isEmpty(); - if (_isEmpty) { - return false; - } - final List splitName = Strings.split(name, delimiter); - int _size = splitName.size(); - int _size_1 = splitPrefix.size(); - boolean _lessThan_1 = (_size < _size_1); - if (_lessThan_1) { - return false; - } - for (int i = 0; (i < splitPrefix.size()); i++) { - boolean _isCandidateMatchingPrefix_1 = this.delegate.isCandidateMatchingPrefix(splitName.get(i), splitPrefix.get(i)); - boolean _not = (!_isCandidateMatchingPrefix_1); - if (_not) { - return false; - } - } - return true; - } - } - return false; - } - - protected String getLastSegment(final String fqn, final String delimiter) { - final int lastDelimIndex = fqn.lastIndexOf(delimiter); - if (((lastDelimIndex >= 0) && ((lastDelimIndex + delimiter.length()) < fqn.length()))) { - int _length = delimiter.length(); - int _plus = (lastDelimIndex + _length); - return fqn.substring(_plus); - } - return null; - } - - public String getDelimiter() { - if ((this.qualifiedNameConverter instanceof IQualifiedNameConverter.DefaultImpl)) { - return ((IQualifiedNameConverter.DefaultImpl)this.qualifiedNameConverter).getDelimiter(); - } else { - return "."; - } - } - - @Pure - public IPrefixMatcher.IgnoreCase getDelegate() { - return this.delegate; - } - - public void setDelegate(final IPrefixMatcher.IgnoreCase delegate) { - this.delegate = delegate; - } -} diff --git a/org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/editor/contentassist/IdeContentProposalProvider.java b/org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/editor/contentassist/IdeContentProposalProvider.java deleted file mode 100644 index 0b36c92d9..000000000 --- a/org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/editor/contentassist/IdeContentProposalProvider.java +++ /dev/null @@ -1,236 +0,0 @@ -/** - * Copyright (c) 2015, 2016 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.editor.contentassist; - -import com.google.common.base.Objects; -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.collect.ImmutableList; -import com.google.inject.Inject; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import org.eclipse.emf.ecore.EClass; -import org.eclipse.emf.ecore.EClassifier; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.ecore.EReference; -import org.eclipse.xtend.lib.annotations.AccessorType; -import org.eclipse.xtend.lib.annotations.Accessors; -import org.eclipse.xtext.AbstractElement; -import org.eclipse.xtext.AbstractRule; -import org.eclipse.xtext.Assignment; -import org.eclipse.xtext.CrossReference; -import org.eclipse.xtext.GrammarUtil; -import org.eclipse.xtext.Keyword; -import org.eclipse.xtext.RuleCall; -import org.eclipse.xtext.TerminalRule; -import org.eclipse.xtext.ide.editor.contentassist.ContentAssistContext; -import org.eclipse.xtext.ide.editor.contentassist.ContentAssistEntry; -import org.eclipse.xtext.ide.editor.contentassist.IIdeContentProposalAcceptor; -import org.eclipse.xtext.ide.editor.contentassist.IdeContentProposalCreator; -import org.eclipse.xtext.ide.editor.contentassist.IdeContentProposalPriorities; -import org.eclipse.xtext.ide.editor.contentassist.IdeCrossrefProposalProvider; -import org.eclipse.xtext.naming.IQualifiedNameConverter; -import org.eclipse.xtext.resource.IEObjectDescription; -import org.eclipse.xtext.scoping.IScope; -import org.eclipse.xtext.scoping.IScopeProvider; -import org.eclipse.xtext.util.TextRegion; -import org.eclipse.xtext.xbase.lib.Extension; -import org.eclipse.xtext.xbase.lib.Procedures.Procedure1; -import org.eclipse.xtext.xbase.lib.Pure; -import org.eclipse.xtext.xtext.CurrentTypeFinder; - -/** - * Generic content proposal provider for use in different IDE contexts. This provider is - * not used by the Eclipse integration, which has its own abstraction for - * content assist proposals. - * @noreference - */ -@SuppressWarnings("all") -public class IdeContentProposalProvider { - @Accessors(AccessorType.PROTECTED_GETTER) - @Inject - private IScopeProvider scopeProvider; - - @Accessors(AccessorType.PROTECTED_GETTER) - @Inject - private IQualifiedNameConverter qualifiedNameConverter; - - @Accessors(AccessorType.PROTECTED_GETTER) - @Inject - private IdeCrossrefProposalProvider crossrefProposalProvider; - - @Accessors(AccessorType.PROTECTED_GETTER) - @Inject - private IdeContentProposalCreator proposalCreator; - - @Accessors(AccessorType.PROTECTED_GETTER) - @Inject - private IdeContentProposalPriorities proposalPriorities; - - @Inject - @Extension - private CurrentTypeFinder _currentTypeFinder; - - /** - * Create content assist proposals and pass them to the given acceptor. - */ - public void createProposals(final Collection contexts, final IIdeContentProposalAcceptor acceptor) { - Iterable _filteredContexts = this.getFilteredContexts(contexts); - for (final ContentAssistContext context : _filteredContexts) { - ImmutableList _firstSetGrammarElements = context.getFirstSetGrammarElements(); - for (final AbstractElement element : _firstSetGrammarElements) { - { - boolean _canAcceptMoreProposals = acceptor.canAcceptMoreProposals(); - boolean _not = (!_canAcceptMoreProposals); - if (_not) { - return; - } - this.createProposals(element, context, acceptor); - } - } - } - } - - protected Iterable getFilteredContexts(final Collection contexts) { - return contexts; - } - - protected void _createProposals(final AbstractElement element, final ContentAssistContext context, final IIdeContentProposalAcceptor acceptor) { - } - - protected void _createProposals(final Assignment assignment, final ContentAssistContext context, final IIdeContentProposalAcceptor acceptor) { - final AbstractElement terminal = assignment.getTerminal(); - if ((terminal instanceof CrossReference)) { - this.createProposals(terminal, context, acceptor); - } else { - if ((terminal instanceof RuleCall)) { - final AbstractRule rule = ((RuleCall)terminal).getRule(); - if (((rule instanceof TerminalRule) && context.getPrefix().isEmpty())) { - String _xifexpression = null; - String _name = rule.getName(); - boolean _equals = Objects.equal(_name, "STRING"); - if (_equals) { - String _feature = assignment.getFeature(); - String _plus = ("\"" + _feature); - _xifexpression = (_plus + "\""); - } else { - _xifexpression = assignment.getFeature(); - } - final String proposal = _xifexpression; - final Procedure1 _function = (ContentAssistEntry it) -> { - String _name_1 = rule.getName(); - boolean _equals_1 = Objects.equal(_name_1, "STRING"); - if (_equals_1) { - List _editPositions = it.getEditPositions(); - int _offset = context.getOffset(); - int _plus_1 = (_offset + 1); - int _length = proposal.length(); - int _minus = (_length - 2); - TextRegion _textRegion = new TextRegion(_plus_1, _minus); - _editPositions.add(_textRegion); - it.setKind(ContentAssistEntry.KIND_TEXT); - } else { - List _editPositions_1 = it.getEditPositions(); - int _offset_1 = context.getOffset(); - int _length_1 = proposal.length(); - TextRegion _textRegion_1 = new TextRegion(_offset_1, _length_1); - _editPositions_1.add(_textRegion_1); - it.setKind(ContentAssistEntry.KIND_VALUE); - } - it.setDescription(rule.getName()); - }; - final ContentAssistEntry entry = this.proposalCreator.createProposal(proposal, context, _function); - acceptor.accept(entry, this.proposalPriorities.getDefaultPriority(entry)); - } - } - } - } - - protected void _createProposals(final Keyword keyword, final ContentAssistContext context, final IIdeContentProposalAcceptor acceptor) { - boolean _filterKeyword = this.filterKeyword(keyword, context); - if (_filterKeyword) { - final ContentAssistEntry entry = this.proposalCreator.createProposal(keyword.getValue(), context, ContentAssistEntry.KIND_KEYWORD, null); - if ((entry != null)) { - acceptor.accept(entry, this.proposalPriorities.getKeywordPriority(keyword.getValue(), entry)); - } - } - } - - protected boolean filterKeyword(final Keyword keyword, final ContentAssistContext context) { - return true; - } - - protected void _createProposals(final RuleCall ruleCall, final ContentAssistContext context, final IIdeContentProposalAcceptor acceptor) { - } - - protected void _createProposals(final CrossReference reference, final ContentAssistContext context, final IIdeContentProposalAcceptor acceptor) { - final EClassifier type = this._currentTypeFinder.findCurrentTypeAfter(reference); - if ((type instanceof EClass)) { - final EReference ereference = GrammarUtil.getReference(reference, ((EClass)type)); - final EObject currentModel = context.getCurrentModel(); - if (((ereference != null) && (currentModel != null))) { - final IScope scope = this.scopeProvider.getScope(currentModel, ereference); - this.crossrefProposalProvider.lookupCrossReference(scope, reference, context, acceptor, - this.getCrossrefFilter(reference, context)); - } - } - } - - protected Predicate getCrossrefFilter(final CrossReference reference, final ContentAssistContext context) { - return Predicates.alwaysTrue(); - } - - protected void createProposals(final AbstractElement assignment, final ContentAssistContext context, final IIdeContentProposalAcceptor acceptor) { - if (assignment instanceof Assignment) { - _createProposals((Assignment)assignment, context, acceptor); - return; - } else if (assignment instanceof CrossReference) { - _createProposals((CrossReference)assignment, context, acceptor); - return; - } else if (assignment instanceof Keyword) { - _createProposals((Keyword)assignment, context, acceptor); - return; - } else if (assignment instanceof RuleCall) { - _createProposals((RuleCall)assignment, context, acceptor); - return; - } else if (assignment != null) { - _createProposals(assignment, context, acceptor); - return; - } else { - throw new IllegalArgumentException("Unhandled parameter types: " + - Arrays.asList(assignment, context, acceptor).toString()); - } - } - - @Pure - protected IScopeProvider getScopeProvider() { - return this.scopeProvider; - } - - @Pure - protected IQualifiedNameConverter getQualifiedNameConverter() { - return this.qualifiedNameConverter; - } - - @Pure - protected IdeCrossrefProposalProvider getCrossrefProposalProvider() { - return this.crossrefProposalProvider; - } - - @Pure - protected IdeContentProposalCreator getProposalCreator() { - return this.proposalCreator; - } - - @Pure - protected IdeContentProposalPriorities getProposalPriorities() { - return this.proposalPriorities; - } -} diff --git a/org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/editor/hierarchy/DefaultCallHierarchyBuilder.java b/org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/editor/hierarchy/DefaultCallHierarchyBuilder.java deleted file mode 100644 index 3be7df09f..000000000 --- a/org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/editor/hierarchy/DefaultCallHierarchyBuilder.java +++ /dev/null @@ -1,255 +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.editor.hierarchy; - -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.emf.common.util.URI; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.ecore.EReference; -import org.eclipse.emf.ecore.util.EcoreUtil; -import org.eclipse.xtend.lib.annotations.Accessors; -import org.eclipse.xtext.findReferences.IReferenceFinder; -import org.eclipse.xtext.findReferences.ReferenceAcceptor; -import org.eclipse.xtext.findReferences.TargetURIs; -import org.eclipse.xtext.ide.editor.hierarchy.AbstractHierarchyBuilder; -import org.eclipse.xtext.ide.editor.hierarchy.DefaultHierarchyNode; -import org.eclipse.xtext.ide.editor.hierarchy.DefaultHierarchyNodeReference; -import org.eclipse.xtext.ide.editor.hierarchy.ICallHierarchyBuilder; -import org.eclipse.xtext.ide.editor.hierarchy.IHierarchyNode; -import org.eclipse.xtext.ide.editor.hierarchy.IHierarchyNodeReference; -import org.eclipse.xtext.nodemodel.ICompositeNode; -import org.eclipse.xtext.nodemodel.util.NodeModelUtils; -import org.eclipse.xtext.resource.IEObjectDescription; -import org.eclipse.xtext.resource.IReferenceDescription; -import org.eclipse.xtext.resource.IResourceDescriptions; -import org.eclipse.xtext.resource.IResourceServiceProvider; -import org.eclipse.xtext.util.IAcceptor; -import org.eclipse.xtext.util.ITextRegionWithLineInformation; -import org.eclipse.xtext.util.concurrent.IUnitOfWork; -import org.eclipse.xtext.xbase.lib.CollectionLiterals; -import org.eclipse.xtext.xbase.lib.Procedures.Procedure2; -import org.eclipse.xtext.xbase.lib.Pure; - -/** - *

- * Default implementation of a call hierarchy builder. - *

- * - * @author kosyakov - Initial contribution and API - * @since 2.10 - */ -@SuppressWarnings("all") -public class DefaultCallHierarchyBuilder extends AbstractHierarchyBuilder implements ICallHierarchyBuilder { - @Accessors - private ICallHierarchyBuilder.CallHierarchyType hierarchyType = ICallHierarchyBuilder.CallHierarchyType.CALLER; - - @Override - public Collection buildRoots(final URI rootURI, final IProgressMonitor monitor) { - final IEObjectDescription rootDeclaration = this.findDeclaration(rootURI); - if ((rootDeclaration == null)) { - return CollectionLiterals.emptyList(); - } - IHierarchyNode _createRoot = this.createRoot(rootDeclaration); - return Collections.unmodifiableList(CollectionLiterals.newArrayList(_createRoot)); - } - - @Override - public Collection buildChildren(final IHierarchyNode parent, final IProgressMonitor monitor) { - boolean _mayHaveChildren = parent.mayHaveChildren(); - boolean _not = (!_mayHaveChildren); - if (_not) { - return CollectionLiterals.emptyList(); - } - final LinkedHashMap children = CollectionLiterals.newLinkedHashMap(); - final Procedure2 _function = (IEObjectDescription declaration, IReferenceDescription reference) -> { - final IHierarchyNode childNode = this.createChild(children, declaration, parent); - if ((childNode != null)) { - final IHierarchyNodeReference nodeReference = this.createNodeReference(reference); - if ((nodeReference != null)) { - Collection _references = childNode.getReferences(); - _references.add(nodeReference); - } - } - }; - this.findDeclarations(parent, monitor, _function); - return children.values(); - } - - protected void findDeclarations(final IHierarchyNode parent, final IProgressMonitor monitor, final Procedure2 acceptor) { - final ICallHierarchyBuilder.CallHierarchyType hierarchyType = this.hierarchyType; - if (hierarchyType != null) { - switch (hierarchyType) { - case CALLEE: - this.findTargetDeclarations(parent.getElement().getEObjectURI(), monitor, acceptor); - break; - default: - this.findSourceDeclarations(parent.getElement().getEObjectURI(), monitor, acceptor); - break; - } - } else { - this.findSourceDeclarations(parent.getElement().getEObjectURI(), monitor, acceptor); - } - } - - protected void findTargetDeclarations(final URI sourceDeclarationURI, final IProgressMonitor monitor, final Procedure2 acceptor) { - final IUnitOfWork _function = (EObject sourceDeclaration) -> { - Object _xblockexpression = null; - { - IReferenceFinder _referenceFinder = this.getReferenceFinder(); - IResourceServiceProvider.Registry _resourceServiceProviderRegistry = this.getResourceServiceProviderRegistry(); - final IAcceptor _function_1 = (IReferenceDescription reference) -> { - boolean _filterReference = this.filterReference(reference); - if (_filterReference) { - IEObjectDescription _findTargetDeclaration = null; - if (reference!=null) { - _findTargetDeclaration=this.findTargetDeclaration(reference); - } - final IEObjectDescription targetDeclaration = _findTargetDeclaration; - acceptor.apply(targetDeclaration, reference); - } - }; - ReferenceAcceptor _referenceAcceptor = new ReferenceAcceptor(_resourceServiceProviderRegistry, _function_1); - _referenceFinder.findAllReferences(sourceDeclaration, _referenceAcceptor, monitor); - _xblockexpression = null; - } - return _xblockexpression; - }; - this.readOnly(sourceDeclarationURI, _function); - } - - protected void findSourceDeclarations(final URI targetDeclarationURI, final IProgressMonitor monitor, final Procedure2 acceptor) { - final TargetURIs targetURIs = this.collectTargetURIs(targetDeclarationURI); - IReferenceFinder _referenceFinder = this.getReferenceFinder(); - IReferenceFinder.IResourceAccess _resourceAccess = this.getResourceAccess(); - IResourceDescriptions _indexData = this.getIndexData(); - IResourceServiceProvider.Registry _resourceServiceProviderRegistry = this.getResourceServiceProviderRegistry(); - final IAcceptor _function = (IReferenceDescription reference) -> { - boolean _filterReference = this.filterReference(reference); - if (_filterReference) { - IEObjectDescription _findSourceDeclaration = null; - if (reference!=null) { - _findSourceDeclaration=this.findSourceDeclaration(reference); - } - final IEObjectDescription sourceDeclaration = _findSourceDeclaration; - acceptor.apply(sourceDeclaration, reference); - } - }; - ReferenceAcceptor _referenceAcceptor = new ReferenceAcceptor(_resourceServiceProviderRegistry, _function); - _referenceFinder.findAllReferences(targetURIs, _resourceAccess, _indexData, _referenceAcceptor, monitor); - } - - protected TargetURIs collectTargetURIs(final URI targetURI) { - final TargetURIs targetURIs = this.getTargetURIProvider().get(); - if ((targetURI == null)) { - return targetURIs; - } - final IUnitOfWork _function = (EObject targetObject) -> { - if ((targetObject != null)) { - this.getTargetURICollector().add(targetObject, targetURIs); - } - return null; - }; - this.readOnly(targetURI, _function); - return targetURIs; - } - - protected boolean filterReference(final IReferenceDescription reference) { - return (reference != null); - } - - protected IEObjectDescription findDeclaration(final URI objectURI) { - return this.getDescription(objectURI); - } - - protected IEObjectDescription findTargetDeclaration(final IReferenceDescription reference) { - return this.findDeclaration(reference.getTargetEObjectUri()); - } - - protected IEObjectDescription findSourceDeclaration(final IReferenceDescription reference) { - return this.findDeclaration(reference.getContainerEObjectURI()); - } - - /** - * @return a root hierarchy node for the given declaration; cannot be null - */ - protected IHierarchyNode createRoot(final IEObjectDescription declaration) { - final DefaultHierarchyNode node = new DefaultHierarchyNode(); - node.setElement(declaration); - node.setMayHaveChildren(true); - return node; - } - - /** - * @return a child node for the given declaration and the parent node; cannot be null - */ - protected IHierarchyNode createChild(final IEObjectDescription declaration, final IHierarchyNode parent) { - final DefaultHierarchyNode node = new DefaultHierarchyNode(); - node.setParent(parent); - node.setElement(declaration); - boolean _isRecursive = node.isRecursive(); - boolean _not = (!_isRecursive); - node.setMayHaveChildren(_not); - return node; - } - - protected IHierarchyNode createChild(final Map children, final IEObjectDescription declaration, final IHierarchyNode parent) { - if ((declaration == null)) { - return null; - } - IHierarchyNode childNode = children.get(declaration.getEObjectURI()); - if ((childNode == null)) { - childNode = this.createChild(declaration, parent); - children.put(declaration.getEObjectURI(), childNode); - } - return childNode; - } - - /** - * @return a hierarchy node reference for the given reference; cannot be null - */ - protected IHierarchyNodeReference createNodeReference(final IReferenceDescription reference) { - final IUnitOfWork _function = (EObject sourceObject) -> { - final ITextRegionWithLineInformation textRegion = this.getTextRegion(sourceObject, reference.getEReference(), reference.getIndexInList()); - final String text = this.getText(sourceObject, textRegion); - return new DefaultHierarchyNodeReference(text, textRegion, reference); - }; - return this.readOnly(reference.getSourceEObjectUri(), _function); - } - - protected ITextRegionWithLineInformation getTextRegion(final EObject obj, final EReference reference, final int indexInList) { - return this.getHierarchyNodeLocationProvider().getTextRegion(obj, reference, indexInList); - } - - protected String getText(final EObject obj, final ITextRegionWithLineInformation textRegion) { - if (((obj == null) || (textRegion == ITextRegionWithLineInformation.EMPTY_REGION))) { - return ""; - } - final ICompositeNode node = NodeModelUtils.getNode(EcoreUtil.getRootContainer(obj)); - if ((node == null)) { - return ""; - } - int _offset = textRegion.getOffset(); - int _length = textRegion.getLength(); - final int endOffset = (_offset + _length); - return node.getRootNode().getText().substring(textRegion.getOffset(), endOffset); - } - - @Pure - public ICallHierarchyBuilder.CallHierarchyType getHierarchyType() { - return this.hierarchyType; - } - - public void setHierarchyType(final ICallHierarchyBuilder.CallHierarchyType hierarchyType) { - this.hierarchyType = hierarchyType; - } -} diff --git a/org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/server/Document.java b/org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/server/Document.java deleted file mode 100644 index 0785607f4..000000000 --- a/org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/server/Document.java +++ /dev/null @@ -1,312 +0,0 @@ -/** - * Copyright (c) 2016, 2019 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.server; - -import org.eclipse.lsp4j.DidChangeTextDocumentParams; -import org.eclipse.lsp4j.Position; -import org.eclipse.lsp4j.Range; -import org.eclipse.lsp4j.TextDocumentContentChangeEvent; -import org.eclipse.lsp4j.TextEdit; -import org.eclipse.xtend.lib.annotations.Data; -import org.eclipse.xtext.xbase.lib.Pure; -import org.eclipse.xtext.xbase.lib.util.ToStringBuilder; - -/** - * @author Sven Efftinge - Initial contribution and API - * @since 2.11 - */ -@Data -@SuppressWarnings("all") -public class Document { - private final Integer version; - - private final String contents; - - private final boolean printSourceOnError; - - public Document(final Integer version, final String contents) { - this(version, contents, true); - } - - /** - * @since 2.15 - */ - public Document(final Integer version, final String contents, final boolean printSourceOnError) { - this.version = version; - this.contents = contents; - this.printSourceOnError = printSourceOnError; - } - - public int getOffSet(final Position position) throws IndexOutOfBoundsException { - final int l = this.contents.length(); - final char NL = '\n'; - int line = 0; - int column = 0; - for (int i = 0; (i < l); i++) { - { - final char ch = this.contents.charAt(i); - if (((position.getLine() == line) && (position.getCharacter() == column))) { - return i; - } - if ((ch == NL)) { - line++; - column = 0; - } else { - column++; - } - } - } - if (((position.getLine() == line) && (position.getCharacter() == column))) { - return l; - } - String _string = position.toString(); - String _xifexpression = null; - if (this.printSourceOnError) { - _xifexpression = ""; - } else { - _xifexpression = (" text was : " + this.contents); - } - String _plus = (_string + _xifexpression); - throw new IndexOutOfBoundsException(_plus); - } - - public Position getPosition(final int offset) throws IndexOutOfBoundsException { - final int l = this.contents.length(); - if (((offset < 0) || (offset > l))) { - String _xifexpression = null; - if (this.printSourceOnError) { - _xifexpression = ""; - } else { - _xifexpression = (" text was : " + this.contents); - } - String _plus = (Integer.valueOf(offset) + _xifexpression); - throw new IndexOutOfBoundsException(_plus); - } - final char NL = '\n'; - int line = 0; - int column = 0; - for (int i = 0; (i < l); i++) { - { - final char ch = this.contents.charAt(i); - if ((i == offset)) { - return new Position(line, column); - } - if ((ch == NL)) { - line++; - column = 0; - } else { - column++; - } - } - } - return new Position(line, column); - } - - /** - * Returns with the text for a certain line without the trailing end line marker. Throws an {@link IndexOutOfBoundsException} if the zero-based {@code lineNumber} - * argument is negative or exceeds the number of lines in the document. - */ - public String getLineContent(final int lineNumber) throws IndexOutOfBoundsException { - if ((lineNumber < 0)) { - String _xifexpression = null; - if (this.printSourceOnError) { - _xifexpression = ""; - } else { - _xifexpression = (" text was : " + this.contents); - } - String _plus = (Integer.valueOf(lineNumber) + _xifexpression); - throw new IndexOutOfBoundsException(_plus); - } - final char NL = '\n'; - final char LF = '\r'; - final int l = this.contents.length(); - final StringBuilder lineContent = new StringBuilder(); - int line = 0; - for (int i = 0; (i < l); i++) { - { - if ((line > lineNumber)) { - return lineContent.toString(); - } - final char ch = this.contents.charAt(i); - if ((((line == lineNumber) && (ch != NL)) && (ch != LF))) { - lineContent.append(ch); - } - if ((ch == NL)) { - line++; - } - } - } - if ((line < lineNumber)) { - String _xifexpression_1 = null; - if (this.printSourceOnError) { - _xifexpression_1 = ""; - } else { - _xifexpression_1 = (" text was : " + this.contents); - } - String _plus_1 = (Integer.valueOf(lineNumber) + _xifexpression_1); - throw new IndexOutOfBoundsException(_plus_1); - } - return lineContent.toString(); - } - - /** - * Get the number of lines in the document. Empty document has line count: {@code 1}. - */ - public int getLineCount() { - int _line = this.getPosition(this.contents.length()).getLine(); - return (_line + 1); - } - - public String getSubstring(final Range range) { - final int start = this.getOffSet(range.getStart()); - final int end = this.getOffSet(range.getEnd()); - return this.contents.substring(start, end); - } - - /** - * As opposed to {@link TextEdit}[] the positions in the edits of a - * {@link DidChangeTextDocumentParams} refer to the state after applying the preceding edits. See - * https://microsoft.github.io/language-server-protocol/specification#textedit-1 and - * https://github.com/microsoft/vscode/issues/23173#issuecomment-289378160 for details. - * - * @return a new document with an incremented version and the text document changes applied. - * @since 2.18 - */ - public Document applyTextDocumentChanges(final Iterable changes) { - Document currentDocument = this; - Integer _xifexpression = null; - if ((currentDocument.version != null)) { - _xifexpression = Integer.valueOf(((currentDocument.version).intValue() + 1)); - } else { - _xifexpression = null; - } - final Integer newVersion = _xifexpression; - for (final TextDocumentContentChangeEvent change : changes) { - { - String _xifexpression_1 = null; - Range _range = change.getRange(); - boolean _tripleEquals = (_range == null); - if (_tripleEquals) { - _xifexpression_1 = change.getText(); - } else { - String _xblockexpression = null; - { - final int start = currentDocument.getOffSet(change.getRange().getStart()); - final int end = currentDocument.getOffSet(change.getRange().getEnd()); - String _substring = currentDocument.contents.substring(0, start); - String _text = change.getText(); - String _plus = (_substring + _text); - String _substring_1 = currentDocument.contents.substring(end); - _xblockexpression = (_plus + _substring_1); - } - _xifexpression_1 = _xblockexpression; - } - final String newContent = _xifexpression_1; - Document _document = new Document(newVersion, newContent, this.printSourceOnError); - currentDocument = _document; - } - } - return currentDocument; - } - - /** - * Only use for testing. - * - * All positions in the {@link TextEdit}s refer to the same original document (this). - */ - public Document applyChanges(final Iterable changes) { - String newContent = this.contents; - for (final TextEdit change : changes) { - Range _range = change.getRange(); - boolean _tripleEquals = (_range == null); - if (_tripleEquals) { - newContent = change.getNewText(); - } else { - final int start = this.getOffSet(change.getRange().getStart()); - final int end = this.getOffSet(change.getRange().getEnd()); - String _substring = newContent.substring(0, start); - String _newText = change.getNewText(); - String _plus = (_substring + _newText); - String _substring_1 = newContent.substring(end); - String _plus_1 = (_plus + _substring_1); - newContent = _plus_1; - } - } - Integer _xifexpression = null; - if ((this.version != null)) { - _xifexpression = Integer.valueOf(((this.version).intValue() + 1)); - } else { - _xifexpression = null; - } - return new Document(_xifexpression, newContent); - } - - /** - * @since 2.15 - */ - @Pure - public boolean isPrintSourceOnError() { - return this.printSourceOnError; - } - - @Override - @Pure - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((this.version== null) ? 0 : this.version.hashCode()); - result = prime * result + ((this.contents== null) ? 0 : this.contents.hashCode()); - return prime * result + (this.printSourceOnError ? 1231 : 1237); - } - - @Override - @Pure - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Document other = (Document) obj; - if (this.version == null) { - if (other.version != null) - return false; - } else if (!this.version.equals(other.version)) - return false; - if (this.contents == null) { - if (other.contents != null) - return false; - } else if (!this.contents.equals(other.contents)) - return false; - if (other.printSourceOnError != this.printSourceOnError) - return false; - return true; - } - - @Override - @Pure - public String toString() { - ToStringBuilder b = new ToStringBuilder(this); - b.add("version", this.version); - b.add("contents", this.contents); - b.add("printSourceOnError", this.printSourceOnError); - return b.toString(); - } - - @Pure - public Integer getVersion() { - return this.version; - } - - @Pure - public String getContents() { - return this.contents; - } -} diff --git a/org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/server/TopologicalSorter.java b/org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/server/TopologicalSorter.java deleted file mode 100644 index 879650f01..000000000 --- a/org.eclipse.xtext.ide/xtend-gen/org/eclipse/xtext/ide/server/TopologicalSorter.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright (c) 2016 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.server; - -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; -import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor; -import org.eclipse.xtext.resource.impl.ProjectDescription; -import org.eclipse.xtext.util.IAcceptor; -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.Procedures.Procedure1; - -/** - * @author Jan Koehnlein - Initial contribution and API - * @since 2.11 - */ -@SuppressWarnings("all") -public class TopologicalSorter { - @FinalFieldsConstructor - protected static class Entry { - private final ProjectDescription description; - - private boolean marked; - - private boolean cyclic; - - @Override - public String toString() { - return this.description.getName(); - } - - public Entry(final ProjectDescription description) { - super(); - this.description = description; - } - } - - private LinkedHashSet result; - - private Map name2entry; - - private IAcceptor cyclicAcceptor; - - public List sortByDependencies(final Iterable descriptions, final Procedure1 cyclicAcceptor) { - List _xblockexpression = null; - { - this.cyclicAcceptor = new IAcceptor() { - public void accept(ProjectDescription t) { - cyclicAcceptor.apply(t); - } - }; - final Function1 _function = (ProjectDescription it) -> { - return new TopologicalSorter.Entry(it); - }; - final Function1 _function_1 = (TopologicalSorter.Entry it) -> { - return it.description.getName(); - }; - this.name2entry = IterableExtensions.toMap(IterableExtensions.map(descriptions, _function), _function_1); - this.result = CollectionLiterals.newLinkedHashSet(); - final Consumer _function_2 = (TopologicalSorter.Entry it) -> { - this.visit(it); - }; - this.name2entry.values().forEach(_function_2); - _xblockexpression = IterableExtensions.toList(this.result); - } - return _xblockexpression; - } - - protected boolean visit(final TopologicalSorter.Entry current) { - if (((!this.result.contains(current.description)) && (!current.cyclic))) { - if (current.marked) { - this.markCyclic(current); - return false; - } - current.marked = true; - List _dependencies = current.description.getDependencies(); - for (final String it : _dependencies) { - { - final TopologicalSorter.Entry depEntry = this.name2entry.get(it); - if (((depEntry != null) && (!this.visit(depEntry)))) { - this.markCyclic(current); - return false; - } - } - } - current.marked = false; - this.result.add(current.description); - } - return true; - } - - protected void markCyclic(final TopologicalSorter.Entry it) { - if ((!it.cyclic)) { - it.cyclic = true; - this.cyclicAcceptor.accept(it.description); - } - } -} diff --git a/org.eclipse.xtext.testing/src/org/eclipse/xtext/testing/TextDocumentConfiguration.java b/org.eclipse.xtext.testing/src/org/eclipse/xtext/testing/TextDocumentConfiguration.java index b37b36a71..05b37d57b 100644 --- a/org.eclipse.xtext.testing/src/org/eclipse/xtext/testing/TextDocumentConfiguration.java +++ b/org.eclipse.xtext.testing/src/org/eclipse/xtext/testing/TextDocumentConfiguration.java @@ -8,6 +8,7 @@ */ package org.eclipse.xtext.testing; +import java.util.Collections; import java.util.Map; import org.eclipse.lsp4j.InitializeParams; @@ -15,7 +16,7 @@ import org.eclipse.xtext.xbase.lib.CollectionLiterals; import org.eclipse.xtext.xbase.lib.Procedures.Procedure1; public class TextDocumentConfiguration { - private Map filesInScope = CollectionLiterals.emptyMap(); + private Map filesInScope = Collections.emptyMap(); private String model; diff --git a/org.eclipse.xtext.testing/src/org/eclipse/xtext/testing/util/InMemoryURIHandler.java b/org.eclipse.xtext.testing/src/org/eclipse/xtext/testing/util/InMemoryURIHandler.java new file mode 100644 index 000000000..dbc822f83 --- /dev/null +++ b/org.eclipse.xtext.testing/src/org/eclipse/xtext/testing/util/InMemoryURIHandler.java @@ -0,0 +1,132 @@ +/** + * 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.testing.util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.resource.URIHandler; + +/** + * @noimplement + * @noreference + */ +public class InMemoryURIHandler implements URIHandler { + public static class InMemFile { + private final URI uri; + + private byte[] contents; + + private boolean exists; + + public OutputStream createOutputstream() { + return new ByteArrayOutputStream() { + @Override + public void close() throws IOException { + contents = toByteArray(); + exists = true; + } + }; + } + + public InputStream createInputStream() throws IOException { + if (contents == null || !exists) { + throw new IOException("File " + uri + " does not exist."); + } + return new ByteArrayInputStream(contents); + } + + public InMemFile(URI uri) { + this.uri = uri; + } + + public URI getUri() { + return uri; + } + + public byte[] getContents() { + return contents; + } + + public void setContents(byte[] contents) { + this.contents = contents; + } + + public boolean isExists() { + return exists; + } + + public void setExists(boolean exists) { + this.exists = exists; + } + } + + public static final String SCHEME = "inmemory"; + + private Map files = new HashMap<>(); + + @Override + public boolean canHandle(URI uri) { + return InMemoryURIHandler.SCHEME.equals(uri.scheme()); + } + + @Override + public Map contentDescription(URI uri, Map options) throws IOException { + return Collections.emptyMap(); + } + + @Override + public InputStream createInputStream(URI uri, Map options) throws IOException { + return getInMemoryFile(uri).createInputStream(); + } + + @Override + public OutputStream createOutputStream(URI uri, Map options) throws IOException { + return getInMemoryFile(uri).createOutputstream(); + } + + @Override + public void delete(URI uri, Map options) throws IOException { + getInMemoryFile(uri).exists = false; + } + + @Override + public boolean exists(URI uri, Map options) { + return getInMemoryFile(uri).exists; + } + + @Override + public Map getAttributes(URI uri, Map options) { + return Collections.emptyMap(); + } + + @Override + public void setAttributes(URI uri, Map attributes, Map options) throws IOException { + } + + public InMemFile getInMemoryFile(URI uri) { + InMemFile result = files.get(uri); + if (result == null) { + result = new InMemFile(uri); + files.put(uri, result); + } + return result; + } + + public Map getFiles() { + return files; + } +} diff --git a/org.eclipse.xtext.testing/src/org/eclipse/xtext/testing/util/InMemoryURIHandler.xtend b/org.eclipse.xtext.testing/src/org/eclipse/xtext/testing/util/InMemoryURIHandler.xtend deleted file mode 100644 index e249d243d..000000000 --- a/org.eclipse.xtext.testing/src/org/eclipse/xtext/testing/util/InMemoryURIHandler.xtend +++ /dev/null @@ -1,93 +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.testing.util - -import java.io.ByteArrayInputStream -import java.io.ByteArrayOutputStream -import java.io.IOException -import java.io.InputStream -import java.io.OutputStream -import java.util.Map -import org.eclipse.emf.common.util.URI -import org.eclipse.emf.ecore.resource.URIHandler -import org.eclipse.xtend.lib.annotations.Accessors -import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor - -/** - * @noimplement - * @noreference - */ -class InMemoryURIHandler implements URIHandler { - - @Accessors @FinalFieldsConstructor static class InMemFile { - val URI uri - byte[] contents - boolean exists - - def OutputStream createOutputstream() { - return new ByteArrayOutputStream() { - override close() throws IOException { - contents = toByteArray - exists = true - } - } - } - - def InputStream createInputStream() { - if (contents === null || !exists) { - throw new IOException("File " + uri + " does not exist.") - } - return new ByteArrayInputStream(contents) - } - } - - public final static String SCHEME = 'inmemory' - - @Accessors(PUBLIC_GETTER) Map files = newHashMap() - - override canHandle(URI uri) { - uri.scheme == SCHEME - } - - override contentDescription(URI uri, Map options) throws IOException { - emptyMap - } - - override createInputStream(URI uri, Map options) throws IOException { - uri.inMemoryFile.createInputStream - } - - override createOutputStream(URI uri, Map options) throws IOException { - return uri.inMemoryFile.createOutputstream - } - - override delete(URI uri, Map options) throws IOException { - uri.inMemoryFile.exists = false - } - - override exists(URI uri, Map options) { - uri.inMemoryFile.exists - } - - override getAttributes(URI uri, Map options) { - emptyMap - } - - override setAttributes(URI uri, Map attributes, Map options) throws IOException { - } - - def InMemFile getInMemoryFile(URI uri) { - var result = files.get(uri) - if (result === null) { - result = new InMemFile(uri) - files.put(uri, result) - } - return result - } -} diff --git a/org.eclipse.xtext.testing/xtend-gen/org/eclipse/xtext/testing/util/InMemoryURIHandler.java b/org.eclipse.xtext.testing/xtend-gen/org/eclipse/xtext/testing/util/InMemoryURIHandler.java deleted file mode 100644 index dcb725a9e..000000000 --- a/org.eclipse.xtext.testing/xtend-gen/org/eclipse/xtext/testing/util/InMemoryURIHandler.java +++ /dev/null @@ -1,152 +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.testing.util; - -import com.google.common.base.Objects; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Map; -import org.eclipse.emf.common.util.URI; -import org.eclipse.emf.ecore.resource.URIHandler; -import org.eclipse.xtend.lib.annotations.AccessorType; -import org.eclipse.xtend.lib.annotations.Accessors; -import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor; -import org.eclipse.xtext.xbase.lib.CollectionLiterals; -import org.eclipse.xtext.xbase.lib.Exceptions; -import org.eclipse.xtext.xbase.lib.Pure; - -/** - * @noimplement - * @noreference - */ -@SuppressWarnings("all") -public class InMemoryURIHandler implements URIHandler { - @Accessors - @FinalFieldsConstructor - public static class InMemFile { - private final URI uri; - - private byte[] contents; - - private boolean exists; - - public OutputStream createOutputstream() { - return new ByteArrayOutputStream() { - @Override - public void close() throws IOException { - InMemFile.this.contents = this.toByteArray(); - InMemFile.this.exists = true; - } - }; - } - - public InputStream createInputStream() { - try { - if (((this.contents == null) || (!this.exists))) { - throw new IOException((("File " + this.uri) + " does not exist.")); - } - return new ByteArrayInputStream(this.contents); - } catch (Throwable _e) { - throw Exceptions.sneakyThrow(_e); - } - } - - public InMemFile(final URI uri) { - super(); - this.uri = uri; - } - - @Pure - public URI getUri() { - return this.uri; - } - - @Pure - public byte[] getContents() { - return this.contents; - } - - public void setContents(final byte[] contents) { - this.contents = contents; - } - - @Pure - public boolean isExists() { - return this.exists; - } - - public void setExists(final boolean exists) { - this.exists = exists; - } - } - - public static final String SCHEME = "inmemory"; - - @Accessors(AccessorType.PUBLIC_GETTER) - private Map files = CollectionLiterals.newHashMap(); - - @Override - public boolean canHandle(final URI uri) { - String _scheme = uri.scheme(); - return Objects.equal(_scheme, InMemoryURIHandler.SCHEME); - } - - @Override - public Map contentDescription(final URI uri, final Map options) throws IOException { - return CollectionLiterals.emptyMap(); - } - - @Override - public InputStream createInputStream(final URI uri, final Map options) throws IOException { - return this.getInMemoryFile(uri).createInputStream(); - } - - @Override - public OutputStream createOutputStream(final URI uri, final Map options) throws IOException { - return this.getInMemoryFile(uri).createOutputstream(); - } - - @Override - public void delete(final URI uri, final Map options) throws IOException { - InMemoryURIHandler.InMemFile _inMemoryFile = this.getInMemoryFile(uri); - _inMemoryFile.exists = false; - } - - @Override - public boolean exists(final URI uri, final Map options) { - return this.getInMemoryFile(uri).exists; - } - - @Override - public Map getAttributes(final URI uri, final Map options) { - return CollectionLiterals.emptyMap(); - } - - @Override - public void setAttributes(final URI uri, final Map attributes, final Map options) throws IOException { - } - - public InMemoryURIHandler.InMemFile getInMemoryFile(final URI uri) { - InMemoryURIHandler.InMemFile result = this.files.get(uri); - if ((result == null)) { - InMemoryURIHandler.InMemFile _inMemFile = new InMemoryURIHandler.InMemFile(uri); - result = _inMemFile; - this.files.put(uri, result); - } - return result; - } - - @Pure - public Map getFiles() { - return this.files; - } -} diff --git a/org.eclipse.xtext.tests/generator/src/org/eclipse/xtext/tests/ImportURIScopingFragment2.java b/org.eclipse.xtext.tests/generator/src/org/eclipse/xtext/tests/ImportURIScopingFragment2.java new file mode 100644 index 000000000..d60634e2c --- /dev/null +++ b/org.eclipse.xtext.tests/generator/src/org/eclipse/xtext/tests/ImportURIScopingFragment2.java @@ -0,0 +1,37 @@ +/** + * 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.tests; + +import com.google.inject.Inject; +import org.eclipse.xtext.scoping.impl.ImportUriGlobalScopeProvider; +import org.eclipse.xtext.scoping.impl.SimpleLocalScopeProvider; +import org.eclipse.xtext.xbase.lib.Extension; +import org.eclipse.xtext.xtext.generator.model.TypeReference; +import org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2; +import org.eclipse.xtext.xtext.generator.xbase.XbaseUsageDetector; + +public class ImportURIScopingFragment2 extends ImportNamespacesScopingFragment2 { + @Inject + @Extension + private XbaseUsageDetector xbaseUsageDetector; + + @Override + public TypeReference getDelegateScopeProvider() { + if (xbaseUsageDetector.inheritsXbase(getLanguage().getGrammar())) { + return TypeReference.typeRef("org.eclipse.xtext.xbase.scoping.XImportSectionNamespaceScopeProvider"); + } else { + return TypeReference.typeRef(SimpleLocalScopeProvider.class); + } + } + + @Override + protected TypeReference getGlobalScopeProvider() { + return TypeReference.typeRef(ImportUriGlobalScopeProvider.class); + } +} diff --git a/org.eclipse.xtext.tests/generator/src/org/eclipse/xtext/tests/ImportURIScopingFragment2.xtend b/org.eclipse.xtext.tests/generator/src/org/eclipse/xtext/tests/ImportURIScopingFragment2.xtend deleted file mode 100644 index 3bb0b6ef6..000000000 --- a/org.eclipse.xtext.tests/generator/src/org/eclipse/xtext/tests/ImportURIScopingFragment2.xtend +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016 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.tests - -import com.google.inject.Inject -import org.eclipse.xtext.scoping.impl.ImportUriGlobalScopeProvider -import org.eclipse.xtext.scoping.impl.SimpleLocalScopeProvider -import org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2 -import org.eclipse.xtext.xtext.generator.xbase.XbaseUsageDetector - -import static extension org.eclipse.xtext.xtext.generator.model.TypeReference.* - -class ImportURIScopingFragment2 extends ImportNamespacesScopingFragment2 { - - @Inject extension XbaseUsageDetector - - override getDelegateScopeProvider() { - if (language.grammar.inheritsXbase) - 'org.eclipse.xtext.xbase.scoping.XImportSectionNamespaceScopeProvider'.typeRef - else - SimpleLocalScopeProvider.typeRef - } - - override protected getGlobalScopeProvider() { - ImportUriGlobalScopeProvider.typeRef - } - -} - \ No newline at end of file diff --git a/org.eclipse.xtext.tests/generator/xtend-gen/org/eclipse/xtext/tests/ImportURIScopingFragment2.java b/org.eclipse.xtext.tests/generator/xtend-gen/org/eclipse/xtext/tests/ImportURIScopingFragment2.java deleted file mode 100644 index dfe162389..000000000 --- a/org.eclipse.xtext.tests/generator/xtend-gen/org/eclipse/xtext/tests/ImportURIScopingFragment2.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2016 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.tests; - -import com.google.inject.Inject; -import org.eclipse.xtext.scoping.impl.ImportUriGlobalScopeProvider; -import org.eclipse.xtext.scoping.impl.SimpleLocalScopeProvider; -import org.eclipse.xtext.xbase.lib.Extension; -import org.eclipse.xtext.xtext.generator.model.TypeReference; -import org.eclipse.xtext.xtext.generator.scoping.ImportNamespacesScopingFragment2; -import org.eclipse.xtext.xtext.generator.xbase.XbaseUsageDetector; - -@SuppressWarnings("all") -public class ImportURIScopingFragment2 extends ImportNamespacesScopingFragment2 { - @Inject - @Extension - private XbaseUsageDetector _xbaseUsageDetector; - - @Override - public TypeReference getDelegateScopeProvider() { - TypeReference _xifexpression = null; - boolean _inheritsXbase = this._xbaseUsageDetector.inheritsXbase(this.getLanguage().getGrammar()); - if (_inheritsXbase) { - _xifexpression = TypeReference.typeRef("org.eclipse.xtext.xbase.scoping.XImportSectionNamespaceScopeProvider"); - } else { - _xifexpression = TypeReference.typeRef(SimpleLocalScopeProvider.class); - } - return _xifexpression; - } - - @Override - protected TypeReference getGlobalScopeProvider() { - return TypeReference.typeRef(ImportUriGlobalScopeProvider.class); - } -} diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/formatting2/internal/FormatterTesterWithImpl.java b/org.eclipse.xtext.tests/src/org/eclipse/xtext/formatting2/internal/FormatterTesterWithImpl.java index 263086980..837074a3d 100644 --- a/org.eclipse.xtext.tests/src/org/eclipse/xtext/formatting2/internal/FormatterTesterWithImpl.java +++ b/org.eclipse.xtext.tests/src/org/eclipse/xtext/formatting2/internal/FormatterTesterWithImpl.java @@ -9,7 +9,6 @@ package org.eclipse.xtext.formatting2.internal; import org.eclipse.xtext.formatting2.IFormatter2; -import org.eclipse.xtext.formatting2.internal.GenericFormatterTestRequest; import org.eclipse.xtext.testing.formatter.FormatterTestHelper; import org.eclipse.xtext.testing.formatter.FormatterTestRequest; diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/formatting2/internal/GenericFormatterTestRequest.java b/org.eclipse.xtext.tests/src/org/eclipse/xtext/formatting2/internal/GenericFormatterTestRequest.java index 9227feb3d..538f0ce73 100644 --- a/org.eclipse.xtext.tests/src/org/eclipse/xtext/formatting2/internal/GenericFormatterTestRequest.java +++ b/org.eclipse.xtext.tests/src/org/eclipse/xtext/formatting2/internal/GenericFormatterTestRequest.java @@ -9,14 +9,12 @@ package org.eclipse.xtext.formatting2.internal; import org.eclipse.emf.ecore.EObject; -import org.eclipse.xtend.lib.annotations.Accessors; import org.eclipse.xtext.testing.formatter.FormatterTestRequest; /** * @author Moritz Eysholdt - Initial contribution and API */ public class GenericFormatterTestRequest extends FormatterTestRequest { - @Accessors private GenericFormatter formatter; public GenericFormatter getFormatter() { diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/formatting2/internal/GenericFormatterTester.java b/org.eclipse.xtext.tests/src/org/eclipse/xtext/formatting2/internal/GenericFormatterTester.java index 3934755d4..bc40e14a4 100644 --- a/org.eclipse.xtext.tests/src/org/eclipse/xtext/formatting2/internal/GenericFormatterTester.java +++ b/org.eclipse.xtext.tests/src/org/eclipse/xtext/formatting2/internal/GenericFormatterTester.java @@ -8,11 +8,10 @@ */ package org.eclipse.xtext.formatting2.internal; +import org.eclipse.xtext.xbase.lib.Procedures.Procedure1; + import com.google.inject.Inject; import com.google.inject.Provider; -import org.eclipse.xtext.formatting2.internal.FormatterTesterWithImpl; -import org.eclipse.xtext.formatting2.internal.GenericFormatterTestRequest; -import org.eclipse.xtext.xbase.lib.Procedures.Procedure1; /** * @author Moritz Eysholdt - Initial contribution and API diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/generator/parser/AntlrGrammarComparator.java b/org.eclipse.xtext.tests/src/org/eclipse/xtext/generator/parser/AntlrGrammarComparator.java index 2871c5ac5..cc109fc11 100644 --- a/org.eclipse.xtext.tests/src/org/eclipse/xtext/generator/parser/AntlrGrammarComparator.java +++ b/org.eclipse.xtext.tests/src/org/eclipse/xtext/generator/parser/AntlrGrammarComparator.java @@ -8,12 +8,11 @@ */ package org.eclipse.xtext.generator.parser; -import com.google.common.base.Objects; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.eclipse.xtend.lib.annotations.Accessors; + import org.eclipse.xtend2.lib.StringConcatenation; import org.eclipse.xtext.xbase.lib.CollectionLiterals; import org.eclipse.xtext.xbase.lib.Functions.Function0; @@ -21,6 +20,8 @@ import org.eclipse.xtext.xbase.lib.IterableExtensions; import org.eclipse.xtext.xbase.lib.Pair; import org.eclipse.xtext.xbase.lib.Pure; +import com.google.common.base.Objects; + /** * Compares two charSequences of ANTLR grammars token by token. * Ignores differences in white space, and counts line breaks for usable error diagnosis. @@ -39,10 +40,8 @@ public class AntlrGrammarComparator { } public static final class ErrorContext { - @Accessors private AntlrGrammarComparator.MatchState testedGrammar = new AntlrGrammarComparator.MatchState(); - @Accessors private AntlrGrammarComparator.MatchState referenceGrammar = new AntlrGrammarComparator.MatchState(); public AntlrGrammarComparator.MatchState reset() { @@ -76,18 +75,14 @@ public class AntlrGrammarComparator { } public static final class MatchState { - @Accessors private String absoluteFileName; - @Accessors private int lineNumber = 1; private int position = 0; - @Accessors private String previousToken; - @Accessors private String currentToken; @Pure diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/generator/trace/TraceFileNameProviderTest.java b/org.eclipse.xtext.tests/src/org/eclipse/xtext/generator/trace/TraceFileNameProviderTest.java new file mode 100644 index 000000000..3ef3d51cc --- /dev/null +++ b/org.eclipse.xtext.tests/src/org/eclipse/xtext/generator/trace/TraceFileNameProviderTest.java @@ -0,0 +1,62 @@ +/** + * 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.generator.trace; + +import org.junit.Assert; +import org.junit.Test; + +public class TraceFileNameProviderTest { + private final TraceFileNameProvider nameProvider = new TraceFileNameProvider(); + + @Test + public void testTraceFileNameOnWindows() { + Assert.assertTrue(nameProvider.isTraceFileName("C:\\workspace\\.Foo.java._trace")); + } + + @Test + public void testTraceFileNameOnUnix() { + Assert.assertTrue(nameProvider.isTraceFileName("/workspace/.Foo.java._trace")); + } + + @Test + public void testTraceFromJavaSimple() { + String trace = nameProvider.getTraceFromJava("Foo.java"); + Assert.assertEquals(".Foo.java._trace", trace); + } + + @Test + public void testTraceFromJavaOnWindows() { + String trace = nameProvider.getTraceFromJava("C:\\workspace\\Foo.java"); + Assert.assertEquals("C:\\workspace\\.Foo.java._trace", trace); + } + + @Test + public void testTraceFromJavaOnUnix() { + String trace = nameProvider.getTraceFromJava("/workspace/Foo.java"); + Assert.assertEquals("/workspace/.Foo.java._trace", trace); + } + + @Test + public void testJavaFromTraceSimple() { + String java = nameProvider.getJavaFromTrace(".Foo.java._trace"); + Assert.assertEquals("Foo.java", java); + } + + @Test + public void testJavaFromTraceOnWindows() { + String java = nameProvider.getJavaFromTrace("C:\\workspace\\.Foo.java._trace"); + Assert.assertEquals("C:\\workspace\\Foo.java", java); + } + + @Test + public void testJavaFromTraceOnUnix() { + String java = nameProvider.getJavaFromTrace("/workspace/.Foo.java._trace"); + Assert.assertEquals("/workspace/Foo.java", java); + } +} diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/generator/trace/TraceFileNameProviderTest.xtend b/org.eclipse.xtext.tests/src/org/eclipse/xtext/generator/trace/TraceFileNameProviderTest.xtend deleted file mode 100644 index bcc87a527..000000000 --- a/org.eclipse.xtext.tests/src/org/eclipse/xtext/generator/trace/TraceFileNameProviderTest.xtend +++ /dev/null @@ -1,61 +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.generator.trace - -import org.junit.Test -import static org.junit.Assert.* - -class TraceFileNameProviderTest { - val nameProvider = new TraceFileNameProvider - - @Test - def testTraceFileNameOnWindows() { - assertTrue(nameProvider.isTraceFileName("C:\\workspace\\.Foo.java._trace")) - } - @Test - def testTraceFileNameOnUnix() { - assertTrue(nameProvider.isTraceFileName("/workspace/.Foo.java._trace")) - } - - @Test - def testTraceFromJavaSimple() { - val trace = nameProvider.getTraceFromJava("Foo.java") - assertEquals(".Foo.java._trace", trace) - } - - @Test - def testTraceFromJavaOnWindows() { - val trace = nameProvider.getTraceFromJava("C:\\workspace\\Foo.java") - assertEquals("C:\\workspace\\.Foo.java._trace", trace) - } - - @Test - def testTraceFromJavaOnUnix() { - val trace = nameProvider.getTraceFromJava("/workspace/Foo.java") - assertEquals("/workspace/.Foo.java._trace", trace) - } - - @Test - def testJavaFromTraceSimple() { - val java = nameProvider.getJavaFromTrace(".Foo.java._trace") - assertEquals("Foo.java", java) - } - - @Test - def testJavaFromTraceOnWindows() { - val java = nameProvider.getJavaFromTrace("C:\\workspace\\.Foo.java._trace") - assertEquals("C:\\workspace\\Foo.java", java) - } - - @Test - def testJavaFromTraceOnUnix() { - val java = nameProvider.getJavaFromTrace("/workspace/.Foo.java._trace") - assertEquals("/workspace/Foo.java", java) - } -} \ No newline at end of file diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/index/IndexTestLanguageGenerator.java b/org.eclipse.xtext.tests/src/org/eclipse/xtext/index/IndexTestLanguageGenerator.java new file mode 100644 index 000000000..bf8f44f10 --- /dev/null +++ b/org.eclipse.xtext.tests/src/org/eclipse/xtext/index/IndexTestLanguageGenerator.java @@ -0,0 +1,37 @@ +/** + * 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.index; + +import org.eclipse.emf.common.util.TreeIterator; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.xtend2.lib.StringConcatenation; +import org.eclipse.xtext.generator.AbstractGenerator; +import org.eclipse.xtext.generator.IFileSystemAccess2; +import org.eclipse.xtext.generator.IGeneratorContext; +import org.eclipse.xtext.index.indexTestLanguage.Entity; + +public class IndexTestLanguageGenerator extends AbstractGenerator { + @Override + public void doGenerate(Resource input, IFileSystemAccess2 fsa, IGeneratorContext context) { + TreeIterator iter = input.getAllContents(); + while (iter.hasNext()) { + EObject e = iter.next(); + if (e instanceof Entity) { + Entity entity = (Entity) e; + StringConcatenation builder = new StringConcatenation(); + builder.append("Hello "); + builder.append(entity.getName()); + builder.append("!"); + builder.newLineIfNotEmpty(); + fsa.generateFile(entity.getName() + ".txt", builder); + } + } + } +} diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/index/IndexTestLanguageGenerator.xtend b/org.eclipse.xtext.tests/src/org/eclipse/xtext/index/IndexTestLanguageGenerator.xtend deleted file mode 100644 index 8aff5e553..000000000 --- a/org.eclipse.xtext.tests/src/org/eclipse/xtext/index/IndexTestLanguageGenerator.xtend +++ /dev/null @@ -1,23 +0,0 @@ -package org.eclipse.xtext.index - -import org.eclipse.emf.ecore.resource.Resource -import org.eclipse.xtext.generator.AbstractGenerator -import org.eclipse.xtext.generator.IFileSystemAccess2 -import org.eclipse.xtext.generator.IGeneratorContext -import org.eclipse.xtext.index.indexTestLanguage.Entity - -class IndexTestLanguageGenerator extends AbstractGenerator { - - override doGenerate(Resource input, IFileSystemAccess2 fsa, IGeneratorContext context) { - val iter = input.allContents - while (iter.hasNext) { - switch e : iter.next { - Entity : - fsa.generateFile(e.name+".txt", ''' - Hello «e.name»! - ''') - } - } - } - -} diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/AbstractFragmentsPlainParsingTest.java b/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/AbstractFragmentsPlainParsingTest.java new file mode 100644 index 000000000..fc2771b63 --- /dev/null +++ b/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/AbstractFragmentsPlainParsingTest.java @@ -0,0 +1,111 @@ +/** + * 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.fragments; + +import com.google.inject.Injector; +import org.eclipse.xtext.resource.XtextResource; +import org.eclipse.xtext.tests.AbstractXtextTests; +import org.junit.Ignore; +import org.junit.Test; + +/** + * @author Sebastian Zarnekow - Initial contribution and API + */ +public abstract class AbstractFragmentsPlainParsingTest extends AbstractXtextTests { + @Override + protected void setInjector(Injector injector) { + super.setInjector(injector); + injectMembers(this); + } + + @Override + protected boolean shouldTestSerializer(XtextResource resource) { + return true; + } + + @Test + public void testSimpleModel() throws Exception { + getModel("#1 myName"); + } + + @Test + public void testReference() throws Exception { + getModel("#2 myName -> myName"); + } + + @Test + public void testReference_02() throws Exception { + getModel("#1 myName : myName"); + } + + @Test + public void testReferenceInFragment() throws Exception { + getModel("#1 myName - myName"); + } + + @Test + public void testReferenceBeforeFragment() throws Exception { + getModel("#3 myName <- myName"); + } + + @Test + public void testAction() throws Exception { + getModel("#4 prev current"); + } + + @Test + public void testActionAndReference() throws Exception { + getModel("#4 prev current prev current"); + } + + @Test + @Ignore("Actions are currently not supported in fragments") + public void testActionInFragment_01() throws Exception { + getModel("#5 prev current"); + } + + @Test + @Ignore("Actions are currently not supported in fragments") + public void testActionInFragment_02() throws Exception { + getModel("#6 prev current"); + } + + @Test + @Ignore("Actions are currently not supported in fragments") + public void testActionInFragmentAndReference_01() throws Exception { + getModel("#5 prev current current - prev"); + } + + @Test + @Ignore("Actions are currently not supported in fragments") + public void testActionInFragmentAndReference_02() throws Exception { + getModel("#6 prev current current - prev"); + } + + @Test + @Ignore("Actions are currently not supported in fragments") + public void testActionInFragmentAndReferenceLoop() throws Exception { + getModel("#7 root -> a a -> b b -> c c - root"); + } + + @Test + public void testDatatypeRule_01() throws Exception { + getModel("#8 a - a"); + } + + @Test + public void testDatatypeRule_02() throws Exception { + getModel("#8 a.b.c.d"); + } + + @Test + public void testDatatypeRule_03() throws Exception { + getModel("#8 a.b.c.d - a.b.c.d"); + } +} diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/AbstractFragmentsPlainParsingTest.xtend b/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/AbstractFragmentsPlainParsingTest.xtend deleted file mode 100644 index 5a56fa3b4..000000000 --- a/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/AbstractFragmentsPlainParsingTest.xtend +++ /dev/null @@ -1,110 +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.fragments - -import com.google.inject.Injector -import org.eclipse.xtext.resource.XtextResource -import org.eclipse.xtext.tests.AbstractXtextTests -import org.junit.Ignore -import org.junit.Test - -/** - * @author Sebastian Zarnekow - Initial contribution and API - */ -abstract class AbstractFragmentsPlainParsingTest extends AbstractXtextTests { - - override protected setInjector(Injector injector) { - super.setInjector(injector) - injectMembers(this) - } - - override protected shouldTestSerializer(XtextResource resource) { - true - } - - @Test - def void testSimpleModel() { - '#1 myName'.model - } - - @Test - def void testReference() { - '#2 myName -> myName'.model - } - - @Test - def void testReference_02() { - '#1 myName : myName'.model - } - - @Test - def void testReferenceInFragment() { - '#1 myName - myName'.model - } - - @Test - def void testReferenceBeforeFragment() { - '#3 myName <- myName'.model - } - - @Test - def void testAction() { - '#4 prev current'.model - } - - @Test - def void testActionAndReference() { - '#4 prev current prev current'.model - } - - @Test - @Ignore("Actions are currently not supported in fragments") - def void testActionInFragment_01() { - '#5 prev current'.model - } - - @Test - @Ignore("Actions are currently not supported in fragments") - def void testActionInFragment_02() { - '#6 prev current'.model - } - - @Test - @Ignore("Actions are currently not supported in fragments") - def void testActionInFragmentAndReference_01() { - '#5 prev current current - prev'.model - } - - @Test - @Ignore("Actions are currently not supported in fragments") - def void testActionInFragmentAndReference_02() { - '#6 prev current current - prev'.model - } - - @Test - @Ignore("Actions are currently not supported in fragments") - def void testActionInFragmentAndReferenceLoop() { - '#7 root -> a a -> b b -> c c - root'.model - } - - @Test - def void testDatatypeRule_01() { - '#8 a - a'.model - } - - @Test - def void testDatatypeRule_02() { - '#8 a.b.c.d'.model - } - - @Test - def void testDatatypeRule_03() { - '#8 a.b.c.d - a.b.c.d'.model - } -} \ No newline at end of file diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/AbstractFragmentsTest.java b/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/AbstractFragmentsTest.java new file mode 100644 index 000000000..0828db4b2 --- /dev/null +++ b/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/AbstractFragmentsTest.java @@ -0,0 +1,262 @@ +/** + * 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.fragments; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.xtext.nodemodel.ICompositeNode; +import org.eclipse.xtext.nodemodel.impl.InvariantChecker; +import org.eclipse.xtext.nodemodel.util.NodeModelUtils; +import org.eclipse.xtext.parser.fragments.fragmentTestLanguage.PRFNamed; +import org.eclipse.xtext.parser.fragments.fragmentTestLanguage.PRFNamedWithAction; +import org.eclipse.xtext.parser.fragments.fragmentTestLanguage.ParserRuleFragments; +import org.eclipse.xtext.resource.XtextResource; +import org.eclipse.xtext.testing.util.ParseHelper; +import org.eclipse.xtext.testing.validation.ValidationTestHelper; +import org.eclipse.xtext.tests.AbstractXtextTests; +import org.eclipse.xtext.xbase.lib.Extension; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +import com.google.inject.Inject; +import com.google.inject.Injector; + +/** + * @author Sebastian Zarnekow - Initial contribution and API + */ +public abstract class AbstractFragmentsTest extends AbstractXtextTests { + @Inject + @Extension + private ParseHelper parseHelper; + + @Inject + @Extension + private ValidationTestHelper validationTestHelper; + + @Inject + @Extension + private InvariantChecker invariantChecker; + + @Override + protected void setInjector(Injector injector) { + super.setInjector(injector); + injectMembers(this); + } + + @Test + public void testSimpleModel() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#1 myName"); + Assert.assertNotNull(fragments); + Assert.assertEquals("myName", fragments.getElement().getName()); + } + + @Test + public void testReference() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#2 myName -> myName"); + Assert.assertNotNull(fragments); + Assert.assertEquals("myName", fragments.getElement().getName()); + Assert.assertEquals(fragments.getElement(), fragments.getRef()); + } + + @Test + public void testReference_02() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#1 myName : myName"); + Assert.assertNotNull(fragments); + Assert.assertEquals("myName", fragments.getElement().getName()); + Assert.assertEquals(fragments.getElement(), fragments.getElement().getRef()); + } + + @Test + public void testReferenceInFragment() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#1 myName - myName"); + Assert.assertNotNull(fragments); + Assert.assertEquals("myName", fragments.getElement().getName()); + Assert.assertEquals(fragments.getElement(), fragments.getElement().getRef()); + } + + @Test + public void testReferenceBeforeFragment() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#3 myName <- myName"); + Assert.assertNotNull(fragments); + Assert.assertEquals("myName", fragments.getElement().getName()); + Assert.assertEquals(fragments.getElement(), fragments.getElement().getRef()); + } + + @Test + public void testAction() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#4 prev current"); + Assert.assertNotNull(fragments); + Assert.assertEquals("current", fragments.getElement().getName()); + Assert.assertEquals("prev", ((PRFNamedWithAction) fragments.getElement()).getPrev().getName()); + } + + @Test + public void testActionAndReference() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#4 prev current prev current"); + Assert.assertNotNull(fragments); + PRFNamed element = fragments.getElement(); + Assert.assertEquals("current", element.getName()); + PRFNamed prev = ((PRFNamedWithAction) element).getPrev(); + Assert.assertEquals("prev", prev.getName()); + Assert.assertEquals(prev, element.getRef()); + Assert.assertEquals(element, ((PRFNamedWithAction) element).getRef2()); + } + + @Test + @Ignore("Actions are currently not supported in fragments") + public void testActionInFragment_01() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#5 prev current"); + Assert.assertNotNull(fragments); + Assert.assertEquals("current", fragments.getElement().getName()); + Assert.assertEquals("prev", ((PRFNamedWithAction) fragments.getElement()).getPrev().getName()); + } + + @Test + @Ignore("Actions are currently not supported in fragments") + public void testActionInFragment_02() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#6 prev current"); + Assert.assertNotNull(fragments); + Assert.assertEquals("current", fragments.getElement().getName()); + Assert.assertEquals("prev", ((PRFNamedWithAction) fragments.getElement()).getPrev().getName()); + } + + @Test + @Ignore("Actions are currently not supported in fragments") + public void testActionInFragmentAndReference_01() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#5 prev current current - prev"); + Assert.assertNotNull(fragments); + PRFNamed element = fragments.getElement(); + Assert.assertEquals("current", element.getName()); + PRFNamed prev = ((PRFNamedWithAction) element).getPrev(); + Assert.assertEquals("prev", prev.getName()); + Assert.assertEquals(prev, element.getRef()); + Assert.assertEquals(element, ((PRFNamedWithAction) element).getRef2()); + } + + @Test + @Ignore("Actions are currently not supported in fragments") + public void testActionInFragmentAndReference_02() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#6 prev current current - prev"); + Assert.assertNotNull(fragments); + PRFNamed element = fragments.getElement(); + Assert.assertEquals("current", element.getName()); + PRFNamed prev = ((PRFNamedWithAction) element).getPrev(); + Assert.assertEquals("prev", prev.getName()); + Assert.assertEquals(prev, element.getRef()); + Assert.assertEquals(element, ((PRFNamedWithAction) element).getRef2()); + } + + @Test + @Ignore("Actions are currently not supported in fragments") + public void testActionInFragmentAndReferenceLoop() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#7 root -> a a -> b b -> c c - root"); + Assert.assertNotNull(fragments); + PRFNamed element = fragments.getElement(); + while ((element instanceof PRFNamedWithAction)) { + { + Assert.assertEquals(element, ((PRFNamedWithAction) element).getRef2()); + element = ((PRFNamedWithAction) element).getPrev(); + } + } + Assert.assertEquals(element, element.getRef()); + } + + @Test + public void testDatatypeRule_01() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#8 a - a"); + Assert.assertNotNull(fragments); + PRFNamed element = fragments.getElement(); + Assert.assertEquals(element, element.getRef()); + } + + @Test + public void testDatatypeRule_02() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#8 a.b.c.d"); + Assert.assertNotNull(fragments); + PRFNamed element = fragments.getElement(); + Assert.assertEquals("a.b.c.d", element.getName()); + } + + @Test + public void testDatatypeRule_03() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#8 a.b.c.d - a.b.c.d"); + Assert.assertNotNull(fragments); + PRFNamed element = fragments.getElement(); + Assert.assertEquals(element, element.getRef()); + } + + @Test + public void testFragmentWithPredicate() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#9 myName - myName"); + Assert.assertNotNull(fragments); + Assert.assertEquals("myName", fragments.getElement().getName()); + Assert.assertEquals(fragments.getElement(), fragments.getElement().getRef()); + } + + @Test + public void testFragmentRecursive_01() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#10 myName myPrev"); + Assert.assertNotNull(fragments); + Assert.assertEquals("myName", fragments.getElement().getName()); + PRFNamed prev = ((PRFNamedWithAction) fragments.getElement()).getPrev(); + Assert.assertEquals("myPrev", prev.getName()); + ICompositeNode node = NodeModelUtils.findActualNodeFor(prev); + Assert.assertEquals(" myPrev", node.getText()); + EObject lookup = NodeModelUtils.findActualSemanticObjectFor(node); + Assert.assertSame(prev, lookup); + } + + @Test + public void testFragmentRecursive_02() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#10 myName ((myPrev))"); + Assert.assertNotNull(fragments); + Assert.assertEquals("myName", fragments.getElement().getName()); + PRFNamed prev = ((PRFNamedWithAction) fragments.getElement()).getPrev(); + Assert.assertEquals("myPrev", prev.getName()); + ICompositeNode node = NodeModelUtils.findActualNodeFor(prev); + Assert.assertEquals(" ((myPrev))", node.getText()); + EObject lookup = NodeModelUtils.findActualSemanticObjectFor(node); + Assert.assertSame(prev, lookup); + } + + @Test + public void testFragmentRecursive_03() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#11 myName myPrev"); + Assert.assertNotNull(fragments); + Assert.assertEquals("myName", fragments.getElement().getName()); + PRFNamed prev = ((PRFNamedWithAction) fragments.getElement()).getPrev(); + Assert.assertEquals("myPrev", prev.getName()); + ICompositeNode node = NodeModelUtils.findActualNodeFor(prev); + Assert.assertEquals(" myPrev", node.getText()); + EObject lookup = NodeModelUtils.findActualSemanticObjectFor(node); + Assert.assertSame(prev, lookup); + } + + @Test + public void testFragmentRecursive_04() throws Exception { + ParserRuleFragments fragments = parseAndValidate("#11 myName ((myPrev))"); + Assert.assertNotNull(fragments); + Assert.assertEquals("myName", fragments.getElement().getName()); + PRFNamed prev = ((PRFNamedWithAction) fragments.getElement()).getPrev(); + Assert.assertEquals("myPrev", prev.getName()); + ICompositeNode node = NodeModelUtils.findActualNodeFor(prev); + Assert.assertEquals("myPrev", node.getText()); + EObject lookup = NodeModelUtils.findActualSemanticObjectFor(node); + Assert.assertSame(prev, lookup); + } + + protected ParserRuleFragments parseAndValidate(CharSequence s) throws Exception { + ParserRuleFragments result = parseHelper.parse(s); + validationTestHelper.assertNoIssues(result); + XtextResource resource = (XtextResource) result.eResource(); + ICompositeNode node = resource.getParseResult().getRootNode(); + invariantChecker.checkInvariant(node); + return result; + } +} diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/AbstractFragmentsTest.xtend b/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/AbstractFragmentsTest.xtend deleted file mode 100644 index 7f63a51bc..000000000 --- a/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/AbstractFragmentsTest.xtend +++ /dev/null @@ -1,259 +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.fragments - -import com.google.inject.Inject -import com.google.inject.Injector -import org.eclipse.xtext.nodemodel.impl.InvariantChecker -import org.eclipse.xtext.nodemodel.util.NodeModelUtils -import org.eclipse.xtext.parser.fragments.fragmentTestLanguage.PRFNamedWithAction -import org.eclipse.xtext.parser.fragments.fragmentTestLanguage.ParserRuleFragments -import org.eclipse.xtext.resource.XtextResource -import org.eclipse.xtext.testing.util.ParseHelper -import org.eclipse.xtext.testing.validation.ValidationTestHelper -import org.eclipse.xtext.tests.AbstractXtextTests -import org.junit.Test -import org.junit.Ignore - -/** - * @author Sebastian Zarnekow - Initial contribution and API - */ -abstract class AbstractFragmentsTest extends AbstractXtextTests { - - @Inject - extension ParseHelper parseHelper - - @Inject - extension ValidationTestHelper validationTestHelper - - @Inject - extension InvariantChecker invariantChecker - - override protected setInjector(Injector injector) { - super.setInjector(injector) - injectMembers(this) - } - - @Test - def void testSimpleModel() { - val fragments = '#1 myName'.parseAndValidate - assertNotNull(fragments) - assertEquals('myName', fragments.element.name) - } - - @Test - def void testReference() { - val fragments = '#2 myName -> myName'.parseAndValidate - assertNotNull(fragments) - assertEquals('myName', fragments.element.name) - assertEquals(fragments.element, fragments.ref) - } - - @Test - def void testReference_02() { - val fragments = '#1 myName : myName'.parseAndValidate - assertNotNull(fragments) - assertEquals('myName', fragments.element.name) - assertEquals(fragments.element, fragments.element.ref) - } - - @Test - def void testReferenceInFragment() { - val fragments = '#1 myName - myName'.parseAndValidate - assertNotNull(fragments) - assertEquals('myName', fragments.element.name) - assertEquals(fragments.element, fragments.element.ref) - } - - @Test - def void testReferenceBeforeFragment() { - val fragments = '#3 myName <- myName'.parseAndValidate - assertNotNull(fragments) - assertEquals('myName', fragments.element.name) - assertEquals(fragments.element, fragments.element.ref) - } - - @Test - def void testAction() { - val fragments = '#4 prev current'.parseAndValidate - assertNotNull(fragments) - assertEquals('current', fragments.element.name) - assertEquals('prev', (fragments.element as PRFNamedWithAction).prev.name) - } - - @Test - def void testActionAndReference() { - val fragments = '#4 prev current prev current'.parseAndValidate - assertNotNull(fragments) - val element = fragments.element - assertEquals('current', element.name) - val prev = (element as PRFNamedWithAction).prev - assertEquals('prev', prev.name) - - assertEquals(prev, element.ref) - assertEquals(element, (element as PRFNamedWithAction).ref2) - } - - @Test - @Ignore("Actions are currently not supported in fragments") - def void testActionInFragment_01() { - val fragments = '#5 prev current'.parseAndValidate - assertNotNull(fragments) - assertEquals('current', fragments.element.name) - assertEquals('prev', (fragments.element as PRFNamedWithAction).prev.name) - } - - @Test - @Ignore("Actions are currently not supported in fragments") - def void testActionInFragment_02() { - val fragments = '#6 prev current'.parseAndValidate - assertNotNull(fragments) - assertEquals('current', fragments.element.name) - assertEquals('prev', (fragments.element as PRFNamedWithAction).prev.name) - } - - @Test - @Ignore("Actions are currently not supported in fragments") - def void testActionInFragmentAndReference_01() { - val fragments = '#5 prev current current - prev'.parseAndValidate - assertNotNull(fragments) - val element = fragments.element - assertEquals('current', element.name) - val prev = (element as PRFNamedWithAction).prev - assertEquals('prev', prev.name) - - assertEquals(prev, element.ref) - assertEquals(element, (element as PRFNamedWithAction).ref2) - } - - @Test - @Ignore("Actions are currently not supported in fragments") - def void testActionInFragmentAndReference_02() { - val fragments = '#6 prev current current - prev'.parseAndValidate - assertNotNull(fragments) - val element = fragments.element - assertEquals('current', element.name) - val prev = (element as PRFNamedWithAction).prev - assertEquals('prev', prev.name) - - assertEquals(prev, element.ref) - assertEquals(element, (element as PRFNamedWithAction).ref2) - } - - @Test - @Ignore("Actions are currently not supported in fragments") - def void testActionInFragmentAndReferenceLoop() { - val fragments = '#7 root -> a a -> b b -> c c - root'.parseAndValidate - assertNotNull(fragments) - - var element = fragments.element - while(element instanceof PRFNamedWithAction) { - assertEquals(element, element.ref2) - element = element.prev - } - assertEquals(element, element.ref) - } - - @Test - def void testDatatypeRule_01() { - val fragments = '#8 a - a'.parseAndValidate - assertNotNull(fragments) - - var element = fragments.element - assertEquals(element, element.ref) - } - - @Test - def void testDatatypeRule_02() { - val fragments = '#8 a.b.c.d'.parseAndValidate - assertNotNull(fragments) - - var element = fragments.element - assertEquals('a.b.c.d', element.name) - } - - @Test - def void testDatatypeRule_03() { - val fragments = '#8 a.b.c.d - a.b.c.d'.parseAndValidate - assertNotNull(fragments) - - var element = fragments.element - assertEquals(element, element.ref) - } - - @Test - def void testFragmentWithPredicate() { - val fragments = '#9 myName - myName'.parseAndValidate - assertNotNull(fragments) - assertEquals('myName', fragments.element.name) - assertEquals(fragments.element, fragments.element.ref) - } - - @Test - def void testFragmentRecursive_01() { - val fragments = '#10 myName myPrev'.parseAndValidate - assertNotNull(fragments) - assertEquals('myName', fragments.element.name) - val prev = (fragments.element as PRFNamedWithAction).prev - assertEquals('myPrev', prev.name) - val node = NodeModelUtils.findActualNodeFor(prev) - assertEquals(' myPrev', node.text) - val lookup = NodeModelUtils.findActualSemanticObjectFor(node) - assertSame(prev, lookup) - } - - @Test - def void testFragmentRecursive_02() { - val fragments = '#10 myName ((myPrev))'.parseAndValidate - assertNotNull(fragments) - assertEquals('myName', fragments.element.name) - val prev = (fragments.element as PRFNamedWithAction).prev - assertEquals('myPrev', prev.name) - val node = NodeModelUtils.findActualNodeFor(prev) - assertEquals(' ((myPrev))', node.text) - val lookup = NodeModelUtils.findActualSemanticObjectFor(node) - assertSame(prev, lookup) - } - - @Test - def void testFragmentRecursive_03() { - val fragments = '#11 myName myPrev'.parseAndValidate - assertNotNull(fragments) - assertEquals('myName', fragments.element.name) - val prev = (fragments.element as PRFNamedWithAction).prev - assertEquals('myPrev', prev.name) - val node = NodeModelUtils.findActualNodeFor(prev) - assertEquals(' myPrev', node.text) - val lookup = NodeModelUtils.findActualSemanticObjectFor(node) - assertSame(prev, lookup) - } - - @Test - def void testFragmentRecursive_04() { - val fragments = '#11 myName ((myPrev))'.parseAndValidate - assertNotNull(fragments) - assertEquals('myName', fragments.element.name) - val prev = (fragments.element as PRFNamedWithAction).prev - assertEquals('myPrev', prev.name) - val node = NodeModelUtils.findActualNodeFor(prev) - assertEquals('myPrev', node.text) - val lookup = NodeModelUtils.findActualSemanticObjectFor(node) - assertSame(prev, lookup) - } - - protected def parseAndValidate(CharSequence s) { - val result = s.parse - result.assertNoIssues - val resource = result.eResource as XtextResource - val node = resource.parseResult.rootNode - node.checkInvariant - return result - } - -} \ No newline at end of file diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentExsPlainParsingTest.java b/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentExsPlainParsingTest.java index c57cec5ec..aac2e1d64 100644 --- a/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentExsPlainParsingTest.java +++ b/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentExsPlainParsingTest.java @@ -8,9 +8,6 @@ */ package org.eclipse.xtext.parser.fragments; -import org.eclipse.xtext.parser.fragments.AbstractFragmentsPlainParsingTest; -import org.eclipse.xtext.parser.fragments.FragmentTestLanguageExStandaloneSetup; - /** * @author Sebastian Zarnekow - Initial contribution and API */ diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentsEagerLinkingTest.java b/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentsEagerLinkingTest.java index 90998c40e..a7c5c5bdc 100644 --- a/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentsEagerLinkingTest.java +++ b/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentsEagerLinkingTest.java @@ -8,8 +8,6 @@ */ package org.eclipse.xtext.parser.fragments; -import org.eclipse.xtext.parser.fragments.AbstractFragmentsTest; -import org.eclipse.xtext.parser.fragments.FragmentsEagerLinkingInjectorProvider; import org.eclipse.xtext.testing.InjectWith; import org.eclipse.xtext.testing.XtextRunner; import org.junit.runner.RunWith; diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentsExTest.java b/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentsExTest.java index 8290aab13..5f82c11c8 100644 --- a/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentsExTest.java +++ b/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentsExTest.java @@ -8,9 +8,6 @@ */ package org.eclipse.xtext.parser.fragments; -import org.eclipse.xtext.parser.fragments.AbstractFragmentsTest; -import org.eclipse.xtext.parser.fragments.FragmentTestLanguageExStandaloneSetup; - /** * @author Sebastian Zarnekow - Initial contribution and API */ diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentsPlainParsingTest.java b/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentsPlainParsingTest.java index f4142a637..36b6f6ebc 100644 --- a/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentsPlainParsingTest.java +++ b/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentsPlainParsingTest.java @@ -8,9 +8,6 @@ */ package org.eclipse.xtext.parser.fragments; -import org.eclipse.xtext.parser.fragments.AbstractFragmentsPlainParsingTest; -import org.eclipse.xtext.parser.fragments.FragmentTestLanguageStandaloneSetup; - /** * @author Sebastian Zarnekow - Initial contribution and API */ diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentsTest.java b/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentsTest.java index 06ed2205d..60e5d1077 100644 --- a/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentsTest.java +++ b/org.eclipse.xtext.tests/src/org/eclipse/xtext/parser/fragments/FragmentsTest.java @@ -8,9 +8,6 @@ */ package org.eclipse.xtext.parser.fragments; -import org.eclipse.xtext.parser.fragments.AbstractFragmentsTest; -import org.eclipse.xtext.parser.fragments.FragmentTestLanguageStandaloneSetup; - /** * @author Sebastian Zarnekow - Initial contribution and API */ diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/xtext/generator/GrammarAccessExtensionsTest.java b/org.eclipse.xtext.tests/src/org/eclipse/xtext/xtext/generator/GrammarAccessExtensionsTest.java new file mode 100644 index 000000000..97bac19d4 --- /dev/null +++ b/org.eclipse.xtext.tests/src/org/eclipse/xtext/xtext/generator/GrammarAccessExtensionsTest.java @@ -0,0 +1,54 @@ +/** + * 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.xtext.generator; + +import org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessExtensions; +import org.junit.Assert; +import org.junit.Test; + +/** + * @author Sebastian Zarnekow - Initial contribution and API + */ +public class GrammarAccessExtensionsTest { + private GrammarAccessExtensions grammarAccessExtensions = new GrammarAccessExtensions(); + + @Test + public void testToJavaIdentifier() { + Assert.assertEquals("FooBar", grammarAccessExtensions.toJavaIdentifier("foo Bar", true)); + Assert.assertEquals("Foo", grammarAccessExtensions.toJavaIdentifier("foo;", true)); + Assert.assertEquals("foo", grammarAccessExtensions.toJavaIdentifier("foo;", false)); + Assert.assertEquals("Colon", grammarAccessExtensions.toJavaIdentifier(":", true)); + Assert.assertEquals("Colon", grammarAccessExtensions.toJavaIdentifier(":", false)); + Assert.assertEquals("Semicolon", grammarAccessExtensions.toJavaIdentifier(";", false)); + Assert.assertEquals("CommercialAtApostrophe", grammarAccessExtensions.toJavaIdentifier("@\'", false)); + Assert.assertEquals("Grün", grammarAccessExtensions.toJavaIdentifier("Grün", true)); + Assert.assertEquals("DollarSign", grammarAccessExtensions.toJavaIdentifier("$", true)); + Assert.assertEquals("_", grammarAccessExtensions.toJavaIdentifier("_", true)); + } + + /** + * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=298492 + */ + @Test + public void testBug() throws Exception { + Assert.assertEquals("HiraganaLetterRu", grammarAccessExtensions.toJavaIdentifier("\u308b", true)); + } + + @Test + public void testSmoke() throws Exception { + for (int i = 0; i < 4000; i++) { + String identifier = grammarAccessExtensions.toJavaIdentifier(String.valueOf((char) i), false); + for (int j = 0; j < identifier.length(); j++) { + char charAt = identifier.charAt(j); + Assert.assertTrue(identifier + ":" + Character.valueOf(charAt), + grammarAccessExtensions.isValidJavaLatinIdentifier(charAt, j == 0)); + } + } + } +} diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/xtext/generator/GrammarAccessExtensionsTest.xtend b/org.eclipse.xtext.tests/src/org/eclipse/xtext/xtext/generator/GrammarAccessExtensionsTest.xtend deleted file mode 100644 index 1bd261167..000000000 --- a/org.eclipse.xtext.tests/src/org/eclipse/xtext/xtext/generator/GrammarAccessExtensionsTest.xtend +++ /dev/null @@ -1,53 +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.xtext.generator - -import org.junit.Test -import static org.junit.Assert.* -import org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessExtensions - -/** - * @author Sebastian Zarnekow - Initial contribution and API - */ -class GrammarAccessExtensionsTest { - - extension GrammarAccessExtensions = new GrammarAccessExtensions - - @Test def void testToJavaIdentifier() { - assertEquals("FooBar", toJavaIdentifier("foo Bar", true)); - assertEquals("Foo", toJavaIdentifier("foo;", true)); - assertEquals("foo", toJavaIdentifier("foo;", false)); - assertEquals("Colon", toJavaIdentifier(":", true)); - assertEquals("Colon", toJavaIdentifier(":", false)); - assertEquals("Semicolon", toJavaIdentifier(";", false)); - assertEquals("CommercialAtApostrophe", toJavaIdentifier("@'", false)); - assertEquals("Grün", toJavaIdentifier("Grün", true)); - assertEquals("DollarSign", toJavaIdentifier("$", true)); - assertEquals("_", toJavaIdentifier("_", true)); - } - - /** - * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=298492 - */ - @Test def void testBug() throws Exception { - assertEquals("HiraganaLetterRu", toJavaIdentifier("\u308B",true)); - } - - @Test def void testSmoke() throws Exception { - for (var int i = 0; i < 4000; i++) { - val identifier = toJavaIdentifier(String.valueOf(i as char), false) - - for (var int j = 0; j < identifier.length(); j++) { - val char charAt = identifier.charAt(j) - assertTrue(identifier+":"+charAt, charAt.isValidJavaLatinIdentifier(j==0)) - } - } - } - -} diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/xtext/generator/WizardConfigTest.java b/org.eclipse.xtext.tests/src/org/eclipse/xtext/xtext/generator/WizardConfigTest.java new file mode 100644 index 000000000..e4fccd943 --- /dev/null +++ b/org.eclipse.xtext.tests/src/org/eclipse/xtext/xtext/generator/WizardConfigTest.java @@ -0,0 +1,54 @@ +/** + * 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.xtext.generator; + +import org.eclipse.xtext.xtext.generator.model.project.StandardProjectConfig; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.google.inject.Guice; +import com.google.inject.Injector; + +/** + * @author Sebastian Zarnekow - Initial contribution and API + */ +public class WizardConfigTest { + private Injector injector; + + @Before + public void createInjector() { + injector = Guice.createInjector(new DefaultGeneratorModule()); + } + + @Test + public void testMavenProjectNames() { + StandardProjectConfig cfg = new StandardProjectConfig(); + cfg.setBaseName("com.acme"); + cfg.setMavenLayout(true); + cfg.getRuntimeTest().setEnabled(true); + cfg.getEclipsePlugin().setEnabled(true); + cfg.getEclipsePluginTest().setEnabled(true); + cfg.initialize(injector); + Assert.assertEquals("com.acme", cfg.getRuntimeTest().getName()); + Assert.assertEquals("com.acme.ui", cfg.getEclipsePluginTest().getName()); + } + + @Test + public void testPlainProjectNames() { + StandardProjectConfig cfg = new StandardProjectConfig(); + cfg.setBaseName("com.acme"); + cfg.getRuntimeTest().setEnabled(true); + cfg.getEclipsePlugin().setEnabled(true); + cfg.getEclipsePluginTest().setEnabled(true); + cfg.initialize(injector); + Assert.assertEquals("com.acme.tests", cfg.getRuntimeTest().getName()); + Assert.assertEquals("com.acme.ui.tests", cfg.getEclipsePluginTest().getName()); + } +} diff --git a/org.eclipse.xtext.tests/src/org/eclipse/xtext/xtext/generator/WizardConfigTest.xtend b/org.eclipse.xtext.tests/src/org/eclipse/xtext/xtext/generator/WizardConfigTest.xtend deleted file mode 100644 index ab7a8536e..000000000 --- a/org.eclipse.xtext.tests/src/org/eclipse/xtext/xtext/generator/WizardConfigTest.xtend +++ /dev/null @@ -1,54 +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.xtext.generator - -import com.google.inject.Guice -import com.google.inject.Injector -import org.eclipse.xtext.xtext.generator.model.project.StandardProjectConfig -import org.junit.Assert -import org.junit.Before -import org.junit.Test - -/** - * @author Sebastian Zarnekow - Initial contribution and API - */ -class WizardConfigTest { - - var Injector injector - - @Before def void createInjector() { - injector = Guice.createInjector(new DefaultGeneratorModule) - } - - @Test def void testMavenProjectNames() { - val cfg = new StandardProjectConfig() => [ - baseName = 'com.acme' - mavenLayout = true - runtimeTest.enabled = true - eclipsePlugin.enabled = true - eclipsePluginTest.enabled = true - ] - cfg.initialize(injector) - Assert.assertEquals('com.acme', cfg.runtimeTest.name) - Assert.assertEquals('com.acme.ui', cfg.eclipsePluginTest.name) - } - - @Test def void testPlainProjectNames() { - val cfg = new StandardProjectConfig() => [ - baseName = 'com.acme' - runtimeTest.enabled = true - eclipsePlugin.enabled = true - eclipsePluginTest.enabled = true - ] - cfg.initialize(injector) - Assert.assertEquals('com.acme.tests', cfg.runtimeTest.name) - Assert.assertEquals('com.acme.ui.tests', cfg.eclipsePluginTest.name) - } - -} \ No newline at end of file diff --git a/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/generator/trace/TraceFileNameProviderTest.java b/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/generator/trace/TraceFileNameProviderTest.java deleted file mode 100644 index bdb80d729..000000000 --- a/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/generator/trace/TraceFileNameProviderTest.java +++ /dev/null @@ -1,64 +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.generator.trace; - -import org.eclipse.xtext.generator.trace.TraceFileNameProvider; -import org.junit.Assert; -import org.junit.Test; - -@SuppressWarnings("all") -public class TraceFileNameProviderTest { - private final TraceFileNameProvider nameProvider = new TraceFileNameProvider(); - - @Test - public void testTraceFileNameOnWindows() { - Assert.assertTrue(this.nameProvider.isTraceFileName("C:\\workspace\\.Foo.java._trace")); - } - - @Test - public void testTraceFileNameOnUnix() { - Assert.assertTrue(this.nameProvider.isTraceFileName("/workspace/.Foo.java._trace")); - } - - @Test - public void testTraceFromJavaSimple() { - final String trace = this.nameProvider.getTraceFromJava("Foo.java"); - Assert.assertEquals(".Foo.java._trace", trace); - } - - @Test - public void testTraceFromJavaOnWindows() { - final String trace = this.nameProvider.getTraceFromJava("C:\\workspace\\Foo.java"); - Assert.assertEquals("C:\\workspace\\.Foo.java._trace", trace); - } - - @Test - public void testTraceFromJavaOnUnix() { - final String trace = this.nameProvider.getTraceFromJava("/workspace/Foo.java"); - Assert.assertEquals("/workspace/.Foo.java._trace", trace); - } - - @Test - public void testJavaFromTraceSimple() { - final String java = this.nameProvider.getJavaFromTrace(".Foo.java._trace"); - Assert.assertEquals("Foo.java", java); - } - - @Test - public void testJavaFromTraceOnWindows() { - final String java = this.nameProvider.getJavaFromTrace("C:\\workspace\\.Foo.java._trace"); - Assert.assertEquals("C:\\workspace\\Foo.java", java); - } - - @Test - public void testJavaFromTraceOnUnix() { - final String java = this.nameProvider.getJavaFromTrace("/workspace/.Foo.java._trace"); - Assert.assertEquals("/workspace/Foo.java", java); - } -} diff --git a/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/index/IndexTestLanguageGenerator.java b/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/index/IndexTestLanguageGenerator.java deleted file mode 100644 index c015ac5eb..000000000 --- a/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/index/IndexTestLanguageGenerator.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.eclipse.xtext.index; - -import org.eclipse.emf.common.util.TreeIterator; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.ecore.resource.Resource; -import org.eclipse.xtend2.lib.StringConcatenation; -import org.eclipse.xtext.generator.AbstractGenerator; -import org.eclipse.xtext.generator.IFileSystemAccess2; -import org.eclipse.xtext.generator.IGeneratorContext; -import org.eclipse.xtext.index.indexTestLanguage.Entity; - -@SuppressWarnings("all") -public class IndexTestLanguageGenerator extends AbstractGenerator { - @Override - public void doGenerate(final Resource input, final IFileSystemAccess2 fsa, final IGeneratorContext context) { - final TreeIterator iter = input.getAllContents(); - while (iter.hasNext()) { - EObject _next = iter.next(); - final EObject e = _next; - boolean _matched = false; - if (e instanceof Entity) { - _matched=true; - String _name = ((Entity)e).getName(); - String _plus = (_name + ".txt"); - StringConcatenation _builder = new StringConcatenation(); - _builder.append("Hello "); - String _name_1 = ((Entity)e).getName(); - _builder.append(_name_1); - _builder.append("!"); - _builder.newLineIfNotEmpty(); - fsa.generateFile(_plus, _builder); - } - } - } -} diff --git a/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/parser/fragments/AbstractFragmentsPlainParsingTest.java b/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/parser/fragments/AbstractFragmentsPlainParsingTest.java deleted file mode 100644 index 21c574283..000000000 --- a/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/parser/fragments/AbstractFragmentsPlainParsingTest.java +++ /dev/null @@ -1,173 +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.fragments; - -import com.google.inject.Injector; -import org.eclipse.xtext.resource.XtextResource; -import org.eclipse.xtext.tests.AbstractXtextTests; -import org.eclipse.xtext.xbase.lib.Exceptions; -import org.junit.Ignore; -import org.junit.Test; - -/** - * @author Sebastian Zarnekow - Initial contribution and API - */ -@SuppressWarnings("all") -public abstract class AbstractFragmentsPlainParsingTest extends AbstractXtextTests { - @Override - protected void setInjector(final Injector injector) { - super.setInjector(injector); - this.injectMembers(this); - } - - @Override - protected boolean shouldTestSerializer(final XtextResource resource) { - return true; - } - - @Test - public void testSimpleModel() { - try { - this.getModel("#1 myName"); - } catch (Throwable _e) { - throw Exceptions.sneakyThrow(_e); - } - } - - @Test - public void testReference() { - try { - this.getModel("#2 myName -> myName"); - } catch (Throwable _e) { - throw Exceptions.sneakyThrow(_e); - } - } - - @Test - public void testReference_02() { - try { - this.getModel("#1 myName : myName"); - } catch (Throwable _e) { - throw Exceptions.sneakyThrow(_e); - } - } - - @Test - public void testReferenceInFragment() { - try { - this.getModel("#1 myName - myName"); - } catch (Throwable _e) { - throw Exceptions.sneakyThrow(_e); - } - } - - @Test - public void testReferenceBeforeFragment() { - try { - this.getModel("#3 myName <- myName"); - } catch (Throwable _e) { - throw Exceptions.sneakyThrow(_e); - } - } - - @Test - public void testAction() { - try { - this.getModel("#4 prev current"); - } catch (Throwable _e) { - throw Exceptions.sneakyThrow(_e); - } - } - - @Test - public void testActionAndReference() { - try { - this.getModel("#4 prev current prev current"); - } catch (Throwable _e) { - throw Exceptions.sneakyThrow(_e); - } - } - - @Test - @Ignore("Actions are currently not supported in fragments") - public void testActionInFragment_01() { - try { - this.getModel("#5 prev current"); - } catch (Throwable _e) { - throw Exceptions.sneakyThrow(_e); - } - } - - @Test - @Ignore("Actions are currently not supported in fragments") - public void testActionInFragment_02() { - try { - this.getModel("#6 prev current"); - } catch (Throwable _e) { - throw Exceptions.sneakyThrow(_e); - } - } - - @Test - @Ignore("Actions are currently not supported in fragments") - public void testActionInFragmentAndReference_01() { - try { - this.getModel("#5 prev current current - prev"); - } catch (Throwable _e) { - throw Exceptions.sneakyThrow(_e); - } - } - - @Test - @Ignore("Actions are currently not supported in fragments") - public void testActionInFragmentAndReference_02() { - try { - this.getModel("#6 prev current current - prev"); - } catch (Throwable _e) { - throw Exceptions.sneakyThrow(_e); - } - } - - @Test - @Ignore("Actions are currently not supported in fragments") - public void testActionInFragmentAndReferenceLoop() { - try { - this.getModel("#7 root -> a a -> b b -> c c - root"); - } catch (Throwable _e) { - throw Exceptions.sneakyThrow(_e); - } - } - - @Test - public void testDatatypeRule_01() { - try { - this.getModel("#8 a - a"); - } catch (Throwable _e) { - throw Exceptions.sneakyThrow(_e); - } - } - - @Test - public void testDatatypeRule_02() { - try { - this.getModel("#8 a.b.c.d"); - } catch (Throwable _e) { - throw Exceptions.sneakyThrow(_e); - } - } - - @Test - public void testDatatypeRule_03() { - try { - this.getModel("#8 a.b.c.d - a.b.c.d"); - } catch (Throwable _e) { - throw Exceptions.sneakyThrow(_e); - } - } -} diff --git a/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/parser/fragments/AbstractFragmentsTest.java b/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/parser/fragments/AbstractFragmentsTest.java deleted file mode 100644 index d70b54eba..000000000 --- a/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/parser/fragments/AbstractFragmentsTest.java +++ /dev/null @@ -1,276 +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.fragments; - -import com.google.inject.Inject; -import com.google.inject.Injector; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.ecore.resource.Resource; -import org.eclipse.xtext.nodemodel.ICompositeNode; -import org.eclipse.xtext.nodemodel.impl.InvariantChecker; -import org.eclipse.xtext.nodemodel.util.NodeModelUtils; -import org.eclipse.xtext.parser.fragments.fragmentTestLanguage.PRFNamed; -import org.eclipse.xtext.parser.fragments.fragmentTestLanguage.PRFNamedWithAction; -import org.eclipse.xtext.parser.fragments.fragmentTestLanguage.ParserRuleFragments; -import org.eclipse.xtext.resource.XtextResource; -import org.eclipse.xtext.testing.util.ParseHelper; -import org.eclipse.xtext.testing.validation.ValidationTestHelper; -import org.eclipse.xtext.tests.AbstractXtextTests; -import org.eclipse.xtext.xbase.lib.Exceptions; -import org.eclipse.xtext.xbase.lib.Extension; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; - -/** - * @author Sebastian Zarnekow - Initial contribution and API - */ -@SuppressWarnings("all") -public abstract class AbstractFragmentsTest extends AbstractXtextTests { - @Inject - @Extension - private ParseHelper parseHelper; - - @Inject - @Extension - private ValidationTestHelper validationTestHelper; - - @Inject - @Extension - private InvariantChecker invariantChecker; - - @Override - protected void setInjector(final Injector injector) { - super.setInjector(injector); - this.injectMembers(this); - } - - @Test - public void testSimpleModel() { - final ParserRuleFragments fragments = this.parseAndValidate("#1 myName"); - Assert.assertNotNull(fragments); - Assert.assertEquals("myName", fragments.getElement().getName()); - } - - @Test - public void testReference() { - final ParserRuleFragments fragments = this.parseAndValidate("#2 myName -> myName"); - Assert.assertNotNull(fragments); - Assert.assertEquals("myName", fragments.getElement().getName()); - Assert.assertEquals(fragments.getElement(), fragments.getRef()); - } - - @Test - public void testReference_02() { - final ParserRuleFragments fragments = this.parseAndValidate("#1 myName : myName"); - Assert.assertNotNull(fragments); - Assert.assertEquals("myName", fragments.getElement().getName()); - Assert.assertEquals(fragments.getElement(), fragments.getElement().getRef()); - } - - @Test - public void testReferenceInFragment() { - final ParserRuleFragments fragments = this.parseAndValidate("#1 myName - myName"); - Assert.assertNotNull(fragments); - Assert.assertEquals("myName", fragments.getElement().getName()); - Assert.assertEquals(fragments.getElement(), fragments.getElement().getRef()); - } - - @Test - public void testReferenceBeforeFragment() { - final ParserRuleFragments fragments = this.parseAndValidate("#3 myName <- myName"); - Assert.assertNotNull(fragments); - Assert.assertEquals("myName", fragments.getElement().getName()); - Assert.assertEquals(fragments.getElement(), fragments.getElement().getRef()); - } - - @Test - public void testAction() { - final ParserRuleFragments fragments = this.parseAndValidate("#4 prev current"); - Assert.assertNotNull(fragments); - Assert.assertEquals("current", fragments.getElement().getName()); - PRFNamed _element = fragments.getElement(); - Assert.assertEquals("prev", ((PRFNamedWithAction) _element).getPrev().getName()); - } - - @Test - public void testActionAndReference() { - final ParserRuleFragments fragments = this.parseAndValidate("#4 prev current prev current"); - Assert.assertNotNull(fragments); - final PRFNamed element = fragments.getElement(); - Assert.assertEquals("current", element.getName()); - final PRFNamed prev = ((PRFNamedWithAction) element).getPrev(); - Assert.assertEquals("prev", prev.getName()); - Assert.assertEquals(prev, element.getRef()); - Assert.assertEquals(element, ((PRFNamedWithAction) element).getRef2()); - } - - @Test - @Ignore("Actions are currently not supported in fragments") - public void testActionInFragment_01() { - final ParserRuleFragments fragments = this.parseAndValidate("#5 prev current"); - Assert.assertNotNull(fragments); - Assert.assertEquals("current", fragments.getElement().getName()); - PRFNamed _element = fragments.getElement(); - Assert.assertEquals("prev", ((PRFNamedWithAction) _element).getPrev().getName()); - } - - @Test - @Ignore("Actions are currently not supported in fragments") - public void testActionInFragment_02() { - final ParserRuleFragments fragments = this.parseAndValidate("#6 prev current"); - Assert.assertNotNull(fragments); - Assert.assertEquals("current", fragments.getElement().getName()); - PRFNamed _element = fragments.getElement(); - Assert.assertEquals("prev", ((PRFNamedWithAction) _element).getPrev().getName()); - } - - @Test - @Ignore("Actions are currently not supported in fragments") - public void testActionInFragmentAndReference_01() { - final ParserRuleFragments fragments = this.parseAndValidate("#5 prev current current - prev"); - Assert.assertNotNull(fragments); - final PRFNamed element = fragments.getElement(); - Assert.assertEquals("current", element.getName()); - final PRFNamed prev = ((PRFNamedWithAction) element).getPrev(); - Assert.assertEquals("prev", prev.getName()); - Assert.assertEquals(prev, element.getRef()); - Assert.assertEquals(element, ((PRFNamedWithAction) element).getRef2()); - } - - @Test - @Ignore("Actions are currently not supported in fragments") - public void testActionInFragmentAndReference_02() { - final ParserRuleFragments fragments = this.parseAndValidate("#6 prev current current - prev"); - Assert.assertNotNull(fragments); - final PRFNamed element = fragments.getElement(); - Assert.assertEquals("current", element.getName()); - final PRFNamed prev = ((PRFNamedWithAction) element).getPrev(); - Assert.assertEquals("prev", prev.getName()); - Assert.assertEquals(prev, element.getRef()); - Assert.assertEquals(element, ((PRFNamedWithAction) element).getRef2()); - } - - @Test - @Ignore("Actions are currently not supported in fragments") - public void testActionInFragmentAndReferenceLoop() { - final ParserRuleFragments fragments = this.parseAndValidate("#7 root -> a a -> b b -> c c - root"); - Assert.assertNotNull(fragments); - PRFNamed element = fragments.getElement(); - while ((element instanceof PRFNamedWithAction)) { - { - Assert.assertEquals(element, ((PRFNamedWithAction)element).getRef2()); - element = ((PRFNamedWithAction)element).getPrev(); - } - } - Assert.assertEquals(element, element.getRef()); - } - - @Test - public void testDatatypeRule_01() { - final ParserRuleFragments fragments = this.parseAndValidate("#8 a - a"); - Assert.assertNotNull(fragments); - PRFNamed element = fragments.getElement(); - Assert.assertEquals(element, element.getRef()); - } - - @Test - public void testDatatypeRule_02() { - final ParserRuleFragments fragments = this.parseAndValidate("#8 a.b.c.d"); - Assert.assertNotNull(fragments); - PRFNamed element = fragments.getElement(); - Assert.assertEquals("a.b.c.d", element.getName()); - } - - @Test - public void testDatatypeRule_03() { - final ParserRuleFragments fragments = this.parseAndValidate("#8 a.b.c.d - a.b.c.d"); - Assert.assertNotNull(fragments); - PRFNamed element = fragments.getElement(); - Assert.assertEquals(element, element.getRef()); - } - - @Test - public void testFragmentWithPredicate() { - final ParserRuleFragments fragments = this.parseAndValidate("#9 myName - myName"); - Assert.assertNotNull(fragments); - Assert.assertEquals("myName", fragments.getElement().getName()); - Assert.assertEquals(fragments.getElement(), fragments.getElement().getRef()); - } - - @Test - public void testFragmentRecursive_01() { - final ParserRuleFragments fragments = this.parseAndValidate("#10 myName myPrev"); - Assert.assertNotNull(fragments); - Assert.assertEquals("myName", fragments.getElement().getName()); - PRFNamed _element = fragments.getElement(); - final PRFNamed prev = ((PRFNamedWithAction) _element).getPrev(); - Assert.assertEquals("myPrev", prev.getName()); - final ICompositeNode node = NodeModelUtils.findActualNodeFor(prev); - Assert.assertEquals(" myPrev", node.getText()); - final EObject lookup = NodeModelUtils.findActualSemanticObjectFor(node); - Assert.assertSame(prev, lookup); - } - - @Test - public void testFragmentRecursive_02() { - final ParserRuleFragments fragments = this.parseAndValidate("#10 myName ((myPrev))"); - Assert.assertNotNull(fragments); - Assert.assertEquals("myName", fragments.getElement().getName()); - PRFNamed _element = fragments.getElement(); - final PRFNamed prev = ((PRFNamedWithAction) _element).getPrev(); - Assert.assertEquals("myPrev", prev.getName()); - final ICompositeNode node = NodeModelUtils.findActualNodeFor(prev); - Assert.assertEquals(" ((myPrev))", node.getText()); - final EObject lookup = NodeModelUtils.findActualSemanticObjectFor(node); - Assert.assertSame(prev, lookup); - } - - @Test - public void testFragmentRecursive_03() { - final ParserRuleFragments fragments = this.parseAndValidate("#11 myName myPrev"); - Assert.assertNotNull(fragments); - Assert.assertEquals("myName", fragments.getElement().getName()); - PRFNamed _element = fragments.getElement(); - final PRFNamed prev = ((PRFNamedWithAction) _element).getPrev(); - Assert.assertEquals("myPrev", prev.getName()); - final ICompositeNode node = NodeModelUtils.findActualNodeFor(prev); - Assert.assertEquals(" myPrev", node.getText()); - final EObject lookup = NodeModelUtils.findActualSemanticObjectFor(node); - Assert.assertSame(prev, lookup); - } - - @Test - public void testFragmentRecursive_04() { - final ParserRuleFragments fragments = this.parseAndValidate("#11 myName ((myPrev))"); - Assert.assertNotNull(fragments); - Assert.assertEquals("myName", fragments.getElement().getName()); - PRFNamed _element = fragments.getElement(); - final PRFNamed prev = ((PRFNamedWithAction) _element).getPrev(); - Assert.assertEquals("myPrev", prev.getName()); - final ICompositeNode node = NodeModelUtils.findActualNodeFor(prev); - Assert.assertEquals("myPrev", node.getText()); - final EObject lookup = NodeModelUtils.findActualSemanticObjectFor(node); - Assert.assertSame(prev, lookup); - } - - protected ParserRuleFragments parseAndValidate(final CharSequence s) { - try { - final ParserRuleFragments result = this.parseHelper.parse(s); - this.validationTestHelper.assertNoIssues(result); - Resource _eResource = result.eResource(); - final XtextResource resource = ((XtextResource) _eResource); - final ICompositeNode node = resource.getParseResult().getRootNode(); - this.invariantChecker.checkInvariant(node); - return result; - } catch (Throwable _e) { - throw Exceptions.sneakyThrow(_e); - } - } -} diff --git a/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/xtext/generator/GrammarAccessExtensionsTest.java b/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/xtext/generator/GrammarAccessExtensionsTest.java deleted file mode 100644 index 4d1df6263..000000000 --- a/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/xtext/generator/GrammarAccessExtensionsTest.java +++ /dev/null @@ -1,60 +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.xtext.generator; - -import org.eclipse.xtext.xbase.lib.Extension; -import org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessExtensions; -import org.junit.Assert; -import org.junit.Test; - -/** - * @author Sebastian Zarnekow - Initial contribution and API - */ -@SuppressWarnings("all") -public class GrammarAccessExtensionsTest { - @Extension - private GrammarAccessExtensions _grammarAccessExtensions = new GrammarAccessExtensions(); - - @Test - public void testToJavaIdentifier() { - Assert.assertEquals("FooBar", this._grammarAccessExtensions.toJavaIdentifier("foo Bar", true)); - Assert.assertEquals("Foo", this._grammarAccessExtensions.toJavaIdentifier("foo;", true)); - Assert.assertEquals("foo", this._grammarAccessExtensions.toJavaIdentifier("foo;", false)); - Assert.assertEquals("Colon", this._grammarAccessExtensions.toJavaIdentifier(":", true)); - Assert.assertEquals("Colon", this._grammarAccessExtensions.toJavaIdentifier(":", false)); - Assert.assertEquals("Semicolon", this._grammarAccessExtensions.toJavaIdentifier(";", false)); - Assert.assertEquals("CommercialAtApostrophe", this._grammarAccessExtensions.toJavaIdentifier("@\'", false)); - Assert.assertEquals("Grün", this._grammarAccessExtensions.toJavaIdentifier("Grün", true)); - Assert.assertEquals("DollarSign", this._grammarAccessExtensions.toJavaIdentifier("$", true)); - Assert.assertEquals("_", this._grammarAccessExtensions.toJavaIdentifier("_", true)); - } - - /** - * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=298492 - */ - @Test - public void testBug() throws Exception { - Assert.assertEquals("HiraganaLetterRu", this._grammarAccessExtensions.toJavaIdentifier("\u308b", true)); - } - - @Test - public void testSmoke() throws Exception { - for (int i = 0; (i < 4000); i++) { - { - final String identifier = this._grammarAccessExtensions.toJavaIdentifier(String.valueOf(((char) i)), false); - for (int j = 0; (j < identifier.length()); j++) { - { - final char charAt = identifier.charAt(j); - Assert.assertTrue(((identifier + ":") + Character.valueOf(charAt)), this._grammarAccessExtensions.isValidJavaLatinIdentifier(charAt, (j == 0))); - } - } - } - } - } -} diff --git a/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/xtext/generator/WizardConfigTest.java b/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/xtext/generator/WizardConfigTest.java deleted file mode 100644 index 8db82ab21..000000000 --- a/org.eclipse.xtext.tests/xtend-gen/org/eclipse/xtext/xtext/generator/WizardConfigTest.java +++ /dev/null @@ -1,71 +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.xtext.generator; - -import com.google.inject.Guice; -import com.google.inject.Injector; -import org.eclipse.xtext.xbase.lib.ObjectExtensions; -import org.eclipse.xtext.xbase.lib.Procedures.Procedure1; -import org.eclipse.xtext.xtext.generator.DefaultGeneratorModule; -import org.eclipse.xtext.xtext.generator.model.project.BundleProjectConfig; -import org.eclipse.xtext.xtext.generator.model.project.StandardProjectConfig; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -/** - * @author Sebastian Zarnekow - Initial contribution and API - */ -@SuppressWarnings("all") -public class WizardConfigTest { - private Injector injector; - - @Before - public void createInjector() { - DefaultGeneratorModule _defaultGeneratorModule = new DefaultGeneratorModule(); - this.injector = Guice.createInjector(_defaultGeneratorModule); - } - - @Test - public void testMavenProjectNames() { - StandardProjectConfig _standardProjectConfig = new StandardProjectConfig(); - final Procedure1 _function = (StandardProjectConfig it) -> { - it.setBaseName("com.acme"); - it.setMavenLayout(true); - BundleProjectConfig _runtimeTest = it.getRuntimeTest(); - _runtimeTest.setEnabled(true); - BundleProjectConfig _eclipsePlugin = it.getEclipsePlugin(); - _eclipsePlugin.setEnabled(true); - BundleProjectConfig _eclipsePluginTest = it.getEclipsePluginTest(); - _eclipsePluginTest.setEnabled(true); - }; - final StandardProjectConfig cfg = ObjectExtensions.operator_doubleArrow(_standardProjectConfig, _function); - cfg.initialize(this.injector); - Assert.assertEquals("com.acme", cfg.getRuntimeTest().getName()); - Assert.assertEquals("com.acme.ui", cfg.getEclipsePluginTest().getName()); - } - - @Test - public void testPlainProjectNames() { - StandardProjectConfig _standardProjectConfig = new StandardProjectConfig(); - final Procedure1 _function = (StandardProjectConfig it) -> { - it.setBaseName("com.acme"); - BundleProjectConfig _runtimeTest = it.getRuntimeTest(); - _runtimeTest.setEnabled(true); - BundleProjectConfig _eclipsePlugin = it.getEclipsePlugin(); - _eclipsePlugin.setEnabled(true); - BundleProjectConfig _eclipsePluginTest = it.getEclipsePluginTest(); - _eclipsePluginTest.setEnabled(true); - }; - final StandardProjectConfig cfg = ObjectExtensions.operator_doubleArrow(_standardProjectConfig, _function); - cfg.initialize(this.injector); - Assert.assertEquals("com.acme.tests", cfg.getRuntimeTest().getName()); - Assert.assertEquals("com.acme.ui.tests", cfg.getEclipsePluginTest().getName()); - } -} diff --git a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/grammarAccess/FragmentFakingEcoreResource.java b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/grammarAccess/FragmentFakingEcoreResource.java new file mode 100644 index 000000000..43f0dc176 --- /dev/null +++ b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/grammarAccess/FragmentFakingEcoreResource.java @@ -0,0 +1,101 @@ +/** + * 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.xtext.generator.grammarAccess; + +import java.util.HashSet; +import java.util.Set; + +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.EClassifier; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EPackage; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.emf.ecore.xmi.XMLResource; +import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl; +import org.eclipse.emf.ecore.xmi.impl.URIHandlerImpl; +import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl; +import org.eclipse.xtext.util.Wrapper; + +public class FragmentFakingEcoreResource extends XMIResourceImpl { + public static class FactoryImpl extends EcoreResourceFactoryImpl { + public static final String ECORE_SUFFIX = "ecore"; + + private final Wrapper isSaving; + + @Override + public Resource createResource(URI uri) { + return new FragmentFakingEcoreResource(uri, isSaving); + } + + public FactoryImpl(Wrapper isSaving) { + this.isSaving = isSaving; + } + } + + private final Wrapper isSaving; + + public FragmentFakingEcoreResource(URI uri, Wrapper isSaving) { + super(uri); + this.isSaving = isSaving; + this.encoding = "UTF-8"; + this.getDefaultSaveOptions().put(XMLResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, true); + this.getDefaultSaveOptions().put(XMLResource.OPTION_LINE_WIDTH, 80); + getDefaultSaveOptions().put(XMLResource.OPTION_URI_HANDLER, new URIHandlerImpl.PlatformSchemeAware()); + } + + @Override + protected boolean useIDs() { + return eObjectToIDMap != null || idToEObjectMap != null; + } + + @Override + public String getURIFragment(EObject eObject) { + if (isSaving.get()) { + if (eObject instanceof EClassifier) { + String result = getURIFragment((EClassifier) eObject); + if (result != null) { + return result; + } + } + } + return super.getURIFragment(eObject); + } + + public String getURIFragment(EClassifier classifier) { + if (classifier.getEPackage().getESuperPackage() != null) { + StringBuilder result = new StringBuilder(60); + calculateURIFragment(classifier.getEPackage(), result, new HashSet<>()); + result.append(classifier.getName()); + return result.toString(); + } + return null; + } + + private void calculateURIFragment(EPackage ePackage, StringBuilder result, Set visited) { + if (!visited.add(ePackage)) { + throw new IllegalStateException(); + } + if (ePackage.getESuperPackage() != null) { + if (ePackage.eResource() == ePackage.getESuperPackage().eResource()) { + calculateURIFragment(ePackage.getESuperPackage(), result, visited); + if (!ePackage.getEClassifiers().isEmpty()) { + if (result.length() != 0) { + result.append(ePackage.getName()).append("/"); + } else { + result.append("//"); + } + } + } else { + result.append("//"); + } + } else { + result.append("//"); + } + } +} diff --git a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/grammarAccess/FragmentFakingEcoreResource.xtend b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/grammarAccess/FragmentFakingEcoreResource.xtend deleted file mode 100644 index cb43bb0f4..000000000 --- a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/grammarAccess/FragmentFakingEcoreResource.xtend +++ /dev/null @@ -1,97 +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.xtext.generator.grammarAccess - -import java.util.Set -import org.eclipse.emf.common.util.URI -import org.eclipse.emf.ecore.EClassifier -import org.eclipse.emf.ecore.EObject -import org.eclipse.emf.ecore.EPackage -import org.eclipse.emf.ecore.xmi.XMLResource -import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl -import org.eclipse.emf.ecore.xmi.impl.URIHandlerImpl -import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl -import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor -import org.eclipse.xtext.util.Wrapper - -class FragmentFakingEcoreResource extends XMIResourceImpl { - - val Wrapper isSaving - - new(URI uri, Wrapper isSaving) { - super(uri) - this.isSaving = isSaving - encoding = "UTF-8" - getDefaultSaveOptions.put(XMLResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, true) - getDefaultSaveOptions.put(XMLResource.OPTION_LINE_WIDTH, 80) - getDefaultSaveOptions.put(XMLResource.OPTION_URI_HANDLER, new URIHandlerImpl.PlatformSchemeAware) - } - - override protected boolean useIDs() { - eObjectToIDMap !== null || idToEObjectMap !== null - } - - override String getURIFragment(EObject eObject) { - if (isSaving.get) { - if (eObject instanceof EClassifier) { - val result = eObject.URIFragment - if (result !== null) - return result - } - } - return super.getURIFragment(eObject) - } - - def String getURIFragment(EClassifier classifier) { - // We need to handle empty subpackages in a special way - if (classifier.EPackage.ESuperPackage !== null) { - val result = new StringBuilder(60) - calculateURIFragment(classifier.EPackage, result, newHashSet) - result.append(classifier.name) - return result.toString - } - return null - } - - def private void calculateURIFragment(EPackage ePackage, StringBuilder result, Set visited) { - if (!visited.add(ePackage)) { - throw new IllegalStateException - } - if (ePackage.ESuperPackage !== null) { - if (ePackage.eResource === ePackage.ESuperPackage.eResource) { - calculateURIFragment(ePackage.ESuperPackage, result, visited) - if (!ePackage.EClassifiers.empty) { - if (result.length !== 0) { - result.append(ePackage.name).append('/') - } else { - result.append('//') - } - } - } else { - result.append('//') - } - } else { - result.append('//') - } - } - - @FinalFieldsConstructor - static class FactoryImpl extends EcoreResourceFactoryImpl { - - public static final String ECORE_SUFFIX = "ecore"; - - val Wrapper isSaving - - override createResource(URI uri) { - return new FragmentFakingEcoreResource(uri, isSaving) - } - - } - -} diff --git a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/model/GuiceModuleAccess.java b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/model/GuiceModuleAccess.java new file mode 100644 index 000000000..022433649 --- /dev/null +++ b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/model/GuiceModuleAccess.java @@ -0,0 +1,443 @@ +/** + * 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.xtext.generator.model; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import org.apache.log4j.Logger; +import org.eclipse.xtend2.lib.StringConcatenationClient; +import org.eclipse.xtext.xbase.lib.util.ToStringBuilder; + +import com.google.common.base.Objects; + +/** + * Configuration object for Guice modules based on + * {@link org.eclipse.xtext.service.AbstractGenericModule}. + */ +public class GuiceModuleAccess { + + private static final Logger LOG = Logger.getLogger(GuiceModuleAccess.class); + + public static class BindKey { + private final String name; + + private final TypeReference type; + + private final boolean singleton; + + private final boolean eagerSingleton; + + @Override + public boolean equals(Object other) { + if (other instanceof GuiceModuleAccess.BindKey) { + return Objects.equal(this.name, ((GuiceModuleAccess.BindKey) other).name) + && Objects.equal(this.type, ((GuiceModuleAccess.BindKey) other).type); + } else { + return false; + } + } + + @Override + public int hashCode() { + int h = 0; + if (name != null) { + h = h + name.hashCode(); + } + if (type != null) { + h = h + type.hashCode(); + } + return h; + } + + public BindKey(String name, TypeReference type, boolean singleton, boolean eagerSingleton) { + this.name = name; + this.type = type; + this.singleton = singleton; + this.eagerSingleton = eagerSingleton; + } + + @Override + public String toString() { + ToStringBuilder b = new ToStringBuilder(this); + b.add("name", name); + b.add("type", type); + b.add("singleton", singleton); + b.add("eagerSingleton", eagerSingleton); + return b.toString(); + } + + public String getName() { + return name; + } + + public TypeReference getType() { + return type; + } + + public boolean isSingleton() { + return singleton; + } + + public boolean isEagerSingleton() { + return eagerSingleton; + } + } + + public static class BindValue { + private final Object expression; + + private final TypeReference type; + + private final boolean provider; + + private final List statements; + + public BindValue(Object expression, TypeReference type, boolean provider, List statements) { + this.expression = expression; + this.type = type; + this.provider = provider; + this.statements = statements; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.expression == null) ? 0 : this.expression.hashCode()); + result = prime * result + ((this.type == null) ? 0 : this.type.hashCode()); + result = prime * result + (this.provider ? 1231 : 1237); + return prime * result + ((this.statements == null) ? 0 : this.statements.hashCode()); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + GuiceModuleAccess.BindValue other = (GuiceModuleAccess.BindValue) obj; + if (this.expression == null) { + if (other.expression != null) + return false; + } else if (!this.expression.equals(other.expression)) + return false; + if (this.type == null) { + if (other.type != null) + return false; + } else if (!this.type.equals(other.type)) + return false; + if (other.provider != this.provider) + return false; + if (this.statements == null) { + if (other.statements != null) + return false; + } else if (!this.statements.equals(other.statements)) + return false; + return true; + } + + @Override + public String toString() { + ToStringBuilder b = new ToStringBuilder(this); + b.add("expression", expression); + b.add("type", type); + b.add("provider", provider); + b.add("statements", statements); + return b.toString(); + } + + public Object getExpression() { + return expression; + } + + public TypeReference getType() { + return type; + } + + public boolean isProvider() { + return provider; + } + + public List getStatements() { + return statements; + } + } + + public static class Binding { + private final GuiceModuleAccess.BindKey key; + + private final GuiceModuleAccess.BindValue value; + + private final boolean isFinal; + + private final String contributedBy; + + @Override + public boolean equals(Object other) { + if (other instanceof GuiceModuleAccess.Binding) { + return Objects.equal(this.key, ((GuiceModuleAccess.Binding) other).key); + } else { + return false; + } + } + + @Override + public int hashCode() { + return key.hashCode(); + } + + public Binding(GuiceModuleAccess.BindKey key, GuiceModuleAccess.BindValue value, boolean isFinal, + String contributedBy) { + this.key = key; + this.value = value; + this.isFinal = isFinal; + this.contributedBy = contributedBy; + } + + @Override + public String toString() { + ToStringBuilder b = new ToStringBuilder(this); + b.add("key", key); + b.add("value", value); + b.add("isFinal", isFinal); + b.add("contributedBy", contributedBy); + return b.toString(); + } + + public GuiceModuleAccess.BindKey getKey() { + return key; + } + + public GuiceModuleAccess.BindValue getValue() { + return value; + } + + public boolean isFinal() { + return isFinal; + } + + public String getContributedBy() { + return contributedBy; + } + } + + public static class BindingFactory { + private final String contributedBy; + + private final Set bindings = new LinkedHashSet<>(); + + public BindingFactory() { + this.contributedBy = new Exception().getStackTrace()[1].getClassName(); + } + + public BindingFactory(String contributedBy) { + this.contributedBy = contributedBy; + } + + private void add(GuiceModuleAccess.BindKey type, GuiceModuleAccess.BindValue expr) { + add(type, expr, false); + } + + private void add(GuiceModuleAccess.BindKey type, GuiceModuleAccess.BindValue expr, boolean isFinal) { + add(new GuiceModuleAccess.Binding(type, expr, isFinal, contributedBy)); + } + + private void add(GuiceModuleAccess.Binding binding) { + if (!bindings.add(binding)) { + throw new IllegalArgumentException( + "Duplicate binding for " + binding.key + " in " + this.contributedBy); + } + } + + private GuiceModuleAccess.BindKey key(TypeReference type) { + return new GuiceModuleAccess.BindKey(null, type, false, false); + } + + private GuiceModuleAccess.BindKey key(String name) { + return new GuiceModuleAccess.BindKey(name, null, false, false); + } + + private GuiceModuleAccess.BindKey eagerSingleton(TypeReference type) { + return new GuiceModuleAccess.BindKey(null, type, true, true); + } + + private GuiceModuleAccess.BindKey singleton(TypeReference type) { + return new GuiceModuleAccess.BindKey(null, type, true, false); + } + + private GuiceModuleAccess.BindValue value(TypeReference type) { + return new GuiceModuleAccess.BindValue(null, type, false, Collections.emptyList()); + } + + private GuiceModuleAccess.BindValue expr(Object expr) { + return new GuiceModuleAccess.BindValue(expr, null, false, Collections.emptyList()); + } + + private GuiceModuleAccess.BindValue provider(TypeReference type) { + return new GuiceModuleAccess.BindValue(null, type, true, Collections.emptyList()); + } + + private GuiceModuleAccess.BindValue providerExpr(Object expr) { + return new GuiceModuleAccess.BindValue(expr, null, true, Collections.emptyList()); + } + + private GuiceModuleAccess.BindValue statements(Object[] statements) { + return new GuiceModuleAccess.BindValue(null, null, false, Arrays.asList(statements)); + } + + public GuiceModuleAccess.BindingFactory addTypeToInstance(TypeReference type, + StringConcatenationClient expression) { + add(key(type), expr(expression)); + return this; + } + + public GuiceModuleAccess.BindingFactory addTypeToProviderInstance(TypeReference type, + StringConcatenationClient expression) { + add(key(type), providerExpr(expression)); + return this; + } + + public GuiceModuleAccess.BindingFactory addConfiguredBinding(String name, StringConcatenationClient statement) { + add(key(name), statements(new Object[] { statement })); + return this; + } + + public GuiceModuleAccess.BindingFactory addTypeToType(TypeReference keyType, TypeReference valueType) { + add(key(keyType), value(valueType)); + return this; + } + + public GuiceModuleAccess.BindingFactory addTypeToTypeSingleton(TypeReference keyType, TypeReference valueType) { + add(singleton(keyType), value(valueType)); + return this; + } + + public GuiceModuleAccess.BindingFactory addTypeToTypeEagerSingleton(TypeReference keyType, + TypeReference valueType) { + add(eagerSingleton(keyType), value(valueType)); + return this; + } + + public GuiceModuleAccess.BindingFactory addTypeToProvider(TypeReference keyType, TypeReference valueType) { + add(key(keyType), provider(valueType)); + return this; + } + + public GuiceModuleAccess.BindingFactory addTypeToProviderSingleton(TypeReference keyType, + TypeReference valueType) { + this.add(this.singleton(keyType), this.provider(valueType)); + return this; + } + + public GuiceModuleAccess.BindingFactory addTypeToProviderEagerSingleton(TypeReference keyType, + TypeReference valueType) { + add(eagerSingleton(keyType), provider(valueType)); + return this; + } + + public GuiceModuleAccess.BindingFactory addfinalTypeToType(TypeReference keyType, TypeReference valueType) { + add(key(keyType), value(valueType), true); + return this; + } + + public GuiceModuleAccess.BindingFactory addfinalTypeToTypeSingleton(TypeReference keyType, + TypeReference valueType) { + add(singleton(keyType), value(valueType), true); + return this; + } + + public GuiceModuleAccess.BindingFactory addfinalTypeToTypeEagerSingleton(TypeReference keyType, + TypeReference valueType) { + add(eagerSingleton(keyType), value(valueType), true); + return this; + } + + public GuiceModuleAccess.BindingFactory addfinalTypeToProvider(TypeReference keyType, TypeReference valueType) { + add(key(keyType), provider(valueType), true); + return this; + } + + public GuiceModuleAccess.BindingFactory addfinalTypeToProviderSingleton(TypeReference keyType, + TypeReference valueType) { + add(singleton(keyType), provider(valueType), true); + return this; + } + + public GuiceModuleAccess.BindingFactory addfinalTypeToProviderEagerSingleton(TypeReference keyType, + TypeReference valueType) { + add(eagerSingleton(keyType), provider(valueType), true); + return this; + } + + public void contributeTo(GuiceModuleAccess module) { + module.addAll(bindings); + } + + public String getContributedBy() { + return contributedBy; + } + } + + private final Set bindings = new LinkedHashSet<>(); + + private TypeReference superClass; + + public void add(GuiceModuleAccess.Binding newBinding) { + if (bindings.contains(newBinding)) { + Iterator iterator = bindings.iterator(); + boolean found = false; + while (iterator.hasNext() && !found) { + GuiceModuleAccess.Binding oldBinding = iterator.next(); + if (Objects.equal(oldBinding, newBinding)) { + if (oldBinding.isFinal) { + if (newBinding.isFinal) { + throw new IllegalStateException( + "Conflicting final bindings for '" + oldBinding.key.type + "' from fragments " + + oldBinding.contributedBy + " and " + newBinding.contributedBy); + } else { + GuiceModuleAccess.LOG.warn("Cannot override final binding '" + oldBinding + "'. " + + "Ignoring binding from fragment '" + newBinding.contributedBy + "'"); + } + } else { + GuiceModuleAccess.LOG.debug("replacing binding : " + oldBinding); + GuiceModuleAccess.LOG.debug(" with new binding : " + newBinding); + iterator.remove(); + } + found = true; + } + } + } + bindings.add(newBinding); + } + + public void addAll(Iterable bindings) { + for (GuiceModuleAccess.Binding binding : bindings) { + add(binding); + } + } + + public Set getBindings() { + return Collections.unmodifiableSet(bindings); + } + + public TypeReference getSuperClass() { + return superClass; + } + + public void setSuperClass(TypeReference superClass) { + this.superClass = superClass; + } +} diff --git a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/model/GuiceModuleAccess.xtend b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/model/GuiceModuleAccess.xtend deleted file mode 100644 index 167b8e9fa..000000000 --- a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/model/GuiceModuleAccess.xtend +++ /dev/null @@ -1,261 +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.xtext.generator.model - -import java.util.Collections -import java.util.List -import java.util.Set -import org.eclipse.xtend.lib.annotations.Accessors -import org.eclipse.xtend.lib.annotations.Data -import org.eclipse.xtend2.lib.StringConcatenationClient -import org.eclipse.xtext.util.internal.Log - -/** - * Configuration object for Guice modules based on {@link org.eclipse.xtext.service.AbstractGenericModule}. - */ -@Log -class GuiceModuleAccess { - - @Data - static class BindKey { - String name - TypeReference type - boolean singleton - boolean eagerSingleton - - override equals(Object other) { - if (other instanceof BindKey) - this.name == other.name && this.type == other.type - else - false - } - - override hashCode() { - var h = 0 - if (name !== null) h += name.hashCode - if (type !== null) h += type.hashCode - return h - } - } - - @Data - static class BindValue { - Object expression - TypeReference type - boolean provider - List statements - } - - @Data - static class Binding { - BindKey key - BindValue value - boolean isFinal - String contributedBy - - override equals(Object other) { - if (other instanceof Binding) - this.key == other.key - else - false - } - - override hashCode() { - key.hashCode - } - } - - val Set bindings = newLinkedHashSet - - @Accessors - TypeReference superClass - - def void add(Binding newBinding) { - if (bindings.contains(newBinding)) { - val iterator = bindings.iterator() - var found = false - while (iterator.hasNext && !found) { - val oldBinding = iterator.next - if (oldBinding == newBinding) { - if (oldBinding.isFinal) { - if (newBinding.isFinal) { - throw new IllegalStateException("Conflicting final bindings for '" + oldBinding.key.type + "' from fragments " - + oldBinding.contributedBy + " and " + newBinding.contributedBy) - } else { - LOG.warn("Cannot override final binding '" + oldBinding + "'. " - + "Ignoring binding from fragment '" + newBinding.contributedBy + "'") - } - } else { - LOG.debug("replacing binding : " + oldBinding) - LOG.debug(" with new binding : " + newBinding) - iterator.remove() - } - found = true - } - } - } - bindings.add(newBinding) - } - - def void addAll(Iterable bindings) { - for (binding : bindings) { - add(binding) - } - } - - def Set getBindings() { - Collections.unmodifiableSet(bindings) - } - - - static class BindingFactory { - - @Accessors - val String contributedBy - - val Set bindings = newLinkedHashSet - - new() { - this.contributedBy = new Exception().stackTrace.get(1).className - } - - new(String contributedBy) { - this.contributedBy = contributedBy - } - - private def add(BindKey type, BindValue expr) { - add(type, expr, false); - } - - private def add(BindKey type, BindValue expr, boolean isFinal) { - add(new Binding(type, expr, isFinal, contributedBy)) - } - - private def add(Binding binding) { - if (!bindings.add(binding)) - throw new IllegalArgumentException("Duplicate binding for " + binding.key + " in " + contributedBy) - } - - private def key(TypeReference type) { - return new BindKey(null, type, false, false) - } - - private def key(String name) { - return new BindKey(name, null, false, false) - } - - private def eagerSingleton(TypeReference type) { - return new BindKey(null, type, true, true) - } - - private def singleton(TypeReference type) { - return new BindKey(null, type, true, false) - } - - private def value(TypeReference type) { - return new BindValue(null, type, false, Collections.emptyList) - } - - private def expr(Object expr) { - return new BindValue(expr, null, false, Collections.emptyList) - } - - private def provider(TypeReference type) { - return new BindValue(null, type, true, Collections.emptyList) - } - - private def providerExpr(Object expr) { - return new BindValue(expr, null, true, Collections.emptyList) - } - - private def statements(Object[] statements) { - return new BindValue(null, null, false, statements) - } - - def BindingFactory addTypeToInstance(TypeReference type, StringConcatenationClient expression) { - add(key(type), expr(expression)) - return this - } - - def BindingFactory addTypeToProviderInstance(TypeReference type, StringConcatenationClient expression) { - add(key(type), providerExpr(expression)) - return this - } - - def BindingFactory addConfiguredBinding(String name, StringConcatenationClient statement) { - add(key(name), statements(#[statement])) - return this - } - - def BindingFactory addTypeToType(TypeReference keyType, TypeReference valueType){ - add(key(keyType), value(valueType)) - return this - } - - def BindingFactory addTypeToTypeSingleton(TypeReference keyType, TypeReference valueType){ - add(singleton(keyType), value(valueType)) - return this - } - - def BindingFactory addTypeToTypeEagerSingleton(TypeReference keyType, TypeReference valueType){ - add(eagerSingleton(keyType), value(valueType)) - return this - } - - def BindingFactory addTypeToProvider(TypeReference keyType, TypeReference valueType){ - add(key(keyType), provider(valueType)) - return this - } - - def BindingFactory addTypeToProviderSingleton(TypeReference keyType, TypeReference valueType){ - add(singleton(keyType), provider(valueType)) - return this - } - - def BindingFactory addTypeToProviderEagerSingleton(TypeReference keyType, TypeReference valueType){ - add(eagerSingleton(keyType), provider(valueType)) - return this - } - - def BindingFactory addfinalTypeToType(TypeReference keyType, TypeReference valueType){ - add(key(keyType), value(valueType), true) - return this - } - - def BindingFactory addfinalTypeToTypeSingleton(TypeReference keyType, TypeReference valueType){ - add(singleton(keyType), value(valueType), true) - return this - } - - def BindingFactory addfinalTypeToTypeEagerSingleton(TypeReference keyType, TypeReference valueType){ - add(eagerSingleton(keyType), value(valueType), true) - return this - } - - def BindingFactory addfinalTypeToProvider(TypeReference keyType, TypeReference valueType){ - add(key(keyType), provider(valueType), true) - return this - } - - def BindingFactory addfinalTypeToProviderSingleton(TypeReference keyType, TypeReference valueType){ - add(singleton(keyType), provider(valueType), true) - return this - } - - def BindingFactory addfinalTypeToProviderEagerSingleton(TypeReference keyType, TypeReference valueType){ - add(eagerSingleton(keyType), provider(valueType), true) - return this - } - - def void contributeTo(GuiceModuleAccess module) { - module.addAll(this.bindings) - } - } - -} diff --git a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/model/project/SubProjectConfig.java b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/model/project/SubProjectConfig.java new file mode 100644 index 000000000..482e87741 --- /dev/null +++ b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/model/project/SubProjectConfig.java @@ -0,0 +1,168 @@ +/** + * 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.xtext.generator.model.project; + +import org.eclipse.xtext.xtext.generator.Issues; +import org.eclipse.xtext.xtext.generator.model.IXtextGeneratorFileSystemAccess; + +import com.google.common.base.Strings; +import com.google.inject.Inject; +import com.google.inject.Injector; + +/** + * Configuration of subprojects. + * + * @noextend This class should not be extended by clients. + */ +public class SubProjectConfig implements ISubProjectConfig { + @Inject + private XtextProjectConfig owner; + + private boolean enabled; + + private boolean overwriteSrc; + + private String name; + + private String rootPath; + + private IXtextGeneratorFileSystemAccess root; + + private String metaInfPath; + + private IXtextGeneratorFileSystemAccess metaInf; + + private String srcPath; + + private IXtextGeneratorFileSystemAccess src; + + private String srcGenPath; + + private IXtextGeneratorFileSystemAccess srcGen; + + private String iconsPath; + + private IXtextGeneratorFileSystemAccess icons; + + public void setRoot(String path) { + this.rootPath = path; + } + + public void setMetaInf(String path) { + this.metaInfPath = path; + } + + public void setSrc(String path) { + this.srcPath = path; + } + + public void setSrcGen(String path) { + this.srcGenPath = path; + } + + public void setIcons(String path) { + this.iconsPath = path; + } + + public void checkConfiguration(Issues issues) { + } + + @Override + public void initialize(Injector injector) { + injector.injectMembers(this); + if (!Strings.isNullOrEmpty(rootPath)) { + root = owner.newFileSystemAccess(rootPath, true); + root.initialize(injector); + } + if (!Strings.isNullOrEmpty(metaInfPath)) { + metaInf = owner.newFileSystemAccess(metaInfPath, true); + metaInf.initialize(injector); + } + if (!Strings.isNullOrEmpty(srcPath)) { + src = owner.newFileSystemAccess(srcPath, overwriteSrc); + src.initialize(injector); + } + if (!Strings.isNullOrEmpty(srcGenPath)) { + srcGen = owner.newFileSystemAccess(srcGenPath, true); + srcGen.initialize(injector); + } + if (!Strings.isNullOrEmpty(iconsPath)) { + icons = owner.newFileSystemAccess(iconsPath, true); + icons.initialize(injector); + } + } + + public XtextProjectConfig getOwner() { + return owner; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public boolean isOverwriteSrc() { + return overwriteSrc; + } + + public void setOverwriteSrc(boolean overwriteSrc) { + this.overwriteSrc = overwriteSrc; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getRootPath() { + return rootPath; + } + + public IXtextGeneratorFileSystemAccess getRoot() { + return root; + } + + public String getMetaInfPath() { + return metaInfPath; + } + + public IXtextGeneratorFileSystemAccess getMetaInf() { + return metaInf; + } + + public String getSrcPath() { + return srcPath; + } + + public IXtextGeneratorFileSystemAccess getSrc() { + return src; + } + + public String getSrcGenPath() { + return srcGenPath; + } + + public IXtextGeneratorFileSystemAccess getSrcGen() { + return srcGen; + } + + public String getIconsPath() { + return iconsPath; + } + + public IXtextGeneratorFileSystemAccess getIcons() { + return icons; + } +} diff --git a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/model/project/SubProjectConfig.xtend b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/model/project/SubProjectConfig.xtend deleted file mode 100644 index 0d3480c88..000000000 --- a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/model/project/SubProjectConfig.xtend +++ /dev/null @@ -1,114 +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.xtext.generator.model.project - -import com.google.inject.Inject -import com.google.inject.Injector -import org.eclipse.xtend.lib.annotations.Accessors -import org.eclipse.xtext.xtext.generator.Issues -import org.eclipse.xtext.xtext.generator.model.IXtextGeneratorFileSystemAccess - -/** - * Configuration of subprojects. - * - * @noextend This class should not be extended by clients. - */ -class SubProjectConfig implements ISubProjectConfig { - - @Inject - @Accessors(PUBLIC_GETTER) - XtextProjectConfig owner - - @Accessors - boolean enabled - - @Accessors - boolean overwriteSrc - - @Accessors - String name - - @Accessors(PUBLIC_GETTER) - String rootPath - - @Accessors(PUBLIC_GETTER) - IXtextGeneratorFileSystemAccess root - - @Accessors(PUBLIC_GETTER) - String metaInfPath - - @Accessors(PUBLIC_GETTER) - IXtextGeneratorFileSystemAccess metaInf - - @Accessors(PUBLIC_GETTER) - String srcPath - - @Accessors(PUBLIC_GETTER) - IXtextGeneratorFileSystemAccess src - - @Accessors(PUBLIC_GETTER) - String srcGenPath - - @Accessors(PUBLIC_GETTER) - IXtextGeneratorFileSystemAccess srcGen - - @Accessors(PUBLIC_GETTER) - String iconsPath - - @Accessors(PUBLIC_GETTER) - IXtextGeneratorFileSystemAccess icons - - def void setRoot(String path) { - rootPath = path - } - - def void setMetaInf(String path) { - metaInfPath = path - } - - def void setSrc(String path) { - srcPath = path - } - - def void setSrcGen(String path) { - srcGenPath = path - } - - def void setIcons(String path) { - iconsPath = path - } - - def void checkConfiguration(Issues issues) { - } - - override initialize(Injector injector) { - injector.injectMembers(this) - if (!rootPath.isNullOrEmpty) { - root = owner.newFileSystemAccess(rootPath, true) - root.initialize(injector) - } - if (!metaInfPath.isNullOrEmpty) { - metaInf = owner.newFileSystemAccess(metaInfPath, true) - metaInf.initialize(injector) - } - if (!srcPath.isNullOrEmpty) { - src = owner.newFileSystemAccess(srcPath, overwriteSrc) - src.initialize(injector) - } - if (!srcGenPath.isNullOrEmpty) { - srcGen = owner.newFileSystemAccess(srcGenPath, true) - srcGen.initialize(injector) - } - if (!iconsPath.isNullOrEmpty) { - icons = owner.newFileSystemAccess(iconsPath, true) - icons.initialize(injector) - } - } - -} diff --git a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/parser/antlr/CombinedGrammarMarker.java b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/parser/antlr/CombinedGrammarMarker.java new file mode 100644 index 000000000..fcb264285 --- /dev/null +++ b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/parser/antlr/CombinedGrammarMarker.java @@ -0,0 +1,104 @@ +/** + * 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.xtext.generator.parser.antlr; + +import java.util.List; +import org.eclipse.emf.common.notify.Adapter; +import org.eclipse.emf.common.notify.Notifier; +import org.eclipse.emf.common.notify.impl.AdapterImpl; +import org.eclipse.xtext.xbase.lib.util.ToStringBuilder; + +public class CombinedGrammarMarker { + public static class CombinedGrammarMarkerAdapter extends AdapterImpl { + private CombinedGrammarMarker element; + + public CombinedGrammarMarkerAdapter(CombinedGrammarMarker element) { + this.element = element; + } + + public CombinedGrammarMarker get() { + return element; + } + + @Override + public boolean isAdapterForType(Object object) { + return object == CombinedGrammarMarker.class; + } + } + + private boolean isCombinedGrammar; + + public static CombinedGrammarMarker findInEmfObject(Notifier emfObject) { + for (Adapter adapter : emfObject.eAdapters()) { + if (adapter instanceof CombinedGrammarMarker.CombinedGrammarMarkerAdapter) { + return ((CombinedGrammarMarker.CombinedGrammarMarkerAdapter) adapter).get(); + } + } + return null; + } + + public static CombinedGrammarMarker removeFromEmfObject(Notifier emfObject) { + List adapters = emfObject.eAdapters(); + for (int i = 0, max = adapters.size(); i < max; i++) { + Adapter adapter = adapters.get(i); + if (adapter instanceof CombinedGrammarMarker.CombinedGrammarMarkerAdapter) { + emfObject.eAdapters().remove(i); + return ((CombinedGrammarMarker.CombinedGrammarMarkerAdapter) adapter).get(); + } + } + return null; + } + + public void attachToEmfObject(Notifier emfObject) { + CombinedGrammarMarker result = findInEmfObject(emfObject); + if (result != null) + throw new IllegalStateException( + "The given EMF object already contains an adapter for CombinedGrammarMarker"); + CombinedGrammarMarker.CombinedGrammarMarkerAdapter adapter = new CombinedGrammarMarker.CombinedGrammarMarkerAdapter( + this); + emfObject.eAdapters().add(adapter); + } + + public CombinedGrammarMarker(boolean isCombinedGrammar) { + this.isCombinedGrammar = isCombinedGrammar; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (isCombinedGrammar ? 1231 : 1237); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + CombinedGrammarMarker other = (CombinedGrammarMarker) obj; + if (isCombinedGrammar != other.isCombinedGrammar) + return false; + return true; + } + + @Override + public String toString() { + ToStringBuilder b = new ToStringBuilder(this); + b.add("isCombinedGrammar", isCombinedGrammar); + return b.toString(); + } + + public boolean isCombinedGrammar() { + return isCombinedGrammar; + } +} diff --git a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/parser/antlr/CombinedGrammarMarker.xtend b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/parser/antlr/CombinedGrammarMarker.xtend deleted file mode 100644 index bf7767af0..000000000 --- a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/parser/antlr/CombinedGrammarMarker.xtend +++ /dev/null @@ -1,18 +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.xtext.generator.parser.antlr - -import org.eclipse.xtext.util.internal.EmfAdaptable -import org.eclipse.xtend.lib.annotations.Data - -@EmfAdaptable -@Data -class CombinedGrammarMarker { - boolean isCombinedGrammar -} \ No newline at end of file diff --git a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.xtend b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.xtend index 494837179..81d6c16bf 100644 --- a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.xtend +++ b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.xtend @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2016 itemis AG (http://www.itemis.eu) and others. + * Copyright (c) 2016, 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. @@ -10,8 +10,6 @@ package org.eclipse.xtext.xtext.generator.serializer import java.util.List import java.util.Map -import org.eclipse.emf.ecore.EClass -import org.eclipse.xtend.lib.annotations.Accessors import org.eclipse.xtext.Grammar import org.eclipse.xtext.GrammarUtil import org.eclipse.xtext.ParserRule @@ -75,11 +73,3 @@ class NamedSerializationContextProvider { } } - -@Accessors class NamedSerializationContexts { - val String name - val EClass type - val List contexts - val T value - -} diff --git a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContexts.java b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContexts.java new file mode 100644 index 000000000..1344037d3 --- /dev/null +++ b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContexts.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) 2016, 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.xtext.generator.serializer; + +import java.util.List; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.xtext.serializer.ISerializationContext; + +public class NamedSerializationContexts { + private final String name; + + private final EClass type; + + private final List contexts; + + private final T value; + + public NamedSerializationContexts(String name, EClass type, List contexts, T value) { + this.name = name; + this.type = type; + this.contexts = contexts; + this.value = value; + } + + public String getName() { + return name; + } + + public EClass getType() { + return type; + } + + public List getContexts() { + return contexts; + } + + public T getValue() { + return value; + } +} diff --git a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/serializer/SyntacticSequencerPDA2ExtendedDot.java b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/serializer/SyntacticSequencerPDA2ExtendedDot.java new file mode 100644 index 000000000..a8ebf334f --- /dev/null +++ b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/serializer/SyntacticSequencerPDA2ExtendedDot.java @@ -0,0 +1,49 @@ +/** + * 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.xtext.generator.serializer; + +import java.util.HashSet; +import java.util.Set; + +import org.eclipse.xtext.serializer.analysis.ISyntacticSequencerPDAProvider; +import org.eclipse.xtext.util.GraphvizDotBuilder; + +public class SyntacticSequencerPDA2ExtendedDot extends GraphvizDotBuilder { + @Override + protected GraphvizDotBuilder.Props drawObject(Object obj) { + if (obj instanceof ISyntacticSequencerPDAProvider.ISynState) { + return drawGrammar((ISyntacticSequencerPDAProvider.ISynState) obj); + } + return null; + } + + protected GraphvizDotBuilder.Digraph drawGrammar(ISyntacticSequencerPDAProvider.ISynState pr) { + GraphvizDotBuilder.Digraph d = new GraphvizDotBuilder.Digraph(); + Set visited = new HashSet<>(); + drawState(d, pr, visited); + return d; + } + + protected void drawState(GraphvizDotBuilder.Digraph d, ISyntacticSequencerPDAProvider.ISynState state, + Set visited) { + if (!visited.add(state)) { + return; + } + GraphvizDotBuilder.Node n = new GraphvizDotBuilder.Node(state, state.toString()); + if (!(state instanceof ISyntacticSequencerPDAProvider.ISynAbsorberState)) { + n.setStyle("dotted"); + } + d.add(n); + for (ISyntacticSequencerPDAProvider.ISynState trans : state.getFollowers()) { + GraphvizDotBuilder.Edge edge = new GraphvizDotBuilder.Edge(state, trans); + d.add(edge); + drawState(d, trans, visited); + } + } +} diff --git a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/serializer/SyntacticSequencerPDA2ExtendedDot.xtend b/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/serializer/SyntacticSequencerPDA2ExtendedDot.xtend deleted file mode 100644 index c081adedf..000000000 --- a/org.eclipse.xtext.xtext.generator/src/org/eclipse/xtext/xtext/generator/serializer/SyntacticSequencerPDA2ExtendedDot.xtend +++ /dev/null @@ -1,43 +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.xtext.generator.serializer - -import java.util.Set -import org.eclipse.xtext.serializer.analysis.ISyntacticSequencerPDAProvider.ISynAbsorberState -import org.eclipse.xtext.serializer.analysis.ISyntacticSequencerPDAProvider.ISynState -import org.eclipse.xtext.util.GraphvizDotBuilder - -class SyntacticSequencerPDA2ExtendedDot extends GraphvizDotBuilder { - - override protected Props drawObject(Object obj) { - if (obj instanceof ISynState) - drawGrammar(obj) - } - - def protected Digraph drawGrammar(ISynState pr) { - val d = new Digraph - val Set visited = newHashSet - drawState(d, pr, visited) - return d - } - - def protected void drawState(Digraph d, ISynState state, Set visited) { - if (!visited.add(state)) - return; - val n = new Node(state, state.toString) - if (!(state instanceof ISynAbsorberState)) - n.style = 'dotted' - d.add(n) - for (trans : state.followers) { - val edge = new Edge(state, trans) - d.add(edge) - drawState(d, trans, visited) - } - } -} diff --git a/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/grammarAccess/FragmentFakingEcoreResource.java b/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/grammarAccess/FragmentFakingEcoreResource.java deleted file mode 100644 index 2d68a409a..000000000 --- a/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/grammarAccess/FragmentFakingEcoreResource.java +++ /dev/null @@ -1,121 +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.xtext.generator.grammarAccess; - -import java.util.Map; -import java.util.Set; -import org.eclipse.emf.common.util.URI; -import org.eclipse.emf.ecore.EClassifier; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.ecore.EPackage; -import org.eclipse.emf.ecore.resource.Resource; -import org.eclipse.emf.ecore.xmi.XMLResource; -import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl; -import org.eclipse.emf.ecore.xmi.impl.URIHandlerImpl; -import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl; -import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor; -import org.eclipse.xtext.util.Wrapper; -import org.eclipse.xtext.xbase.lib.CollectionLiterals; - -@SuppressWarnings("all") -public class FragmentFakingEcoreResource extends XMIResourceImpl { - @FinalFieldsConstructor - public static class FactoryImpl extends EcoreResourceFactoryImpl { - public static final String ECORE_SUFFIX = "ecore"; - - private final Wrapper isSaving; - - @Override - public Resource createResource(final URI uri) { - return new FragmentFakingEcoreResource(uri, this.isSaving); - } - - public FactoryImpl(final Wrapper isSaving) { - super(); - this.isSaving = isSaving; - } - } - - private final Wrapper isSaving; - - public FragmentFakingEcoreResource(final URI uri, final Wrapper isSaving) { - super(uri); - this.isSaving = isSaving; - this.encoding = "UTF-8"; - this.getDefaultSaveOptions().put(XMLResource.OPTION_USE_ENCODED_ATTRIBUTE_STYLE, Boolean.valueOf(true)); - this.getDefaultSaveOptions().put(XMLResource.OPTION_LINE_WIDTH, Integer.valueOf(80)); - Map _defaultSaveOptions = this.getDefaultSaveOptions(); - URIHandlerImpl.PlatformSchemeAware _platformSchemeAware = new URIHandlerImpl.PlatformSchemeAware(); - _defaultSaveOptions.put(XMLResource.OPTION_URI_HANDLER, _platformSchemeAware); - } - - @Override - protected boolean useIDs() { - return ((this.eObjectToIDMap != null) || (this.idToEObjectMap != null)); - } - - @Override - public String getURIFragment(final EObject eObject) { - Boolean _get = this.isSaving.get(); - if ((_get).booleanValue()) { - if ((eObject instanceof EClassifier)) { - final String result = this.getURIFragment(((EClassifier)eObject)); - if ((result != null)) { - return result; - } - } - } - return super.getURIFragment(eObject); - } - - public String getURIFragment(final EClassifier classifier) { - EPackage _eSuperPackage = classifier.getEPackage().getESuperPackage(); - boolean _tripleNotEquals = (_eSuperPackage != null); - if (_tripleNotEquals) { - final StringBuilder result = new StringBuilder(60); - this.calculateURIFragment(classifier.getEPackage(), result, CollectionLiterals.newHashSet()); - result.append(classifier.getName()); - return result.toString(); - } - return null; - } - - private void calculateURIFragment(final EPackage ePackage, final StringBuilder result, final Set visited) { - boolean _add = visited.add(ePackage); - boolean _not = (!_add); - if (_not) { - throw new IllegalStateException(); - } - EPackage _eSuperPackage = ePackage.getESuperPackage(); - boolean _tripleNotEquals = (_eSuperPackage != null); - if (_tripleNotEquals) { - Resource _eResource = ePackage.eResource(); - Resource _eResource_1 = ePackage.getESuperPackage().eResource(); - boolean _tripleEquals = (_eResource == _eResource_1); - if (_tripleEquals) { - this.calculateURIFragment(ePackage.getESuperPackage(), result, visited); - boolean _isEmpty = ePackage.getEClassifiers().isEmpty(); - boolean _not_1 = (!_isEmpty); - if (_not_1) { - int _length = result.length(); - boolean _tripleNotEquals_1 = (_length != 0); - if (_tripleNotEquals_1) { - result.append(ePackage.getName()).append("/"); - } else { - result.append("//"); - } - } - } else { - result.append("//"); - } - } else { - result.append("//"); - } - } -} diff --git a/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/model/GuiceModuleAccess.java b/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/model/GuiceModuleAccess.java deleted file mode 100644 index e88d9dadf..000000000 --- a/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/model/GuiceModuleAccess.java +++ /dev/null @@ -1,477 +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.xtext.generator.model; - -import com.google.common.base.Objects; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import org.apache.log4j.Logger; -import org.eclipse.xtend.lib.annotations.Accessors; -import org.eclipse.xtend.lib.annotations.Data; -import org.eclipse.xtend2.lib.StringConcatenationClient; -import org.eclipse.xtext.util.internal.Log; -import org.eclipse.xtext.xbase.lib.CollectionLiterals; -import org.eclipse.xtext.xbase.lib.Conversions; -import org.eclipse.xtext.xbase.lib.Pure; -import org.eclipse.xtext.xbase.lib.util.ToStringBuilder; -import org.eclipse.xtext.xtext.generator.model.TypeReference; - -/** - * Configuration object for Guice modules based on {@link org.eclipse.xtext.service.AbstractGenericModule}. - */ -@Log -@SuppressWarnings("all") -public class GuiceModuleAccess { - @Data - public static class BindKey { - private final String name; - - private final TypeReference type; - - private final boolean singleton; - - private final boolean eagerSingleton; - - @Override - public boolean equals(final Object other) { - boolean _xifexpression = false; - if ((other instanceof GuiceModuleAccess.BindKey)) { - _xifexpression = (Objects.equal(this.name, ((GuiceModuleAccess.BindKey)other).name) && Objects.equal(this.type, ((GuiceModuleAccess.BindKey)other).type)); - } else { - _xifexpression = false; - } - return _xifexpression; - } - - @Override - public int hashCode() { - int h = 0; - if ((this.name != null)) { - int _h = h; - int _hashCode = this.name.hashCode(); - h = (_h + _hashCode); - } - if ((this.type != null)) { - int _h_1 = h; - int _hashCode_1 = this.type.hashCode(); - h = (_h_1 + _hashCode_1); - } - return h; - } - - public BindKey(final String name, final TypeReference type, final boolean singleton, final boolean eagerSingleton) { - super(); - this.name = name; - this.type = type; - this.singleton = singleton; - this.eagerSingleton = eagerSingleton; - } - - @Override - @Pure - public String toString() { - ToStringBuilder b = new ToStringBuilder(this); - b.add("name", this.name); - b.add("type", this.type); - b.add("singleton", this.singleton); - b.add("eagerSingleton", this.eagerSingleton); - return b.toString(); - } - - @Pure - public String getName() { - return this.name; - } - - @Pure - public TypeReference getType() { - return this.type; - } - - @Pure - public boolean isSingleton() { - return this.singleton; - } - - @Pure - public boolean isEagerSingleton() { - return this.eagerSingleton; - } - } - - @Data - public static class BindValue { - private final Object expression; - - private final TypeReference type; - - private final boolean provider; - - private final List statements; - - public BindValue(final Object expression, final TypeReference type, final boolean provider, final List statements) { - super(); - this.expression = expression; - this.type = type; - this.provider = provider; - this.statements = statements; - } - - @Override - @Pure - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((this.expression== null) ? 0 : this.expression.hashCode()); - result = prime * result + ((this.type== null) ? 0 : this.type.hashCode()); - result = prime * result + (this.provider ? 1231 : 1237); - return prime * result + ((this.statements== null) ? 0 : this.statements.hashCode()); - } - - @Override - @Pure - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - GuiceModuleAccess.BindValue other = (GuiceModuleAccess.BindValue) obj; - if (this.expression == null) { - if (other.expression != null) - return false; - } else if (!this.expression.equals(other.expression)) - return false; - if (this.type == null) { - if (other.type != null) - return false; - } else if (!this.type.equals(other.type)) - return false; - if (other.provider != this.provider) - return false; - if (this.statements == null) { - if (other.statements != null) - return false; - } else if (!this.statements.equals(other.statements)) - return false; - return true; - } - - @Override - @Pure - public String toString() { - ToStringBuilder b = new ToStringBuilder(this); - b.add("expression", this.expression); - b.add("type", this.type); - b.add("provider", this.provider); - b.add("statements", this.statements); - return b.toString(); - } - - @Pure - public Object getExpression() { - return this.expression; - } - - @Pure - public TypeReference getType() { - return this.type; - } - - @Pure - public boolean isProvider() { - return this.provider; - } - - @Pure - public List getStatements() { - return this.statements; - } - } - - @Data - public static class Binding { - private final GuiceModuleAccess.BindKey key; - - private final GuiceModuleAccess.BindValue value; - - private final boolean isFinal; - - private final String contributedBy; - - @Override - public boolean equals(final Object other) { - boolean _xifexpression = false; - if ((other instanceof GuiceModuleAccess.Binding)) { - _xifexpression = Objects.equal(this.key, ((GuiceModuleAccess.Binding)other).key); - } else { - _xifexpression = false; - } - return _xifexpression; - } - - @Override - public int hashCode() { - return this.key.hashCode(); - } - - public Binding(final GuiceModuleAccess.BindKey key, final GuiceModuleAccess.BindValue value, final boolean isFinal, final String contributedBy) { - super(); - this.key = key; - this.value = value; - this.isFinal = isFinal; - this.contributedBy = contributedBy; - } - - @Override - @Pure - public String toString() { - ToStringBuilder b = new ToStringBuilder(this); - b.add("key", this.key); - b.add("value", this.value); - b.add("isFinal", this.isFinal); - b.add("contributedBy", this.contributedBy); - return b.toString(); - } - - @Pure - public GuiceModuleAccess.BindKey getKey() { - return this.key; - } - - @Pure - public GuiceModuleAccess.BindValue getValue() { - return this.value; - } - - @Pure - public boolean isFinal() { - return this.isFinal; - } - - @Pure - public String getContributedBy() { - return this.contributedBy; - } - } - - public static class BindingFactory { - @Accessors - private final String contributedBy; - - private final Set bindings = CollectionLiterals.newLinkedHashSet(); - - public BindingFactory() { - this.contributedBy = (new Exception().getStackTrace()[1]).getClassName(); - } - - public BindingFactory(final String contributedBy) { - this.contributedBy = contributedBy; - } - - private void add(final GuiceModuleAccess.BindKey type, final GuiceModuleAccess.BindValue expr) { - this.add(type, expr, false); - } - - private void add(final GuiceModuleAccess.BindKey type, final GuiceModuleAccess.BindValue expr, final boolean isFinal) { - GuiceModuleAccess.Binding _binding = new GuiceModuleAccess.Binding(type, expr, isFinal, this.contributedBy); - this.add(_binding); - } - - private void add(final GuiceModuleAccess.Binding binding) { - boolean _add = this.bindings.add(binding); - boolean _not = (!_add); - if (_not) { - throw new IllegalArgumentException(((("Duplicate binding for " + binding.key) + " in ") + this.contributedBy)); - } - } - - private GuiceModuleAccess.BindKey key(final TypeReference type) { - return new GuiceModuleAccess.BindKey(null, type, false, false); - } - - private GuiceModuleAccess.BindKey key(final String name) { - return new GuiceModuleAccess.BindKey(name, null, false, false); - } - - private GuiceModuleAccess.BindKey eagerSingleton(final TypeReference type) { - return new GuiceModuleAccess.BindKey(null, type, true, true); - } - - private GuiceModuleAccess.BindKey singleton(final TypeReference type) { - return new GuiceModuleAccess.BindKey(null, type, true, false); - } - - private GuiceModuleAccess.BindValue value(final TypeReference type) { - List _emptyList = Collections.emptyList(); - return new GuiceModuleAccess.BindValue(null, type, false, _emptyList); - } - - private GuiceModuleAccess.BindValue expr(final Object expr) { - List _emptyList = Collections.emptyList(); - return new GuiceModuleAccess.BindValue(expr, null, false, _emptyList); - } - - private GuiceModuleAccess.BindValue provider(final TypeReference type) { - List _emptyList = Collections.emptyList(); - return new GuiceModuleAccess.BindValue(null, type, true, _emptyList); - } - - private GuiceModuleAccess.BindValue providerExpr(final Object expr) { - List _emptyList = Collections.emptyList(); - return new GuiceModuleAccess.BindValue(expr, null, true, _emptyList); - } - - private GuiceModuleAccess.BindValue statements(final Object[] statements) { - return new GuiceModuleAccess.BindValue(null, null, false, (List)Conversions.doWrapArray(statements)); - } - - public GuiceModuleAccess.BindingFactory addTypeToInstance(final TypeReference type, final StringConcatenationClient expression) { - this.add(this.key(type), this.expr(expression)); - return this; - } - - public GuiceModuleAccess.BindingFactory addTypeToProviderInstance(final TypeReference type, final StringConcatenationClient expression) { - this.add(this.key(type), this.providerExpr(expression)); - return this; - } - - public GuiceModuleAccess.BindingFactory addConfiguredBinding(final String name, final StringConcatenationClient statement) { - this.add(this.key(name), this.statements(new Object[] { statement })); - return this; - } - - public GuiceModuleAccess.BindingFactory addTypeToType(final TypeReference keyType, final TypeReference valueType) { - this.add(this.key(keyType), this.value(valueType)); - return this; - } - - public GuiceModuleAccess.BindingFactory addTypeToTypeSingleton(final TypeReference keyType, final TypeReference valueType) { - this.add(this.singleton(keyType), this.value(valueType)); - return this; - } - - public GuiceModuleAccess.BindingFactory addTypeToTypeEagerSingleton(final TypeReference keyType, final TypeReference valueType) { - this.add(this.eagerSingleton(keyType), this.value(valueType)); - return this; - } - - public GuiceModuleAccess.BindingFactory addTypeToProvider(final TypeReference keyType, final TypeReference valueType) { - this.add(this.key(keyType), this.provider(valueType)); - return this; - } - - public GuiceModuleAccess.BindingFactory addTypeToProviderSingleton(final TypeReference keyType, final TypeReference valueType) { - this.add(this.singleton(keyType), this.provider(valueType)); - return this; - } - - public GuiceModuleAccess.BindingFactory addTypeToProviderEagerSingleton(final TypeReference keyType, final TypeReference valueType) { - this.add(this.eagerSingleton(keyType), this.provider(valueType)); - return this; - } - - public GuiceModuleAccess.BindingFactory addfinalTypeToType(final TypeReference keyType, final TypeReference valueType) { - this.add(this.key(keyType), this.value(valueType), true); - return this; - } - - public GuiceModuleAccess.BindingFactory addfinalTypeToTypeSingleton(final TypeReference keyType, final TypeReference valueType) { - this.add(this.singleton(keyType), this.value(valueType), true); - return this; - } - - public GuiceModuleAccess.BindingFactory addfinalTypeToTypeEagerSingleton(final TypeReference keyType, final TypeReference valueType) { - this.add(this.eagerSingleton(keyType), this.value(valueType), true); - return this; - } - - public GuiceModuleAccess.BindingFactory addfinalTypeToProvider(final TypeReference keyType, final TypeReference valueType) { - this.add(this.key(keyType), this.provider(valueType), true); - return this; - } - - public GuiceModuleAccess.BindingFactory addfinalTypeToProviderSingleton(final TypeReference keyType, final TypeReference valueType) { - this.add(this.singleton(keyType), this.provider(valueType), true); - return this; - } - - public GuiceModuleAccess.BindingFactory addfinalTypeToProviderEagerSingleton(final TypeReference keyType, final TypeReference valueType) { - this.add(this.eagerSingleton(keyType), this.provider(valueType), true); - return this; - } - - public void contributeTo(final GuiceModuleAccess module) { - module.addAll(this.bindings); - } - - @Pure - public String getContributedBy() { - return this.contributedBy; - } - } - - private final Set bindings = CollectionLiterals.newLinkedHashSet(); - - @Accessors - private TypeReference superClass; - - public void add(final GuiceModuleAccess.Binding newBinding) { - boolean _contains = this.bindings.contains(newBinding); - if (_contains) { - final Iterator iterator = this.bindings.iterator(); - boolean found = false; - while ((iterator.hasNext() && (!found))) { - { - final GuiceModuleAccess.Binding oldBinding = iterator.next(); - boolean _equals = Objects.equal(oldBinding, newBinding); - if (_equals) { - if (oldBinding.isFinal) { - if (newBinding.isFinal) { - throw new IllegalStateException(((((("Conflicting final bindings for \'" + oldBinding.key.type) + "\' from fragments ") + oldBinding.contributedBy) + " and ") + newBinding.contributedBy)); - } else { - GuiceModuleAccess.LOG.warn(((((("Cannot override final binding \'" + oldBinding) + "\'. ") + "Ignoring binding from fragment \'") + newBinding.contributedBy) + "\'")); - } - } else { - GuiceModuleAccess.LOG.debug(("replacing binding : " + oldBinding)); - GuiceModuleAccess.LOG.debug((" with new binding : " + newBinding)); - iterator.remove(); - } - found = true; - } - } - } - } - this.bindings.add(newBinding); - } - - public void addAll(final Iterable bindings) { - for (final GuiceModuleAccess.Binding binding : bindings) { - this.add(binding); - } - } - - public Set getBindings() { - return Collections.unmodifiableSet(this.bindings); - } - - private static final Logger LOG = Logger.getLogger(GuiceModuleAccess.class); - - @Pure - public TypeReference getSuperClass() { - return this.superClass; - } - - public void setSuperClass(final TypeReference superClass) { - this.superClass = superClass; - } -} diff --git a/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/model/project/SubProjectConfig.java b/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/model/project/SubProjectConfig.java deleted file mode 100644 index b5d630c55..000000000 --- a/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/model/project/SubProjectConfig.java +++ /dev/null @@ -1,211 +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.xtext.generator.model.project; - -import com.google.inject.Inject; -import com.google.inject.Injector; -import org.eclipse.xtend.lib.annotations.AccessorType; -import org.eclipse.xtend.lib.annotations.Accessors; -import org.eclipse.xtext.xbase.lib.Pure; -import org.eclipse.xtext.xbase.lib.StringExtensions; -import org.eclipse.xtext.xtext.generator.Issues; -import org.eclipse.xtext.xtext.generator.model.IXtextGeneratorFileSystemAccess; -import org.eclipse.xtext.xtext.generator.model.project.ISubProjectConfig; -import org.eclipse.xtext.xtext.generator.model.project.XtextProjectConfig; - -/** - * Configuration of subprojects. - * - * @noextend This class should not be extended by clients. - */ -@SuppressWarnings("all") -public class SubProjectConfig implements ISubProjectConfig { - @Inject - @Accessors(AccessorType.PUBLIC_GETTER) - private XtextProjectConfig owner; - - @Accessors - private boolean enabled; - - @Accessors - private boolean overwriteSrc; - - @Accessors - private String name; - - @Accessors(AccessorType.PUBLIC_GETTER) - private String rootPath; - - @Accessors(AccessorType.PUBLIC_GETTER) - private IXtextGeneratorFileSystemAccess root; - - @Accessors(AccessorType.PUBLIC_GETTER) - private String metaInfPath; - - @Accessors(AccessorType.PUBLIC_GETTER) - private IXtextGeneratorFileSystemAccess metaInf; - - @Accessors(AccessorType.PUBLIC_GETTER) - private String srcPath; - - @Accessors(AccessorType.PUBLIC_GETTER) - private IXtextGeneratorFileSystemAccess src; - - @Accessors(AccessorType.PUBLIC_GETTER) - private String srcGenPath; - - @Accessors(AccessorType.PUBLIC_GETTER) - private IXtextGeneratorFileSystemAccess srcGen; - - @Accessors(AccessorType.PUBLIC_GETTER) - private String iconsPath; - - @Accessors(AccessorType.PUBLIC_GETTER) - private IXtextGeneratorFileSystemAccess icons; - - public void setRoot(final String path) { - this.rootPath = path; - } - - public void setMetaInf(final String path) { - this.metaInfPath = path; - } - - public void setSrc(final String path) { - this.srcPath = path; - } - - public void setSrcGen(final String path) { - this.srcGenPath = path; - } - - public void setIcons(final String path) { - this.iconsPath = path; - } - - public void checkConfiguration(final Issues issues) { - } - - @Override - public void initialize(final Injector injector) { - injector.injectMembers(this); - boolean _isNullOrEmpty = StringExtensions.isNullOrEmpty(this.rootPath); - boolean _not = (!_isNullOrEmpty); - if (_not) { - this.root = this.owner.newFileSystemAccess(this.rootPath, true); - this.root.initialize(injector); - } - boolean _isNullOrEmpty_1 = StringExtensions.isNullOrEmpty(this.metaInfPath); - boolean _not_1 = (!_isNullOrEmpty_1); - if (_not_1) { - this.metaInf = this.owner.newFileSystemAccess(this.metaInfPath, true); - this.metaInf.initialize(injector); - } - boolean _isNullOrEmpty_2 = StringExtensions.isNullOrEmpty(this.srcPath); - boolean _not_2 = (!_isNullOrEmpty_2); - if (_not_2) { - this.src = this.owner.newFileSystemAccess(this.srcPath, this.overwriteSrc); - this.src.initialize(injector); - } - boolean _isNullOrEmpty_3 = StringExtensions.isNullOrEmpty(this.srcGenPath); - boolean _not_3 = (!_isNullOrEmpty_3); - if (_not_3) { - this.srcGen = this.owner.newFileSystemAccess(this.srcGenPath, true); - this.srcGen.initialize(injector); - } - boolean _isNullOrEmpty_4 = StringExtensions.isNullOrEmpty(this.iconsPath); - boolean _not_4 = (!_isNullOrEmpty_4); - if (_not_4) { - this.icons = this.owner.newFileSystemAccess(this.iconsPath, true); - this.icons.initialize(injector); - } - } - - @Pure - public XtextProjectConfig getOwner() { - return this.owner; - } - - @Pure - public boolean isEnabled() { - return this.enabled; - } - - public void setEnabled(final boolean enabled) { - this.enabled = enabled; - } - - @Pure - public boolean isOverwriteSrc() { - return this.overwriteSrc; - } - - public void setOverwriteSrc(final boolean overwriteSrc) { - this.overwriteSrc = overwriteSrc; - } - - @Pure - public String getName() { - return this.name; - } - - public void setName(final String name) { - this.name = name; - } - - @Pure - public String getRootPath() { - return this.rootPath; - } - - @Pure - public IXtextGeneratorFileSystemAccess getRoot() { - return this.root; - } - - @Pure - public String getMetaInfPath() { - return this.metaInfPath; - } - - @Pure - public IXtextGeneratorFileSystemAccess getMetaInf() { - return this.metaInf; - } - - @Pure - public String getSrcPath() { - return this.srcPath; - } - - @Pure - public IXtextGeneratorFileSystemAccess getSrc() { - return this.src; - } - - @Pure - public String getSrcGenPath() { - return this.srcGenPath; - } - - @Pure - public IXtextGeneratorFileSystemAccess getSrcGen() { - return this.srcGen; - } - - @Pure - public String getIconsPath() { - return this.iconsPath; - } - - @Pure - public IXtextGeneratorFileSystemAccess getIcons() { - return this.icons; - } -} diff --git a/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/parser/antlr/CombinedGrammarMarker.java b/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/parser/antlr/CombinedGrammarMarker.java deleted file mode 100644 index 24c3d6037..000000000 --- a/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/parser/antlr/CombinedGrammarMarker.java +++ /dev/null @@ -1,110 +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.xtext.generator.parser.antlr; - -import java.util.List; -import org.eclipse.emf.common.notify.Adapter; -import org.eclipse.emf.common.notify.Notifier; -import org.eclipse.emf.common.notify.impl.AdapterImpl; -import org.eclipse.xtend.lib.annotations.Data; -import org.eclipse.xtext.util.internal.EmfAdaptable; -import org.eclipse.xtext.xbase.lib.Pure; -import org.eclipse.xtext.xbase.lib.util.ToStringBuilder; - -@EmfAdaptable -@Data -@SuppressWarnings("all") -public class CombinedGrammarMarker { - public static class CombinedGrammarMarkerAdapter extends AdapterImpl { - private CombinedGrammarMarker element; - - public CombinedGrammarMarkerAdapter(final CombinedGrammarMarker element) { - this.element = element; - } - - public CombinedGrammarMarker get() { - return this.element; - } - - @Override - public boolean isAdapterForType(final Object object) { - return object == CombinedGrammarMarker.class; - } - } - - private final boolean isCombinedGrammar; - - public static CombinedGrammarMarker findInEmfObject(final Notifier emfObject) { - for (Adapter adapter : emfObject.eAdapters()) { - if (adapter instanceof CombinedGrammarMarker.CombinedGrammarMarkerAdapter) { - return ((CombinedGrammarMarker.CombinedGrammarMarkerAdapter) adapter).get(); - } - } - return null; - } - - public static CombinedGrammarMarker removeFromEmfObject(final Notifier emfObject) { - List adapters = emfObject.eAdapters(); - for(int i = 0, max = adapters.size(); i < max; i++) { - Adapter adapter = adapters.get(i); - if (adapter instanceof CombinedGrammarMarker.CombinedGrammarMarkerAdapter) { - emfObject.eAdapters().remove(i); - return ((CombinedGrammarMarker.CombinedGrammarMarkerAdapter) adapter).get(); - } - } - return null; - } - - public void attachToEmfObject(final Notifier emfObject) { - CombinedGrammarMarker result = findInEmfObject(emfObject); - if (result != null) - throw new IllegalStateException("The given EMF object already contains an adapter for CombinedGrammarMarker"); - CombinedGrammarMarker.CombinedGrammarMarkerAdapter adapter = new CombinedGrammarMarker.CombinedGrammarMarkerAdapter(this); - emfObject.eAdapters().add(adapter); - } - - public CombinedGrammarMarker(final boolean isCombinedGrammar) { - super(); - this.isCombinedGrammar = isCombinedGrammar; - } - - @Override - @Pure - public int hashCode() { - return 31 * 1 + (this.isCombinedGrammar ? 1231 : 1237); - } - - @Override - @Pure - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - CombinedGrammarMarker other = (CombinedGrammarMarker) obj; - if (other.isCombinedGrammar != this.isCombinedGrammar) - return false; - return true; - } - - @Override - @Pure - public String toString() { - ToStringBuilder b = new ToStringBuilder(this); - b.add("isCombinedGrammar", this.isCombinedGrammar); - return b.toString(); - } - - @Pure - public boolean isCombinedGrammar() { - return this.isCombinedGrammar; - } -} diff --git a/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java b/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java index 77468cfa4..ca9d3d8e9 100644 --- a/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java +++ b/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContextProvider.java @@ -1,5 +1,5 @@ /** - * Copyright (c) 2016 itemis AG (http://www.itemis.eu) and others. + * Copyright (c) 2016, 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. diff --git a/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContexts.java b/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContexts.java deleted file mode 100644 index fa9a4aae0..000000000 --- a/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/NamedSerializationContexts.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright (c) 2016 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.xtext.generator.serializer; - -import java.util.List; -import org.eclipse.emf.ecore.EClass; -import org.eclipse.xtend.lib.annotations.Accessors; -import org.eclipse.xtext.serializer.ISerializationContext; -import org.eclipse.xtext.xbase.lib.Pure; - -@Accessors -@SuppressWarnings("all") -public class NamedSerializationContexts { - private final String name; - - private final EClass type; - - private final List contexts; - - private final T value; - - public NamedSerializationContexts(final String name, final EClass type, final List contexts, final T value) { - super(); - this.name = name; - this.type = type; - this.contexts = contexts; - this.value = value; - } - - @Pure - public String getName() { - return this.name; - } - - @Pure - public EClass getType() { - return this.type; - } - - @Pure - public List getContexts() { - return this.contexts; - } - - @Pure - public T getValue() { - return this.value; - } -} diff --git a/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/SyntacticSequencerPDA2ExtendedDot.java b/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/SyntacticSequencerPDA2ExtendedDot.java deleted file mode 100644 index 916345f37..000000000 --- a/org.eclipse.xtext.xtext.generator/xtend-gen/org/eclipse/xtext/xtext/generator/serializer/SyntacticSequencerPDA2ExtendedDot.java +++ /dev/null @@ -1,56 +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.xtext.generator.serializer; - -import java.util.List; -import java.util.Set; -import org.eclipse.xtext.serializer.analysis.ISyntacticSequencerPDAProvider; -import org.eclipse.xtext.util.GraphvizDotBuilder; -import org.eclipse.xtext.xbase.lib.CollectionLiterals; - -@SuppressWarnings("all") -public class SyntacticSequencerPDA2ExtendedDot extends GraphvizDotBuilder { - @Override - protected GraphvizDotBuilder.Props drawObject(final Object obj) { - GraphvizDotBuilder.Digraph _xifexpression = null; - if ((obj instanceof ISyntacticSequencerPDAProvider.ISynState)) { - _xifexpression = this.drawGrammar(((ISyntacticSequencerPDAProvider.ISynState)obj)); - } - return _xifexpression; - } - - protected GraphvizDotBuilder.Digraph drawGrammar(final ISyntacticSequencerPDAProvider.ISynState pr) { - final GraphvizDotBuilder.Digraph d = new GraphvizDotBuilder.Digraph(); - final Set visited = CollectionLiterals.newHashSet(); - this.drawState(d, pr, visited); - return d; - } - - protected void drawState(final GraphvizDotBuilder.Digraph d, final ISyntacticSequencerPDAProvider.ISynState state, final Set visited) { - boolean _add = visited.add(state); - boolean _not = (!_add); - if (_not) { - return; - } - String _string = state.toString(); - final GraphvizDotBuilder.Node n = new GraphvizDotBuilder.Node(state, _string); - if ((!(state instanceof ISyntacticSequencerPDAProvider.ISynAbsorberState))) { - n.setStyle("dotted"); - } - d.add(n); - List _followers = state.getFollowers(); - for (final ISyntacticSequencerPDAProvider.ISynState trans : _followers) { - { - final GraphvizDotBuilder.Edge edge = new GraphvizDotBuilder.Edge(state, trans); - d.add(edge); - this.drawState(d, trans, visited); - } - } - } -} diff --git a/org.eclipse.xtext.xtext.wizard/src/org/eclipse/xtext/xtext/wizard/ExternalDependency.java b/org.eclipse.xtext.xtext.wizard/src/org/eclipse/xtext/xtext/wizard/ExternalDependency.java index e2df2ec47..05a8a1831 100644 --- a/org.eclipse.xtext.xtext.wizard/src/org/eclipse/xtext/xtext/wizard/ExternalDependency.java +++ b/org.eclipse.xtext.xtext.wizard/src/org/eclipse/xtext/xtext/wizard/ExternalDependency.java @@ -8,8 +8,9 @@ */ package org.eclipse.xtext.xtext.wizard; +import java.util.HashSet; import java.util.Set; -import org.eclipse.xtext.xbase.lib.CollectionLiterals; + import org.eclipse.xtext.xbase.lib.Procedures.Procedure1; import org.eclipse.xtext.xbase.lib.Pure; @@ -83,7 +84,7 @@ public class ExternalDependency { private String version; - private Set packages = CollectionLiterals.newHashSet(); + private Set packages = new HashSet<>(); @Pure public String getBundleId() { diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/CompositeGeneratorNode.java b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/CompositeGeneratorNode.java new file mode 100644 index 000000000..ceed153e4 --- /dev/null +++ b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/CompositeGeneratorNode.java @@ -0,0 +1,44 @@ +/** + * 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.generator.trace.node; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.xtend2.lib.StringConcatenation; + +/** + * A composite node does not contribute any output directly, but only through its children. Thus it is an inner + * node of the code generator tree. + * + * @author Sven Efftinge - Initial contribution and API + */ +public class CompositeGeneratorNode implements IGeneratorNode { + private final List children = new ArrayList<>(); + + @Override + public String toString() { + StringConcatenation builder = new StringConcatenation(); + builder.append(getClass().getSimpleName()); + builder.append(" {"); + builder.newLineIfNotEmpty(); + for (IGeneratorNode c : children) { + builder.append("\t"); + builder.append(c.toString(), "\t"); + builder.newLineIfNotEmpty(); + } + builder.append("}"); + builder.newLine(); + return builder.toString(); + } + + public List getChildren() { + return children; + } +} diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/CompositeGeneratorNode.xtend b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/CompositeGeneratorNode.xtend deleted file mode 100644 index 01cf2c9d3..000000000 --- a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/CompositeGeneratorNode.xtend +++ /dev/null @@ -1,33 +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.generator.trace.node - -import java.util.List -import org.eclipse.xtend.lib.annotations.Accessors - -/** - * A composite node does not contribute any output directly, but only through its children. - * Thus it is an inner node of the code generator tree. - * - * @author Sven Efftinge - Initial contribution and API - */ -@Accessors -class CompositeGeneratorNode implements IGeneratorNode { - - val List children = newArrayList - - override toString() ''' - «class.simpleName» { - «FOR c: children» - «c.toString» - «ENDFOR» - } - ''' - -} \ No newline at end of file diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/GeneratorNodeExtensions.java b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/GeneratorNodeExtensions.java new file mode 100644 index 000000000..0ab9d097b --- /dev/null +++ b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/GeneratorNodeExtensions.java @@ -0,0 +1,143 @@ +/** + * 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.generator.trace.node; + +import org.eclipse.xtend2.lib.StringConcatenationClient; +import org.eclipse.xtext.generator.trace.ILocationData; + +import com.google.inject.Inject; + +/** + * A builder API to create generator node trees + * + * @author Sven Efftinge - Initial contribution and API + */ +public class GeneratorNodeExtensions { + @Inject + private GeneratorWhiteSpaceConfig wsConfig = new GeneratorWhiteSpaceConfig(); + + /** + * @return a root trace node for the given location + */ + public CompositeGeneratorNode trace(ILocationData data) { + return new TraceNode(data); + } + + /** + * @return a root trace node for the given location + */ + public CompositeGeneratorNode trace(ILocationData data, boolean useForDebugging) { + TraceNode result = new TraceNode(data); + result.setUseForDebugging(useForDebugging); + return result; + } + + /** + * @return a trace node for the given location, appended as a child on the given parent + */ + public CompositeGeneratorNode trace(CompositeGeneratorNode parent, ILocationData data) { + TraceNode result = new TraceNode(data); + parent.getChildren().add(result); + return result; + } + + /** + * @return a trace node for the given location, appended as a child on the given parent + */ + public CompositeGeneratorNode trace(CompositeGeneratorNode parent, ILocationData data, boolean useForDebugging) { + TraceNode result = new TraceNode(data); + result.setUseForDebugging(useForDebugging); + parent.getChildren().add(result); + return result; + } + + /** + * @return an indentation node, using the default indentation string, appended as a child on the given parent + */ + public CompositeGeneratorNode indent(CompositeGeneratorNode parent) { + return indent(parent, wsConfig.getIndentationString()); + } + + /** + * Appends the indentation string at the current position of the parent and adds a new composite node, indicating + * the same indentation for subsequent lines. + * + * @return an indentation node, using the given indentString, appended as a child on the given parent + */ + public CompositeGeneratorNode indent(CompositeGeneratorNode parent, String indentString) { + IndentNode indent = new IndentNode(indentString); + parent.getChildren().add(indent); + return indent; + } + + /** + * Appends a line separator node to the given parent. + * + * @return the given parent node + */ + public CompositeGeneratorNode appendNewLine(CompositeGeneratorNode parent) { + parent.getChildren().add(new NewLineNode(wsConfig.getLineDelimiter(), false)); + return parent; + } + + /** + * Appends a line separator node to the given parent. + * + * @return the given parent node + */ + public CompositeGeneratorNode appendNewLine(CompositeGeneratorNode parent, String lineSeparator) { + parent.getChildren().add(new NewLineNode(lineSeparator, false)); + return parent; + } + + /** + * Appends a line separator node that will only be effective if the current line contains non-whitespace text. + * + * @return the given parent node + */ + public CompositeGeneratorNode appendNewLineIfNotEmpty(CompositeGeneratorNode parent) { + parent.getChildren().add(new NewLineNode(wsConfig.getLineDelimiter(), true)); + return parent; + } + + /** + * Creates a text node containing the toString() representation of the given object and appends it to the given + * parent node. + * + * @return the given parent node + */ + public CompositeGeneratorNode append(CompositeGeneratorNode parent, Object object) { + if (object instanceof StringConcatenationClient) { + appendTemplate(parent, (StringConcatenationClient) object); + } else { + if (object instanceof IGeneratorNode) { + parent.getChildren().add((IGeneratorNode) object); + } else { + if (object != null) { + parent.getChildren().add(new TextNode(object.toString())); + } + } + } + return parent; + } + + /** + * Creates a template node for the given templateString and appends it to the given parent node. + * + * Templates are translated to generator node trees and expressions in templates can be of type IGeneratorNode. + * + * @return the given parent node + */ + public CompositeGeneratorNode appendTemplate(CompositeGeneratorNode parent, + StringConcatenationClient templateString) { + TemplateNode proc = new TemplateNode(templateString, this); + parent.getChildren().add(proc); + return parent; + } +} diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/GeneratorNodeExtensions.xtend b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/GeneratorNodeExtensions.xtend deleted file mode 100644 index bec03d66a..000000000 --- a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/GeneratorNodeExtensions.xtend +++ /dev/null @@ -1,139 +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.generator.trace.node - -import com.google.inject.Inject -import org.eclipse.xtend2.lib.StringConcatenationClient -import org.eclipse.xtext.generator.trace.ILocationData - -/** - * A builder API to create generator node trees - * - * @author Sven Efftinge - Initial contribution and API - */ -class GeneratorNodeExtensions { - - @Inject GeneratorWhiteSpaceConfig wsConfig = new GeneratorWhiteSpaceConfig - - /** - * @return a root trace node for the given location - */ - def CompositeGeneratorNode trace(ILocationData data) { - val result = new TraceNode(data) - return result - } - - /** - * @return a root trace node for the given location - */ - def CompositeGeneratorNode trace(ILocationData data, boolean useForDebugging) { - val result = new TraceNode(data) - result.useForDebugging = useForDebugging - return result - } - - /** - * @return a trace node for the given location, appended as a child on the given parent - */ - def CompositeGeneratorNode trace(CompositeGeneratorNode parent, ILocationData data) { - val result = new TraceNode(data) - parent.children += result - return result - } - - /** - * @return a trace node for the given location, appended as a child on the given parent - */ - def CompositeGeneratorNode trace(CompositeGeneratorNode parent, ILocationData data, boolean useForDebugging) { - val result = new TraceNode(data) - result.useForDebugging = useForDebugging - parent.children += result - return result - } - - /** - * @return an indentation node, using the default indentation string, appended as a child on the given parent - */ - def CompositeGeneratorNode indent(CompositeGeneratorNode parent) { - return indent(parent, wsConfig.indentationString) - } - - /** - * Appends the indentation string at the current position of the parent and adds a new composite node, indicating the same indentation for - * subsequent lines. - * - * @return an indentation node, using the given indentString, appended as a child on the given parent - */ - def CompositeGeneratorNode indent(CompositeGeneratorNode parent, String indentString) { - val indent = new IndentNode(indentString) - parent.children += indent - return indent - } - - /** - * Appends a line separator node to the given parent. - * - * @return the given parent node - */ - def CompositeGeneratorNode appendNewLine(CompositeGeneratorNode parent) { - parent.children += new NewLineNode(wsConfig.lineDelimiter, false) - return parent - } - - /** - * Appends a line separator node to the given parent. - * - * @return the given parent node - */ - def CompositeGeneratorNode appendNewLine(CompositeGeneratorNode parent, String lineSeparator) { - parent.children += new NewLineNode(lineSeparator, false) - return parent - } - - /** - * Appends a line separator node that will only be effective if the current line contains non-whitespace text. - * - * @return the given parent node - */ - def CompositeGeneratorNode appendNewLineIfNotEmpty(CompositeGeneratorNode parent) { - parent.children += new NewLineNode(wsConfig.lineDelimiter, true) - return parent - } - /** - * Creates a text node containing the toString() representation of the given object and - * appends it to the given parent node. - * - * @return the given parent node - */ - def CompositeGeneratorNode append(CompositeGeneratorNode parent, Object object) { - if (object instanceof StringConcatenationClient) { - appendTemplate(parent, object) - } else if (object instanceof IGeneratorNode) { - parent.children += object - } else if (object !== null) { - parent.children += new TextNode(object.toString) - } - return parent - } - - /** - * Creates a template node for the given templateString and appends it to the given parent node. - * - * Templates are translated to generator node trees and expressions in templates can be of type IGeneratorNode. - * - * @return the given parent node - */ - def CompositeGeneratorNode appendTemplate(CompositeGeneratorNode parent, StringConcatenationClient templateString) { - val proc = new TemplateNode(templateString, this) - parent.children += proc - return parent - } - - -} \ No newline at end of file diff --git a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/GeneratorWhiteSpaceConfig.java b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/GeneratorWhiteSpaceConfig.java similarity index 63% rename from org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/GeneratorWhiteSpaceConfig.java rename to org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/GeneratorWhiteSpaceConfig.java index b2743f87a..5403eedfe 100644 --- a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/GeneratorWhiteSpaceConfig.java +++ b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/GeneratorWhiteSpaceConfig.java @@ -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,13 +11,12 @@ package org.eclipse.xtext.generator.trace.node; /** * @author Sven Efftinge - Initial contribution and API */ -@SuppressWarnings("all") public class GeneratorWhiteSpaceConfig { - public String getIndentationString() { - return " "; - } - - public String getLineDelimiter() { - return "\n"; - } + public String getIndentationString() { + return " "; + } + + public String getLineDelimiter() { + return "\n"; + } } diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/GeneratorWhiteSpaceConfig.xtend b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/GeneratorWhiteSpaceConfig.xtend deleted file mode 100644 index 35d7d4d4e..000000000 --- a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/GeneratorWhiteSpaceConfig.xtend +++ /dev/null @@ -1,23 +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.generator.trace.node - -/** - * @author Sven Efftinge - Initial contribution and API - */ -class GeneratorWhiteSpaceConfig { - - def String getIndentationString() { - ' ' - } - - def String getLineDelimiter() { - '\n' - } -} \ No newline at end of file diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/IGeneratorNode.xtend b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/IGeneratorNode.java similarity index 75% rename from org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/IGeneratorNode.xtend rename to org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/IGeneratorNode.java index fa9cd7b06..b15bb8b71 100644 --- a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/IGeneratorNode.xtend +++ b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/IGeneratorNode.java @@ -1,12 +1,12 @@ /******************************************************************************* - * 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. * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ -package org.eclipse.xtext.generator.trace.node +package org.eclipse.xtext.generator.trace.node; /** * @@ -14,6 +14,6 @@ package org.eclipse.xtext.generator.trace.node * * @author Sven Efftinge - Initial contribution and API */ -interface IGeneratorNode { +public interface IGeneratorNode { } \ No newline at end of file diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/IndentNode.java b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/IndentNode.java new file mode 100644 index 000000000..0f194071b --- /dev/null +++ b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/IndentNode.java @@ -0,0 +1,66 @@ +/** + * 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.generator.trace.node; + +/** + * An indent node prepends the indentation string to each line that is generated through its children. + * + * @author Sven Efftinge - Initial contribution and API + */ +public class IndentNode extends CompositeGeneratorNode { + private String indentationString; + + /** + * When this is set to {@code true}, the indentation is always inserted in the first line, otherwise it is inserted + * only if the first line has no text preceding this node. + */ + private boolean indentImmediately; + + /** + * When this is set to {@code true}, all lines are indented, otherwise only lines with text content are indented. + */ + private boolean indentEmptyLines; + + public IndentNode(String indentationString) { + this(indentationString, true, false); + } + + public IndentNode(String indentationString, boolean indentImmediately, boolean indentEmptyLines) { + if (indentationString == null) { + throw new NullPointerException(); + } + this.indentationString = indentationString; + this.indentImmediately = indentImmediately; + this.indentEmptyLines = indentEmptyLines; + } + + public String getIndentationString() { + return indentationString; + } + + public void setIndentationString(String indentationString) { + this.indentationString = indentationString; + } + + public boolean isIndentImmediately() { + return indentImmediately; + } + + public void setIndentImmediately(boolean indentImmediately) { + this.indentImmediately = indentImmediately; + } + + public boolean isIndentEmptyLines() { + return indentEmptyLines; + } + + public void setIndentEmptyLines(boolean indentEmptyLines) { + this.indentEmptyLines = indentEmptyLines; + } +} diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/IndentNode.xtend b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/IndentNode.xtend deleted file mode 100644 index 7ae458879..000000000 --- a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/IndentNode.xtend +++ /dev/null @@ -1,46 +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.generator.trace.node - -import org.eclipse.xtend.lib.annotations.Accessors - -/** - * An indent node prepends the indentation string to each line that is generated through its children. - * - * @author Sven Efftinge - Initial contribution and API - */ -@Accessors -class IndentNode extends CompositeGeneratorNode { - - String indentationString - - /** - * When this is set to {@code true}, the indentation is always inserted in the first line, otherwise it is - * inserted only if the first line has no text preceding this node. - */ - boolean indentImmediately - - /** - * When this is set to {@code true}, all lines are indented, otherwise only lines with text content are indented. - */ - boolean indentEmptyLines - - new(String indentationString) { - this(indentationString, true, false) - } - - new(String indentationString, boolean indentImmediately, boolean indentEmptyLines) { - if (indentationString === null) - throw new NullPointerException - this.indentationString = indentationString - this.indentImmediately = indentImmediately - this.indentEmptyLines = indentEmptyLines - } - -} \ No newline at end of file diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/NewLineNode.java b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/NewLineNode.java new file mode 100644 index 000000000..565bed29c --- /dev/null +++ b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/NewLineNode.java @@ -0,0 +1,62 @@ +/** + * 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.generator.trace.node; + +import org.eclipse.xtext.util.Strings; + +/** + * A new line node is a leaf in the code generator tree and produces line breaks. + * + * @author Sven Efftinge - Initial contribution and API + */ +public class NewLineNode implements IGeneratorNode { + private String lineDelimiter; + + /** + * When this is set to {@code true}, the preceding line is removed if it contains only whitespace. + */ + private boolean ifNotEmpty; + + public NewLineNode(String lineDelimiter) { + this(lineDelimiter, false); + } + + public NewLineNode(String lineDelimiter, boolean ifNotEmpty) { + if (lineDelimiter == null) { + throw new NullPointerException(); + } + this.lineDelimiter = lineDelimiter; + this.ifNotEmpty = ifNotEmpty; + } + + @Override + public String toString() { + String result = getClass().getSimpleName() + " \"" + Strings.convertToJavaString(lineDelimiter) + "\""; + if (ifNotEmpty) { + result = result + " if not empty"; + } + return result; + } + + public String getLineDelimiter() { + return lineDelimiter; + } + + public void setLineDelimiter(String lineDelimiter) { + this.lineDelimiter = lineDelimiter; + } + + public boolean isIfNotEmpty() { + return ifNotEmpty; + } + + public void setIfNotEmpty(boolean ifNotEmpty) { + this.ifNotEmpty = ifNotEmpty; + } +} diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/NewLineNode.xtend b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/NewLineNode.xtend deleted file mode 100644 index 77f2ce51f..000000000 --- a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/NewLineNode.xtend +++ /dev/null @@ -1,44 +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.generator.trace.node - -import org.eclipse.xtend.lib.annotations.Accessors -import org.eclipse.xtext.util.Strings - -/** - * A new line node is a leaf in the code generator tree and produces line breaks. - * - * @author Sven Efftinge - Initial contribution and API - */ -@Accessors -class NewLineNode implements IGeneratorNode { - - String lineDelimiter - - /** - * When this is set to {@code true}, the preceding line is removed if it contains only whitespace. - */ - boolean ifNotEmpty - - new(String lineDelimiter) { - this(lineDelimiter, false) - } - - new(String lineDelimiter, boolean ifNotEmpty) { - if (lineDelimiter === null) - throw new NullPointerException - this.lineDelimiter = lineDelimiter - this.ifNotEmpty = ifNotEmpty - } - - override toString() { - '''«class.simpleName» "«Strings.convertToJavaString(lineDelimiter)»"«IF ifNotEmpty» if not empty«ENDIF»''' - } - -} \ No newline at end of file diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TextNode.java b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TextNode.java new file mode 100644 index 000000000..be4d401a3 --- /dev/null +++ b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TextNode.java @@ -0,0 +1,38 @@ +/** + * 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.generator.trace.node; + +import org.eclipse.xtext.generator.trace.node.IGeneratorNode; +import org.eclipse.xtext.util.Strings; + +/** + * A text node is a leaf in the code generator tree and produces arbitrary text. + * + * @author Sven Efftinge - Initial contribution and API + */ +public class TextNode implements IGeneratorNode { + private CharSequence text; + + public TextNode(CharSequence text) { + this.text = text; + } + + @Override + public String toString() { + return getClass().getSimpleName() + " \"" + Strings.convertToJavaString(text.toString()) + "\""; + } + + public CharSequence getText() { + return text; + } + + public void setText(CharSequence text) { + this.text = text; + } +} diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TextNode.xtend b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TextNode.xtend deleted file mode 100644 index c53b3e3b3..000000000 --- a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TextNode.xtend +++ /dev/null @@ -1,32 +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.generator.trace.node - -import org.eclipse.xtend.lib.annotations.Accessors -import org.eclipse.xtext.util.Strings - -/** - * A text node is a leaf in the code generator tree and produces arbitrary text. - * - * @author Sven Efftinge - Initial contribution and API - */ -@Accessors -class TextNode implements IGeneratorNode { - - CharSequence text - - new(CharSequence text) { - this.text = text - } - - override toString() { - '''«class.simpleName» "«Strings.convertToJavaString(text.toString)»"''' - } - -} \ No newline at end of file diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TraceNode.java b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TraceNode.java new file mode 100644 index 000000000..e87e3c2e8 --- /dev/null +++ b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TraceNode.java @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2017, 2020 TypeFox (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.generator.trace.node; + +import org.eclipse.xtext.generator.trace.ILocationData; + +/** + * A trace node maps the text generated through its children to a source location. + * + * @author Sven Efftinge - initial contribution and API + */ +public class TraceNode extends CompositeGeneratorNode { + private ILocationData sourceLocation; + + public TraceNode(ILocationData sourceLocation) { + this.sourceLocation = sourceLocation; + } + + private boolean useForDebugging; + + public ILocationData getSourceLocation() { + return sourceLocation; + } + + public void setSourceLocation(ILocationData sourceLocation) { + this.sourceLocation = sourceLocation; + } + + public boolean isUseForDebugging() { + return useForDebugging; + } + + public void setUseForDebugging(boolean useForDebugging) { + this.useForDebugging = useForDebugging; + } +} diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TraceNode.xtend b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TraceNode.xtend deleted file mode 100644 index 94b6992af..000000000 --- a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TraceNode.xtend +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017 TypeFox (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.generator.trace.node - -import org.eclipse.xtend.lib.annotations.Accessors -import org.eclipse.xtext.generator.trace.ILocationData - -/** - * A trace node maps the text generated through its children to a source location. - * - * @author Sven Efftinge - initial contribution and API - */ -@Accessors -class TraceNode extends CompositeGeneratorNode { - - ILocationData sourceLocation - - new(ILocationData sourceLocation) { - this.sourceLocation = sourceLocation - } - - boolean useForDebugging - -} \ No newline at end of file diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TracingSugar.java b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TracingSugar.java new file mode 100644 index 000000000..841de3ac9 --- /dev/null +++ b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TracingSugar.java @@ -0,0 +1,98 @@ +/** + * Copyright (c) 2017, 2020 TypeFox (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.generator.trace.node; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.xtend2.lib.StringConcatenationClient; +import org.eclipse.xtext.generator.IFileSystemAccess2; +import org.eclipse.xtext.generator.trace.ILocationData; +import org.eclipse.xtext.generator.trace.ITraceURIConverter; +import org.eclipse.xtext.generator.trace.LocationData; +import org.eclipse.xtext.generator.trace.SourceRelativeURI; +import org.eclipse.xtext.resource.ILocationInFileProvider; +import org.eclipse.xtext.util.ITextRegion; +import org.eclipse.xtext.util.ITextRegionWithLineInformation; + +import com.google.inject.Inject; + +/** + * Some additional sugar extension to - create generator nodes for EObjects - create ILocationData for EObjects. - + * enhance FileSystemAccess for tracing + */ +public class TracingSugar extends GeneratorNodeExtensions { + @Inject + protected ILocationInFileProvider locationProvider; + + @Inject + protected ITraceURIConverter traceURIConverter; + + @Inject + protected GeneratorWhiteSpaceConfig whiteSpaceConfig; + + @Inject + protected GeneratorNodeProcessor processor; + + /** + * Convenience extension, to generate traced code. + */ + public void generateTracedFile(IFileSystemAccess2 fsa, String path, EObject rootTrace, + StringConcatenationClient code) { + CompositeGeneratorNode node = trace(rootTrace, code); + generateTracedFile(fsa, path, node); + } + + /** + * Use to generate a file based on generator node. + */ + public void generateTracedFile(IFileSystemAccess2 fsa, String path, CompositeGeneratorNode rootNode) { + GeneratorNodeProcessor.Result result = processor.process(rootNode); + fsa.generateFile(path, result); + } + + /** + * Convenience shorthand for obj.location.trace + */ + public CompositeGeneratorNode trace(EObject obj) { + return trace(location(obj)); + } + + /** + * Convenience shorthand for obj.trace.appendTemplate('''some template''') + */ + public CompositeGeneratorNode trace(EObject obj, StringConcatenationClient code) { + return appendTemplate(trace(obj), code); + } + + /** + * @return ILocationData covering the fullTextRegion of the given EObject. + */ + public ILocationData location(EObject obj) { + ITextRegion region = locationProvider.getFullTextRegion(obj); + SourceRelativeURI uri = traceURIConverter.getURIForTrace(obj.eResource()); + return new LocationData((ITextRegionWithLineInformation) region, uri); + } + + /** + * @param obj + * the EObject containing the feature + * @param feature + * the EStructuralFeature to trace + * @param idx + * the index of the value to trace, in case the feature contains a list, should be -1 + * otherwise. + * + * @return ILocationData covering the fullTextRegion of the given feature in the given EObject. + */ + public ILocationData location(EObject obj, EStructuralFeature feature, int idx) { + ITextRegion region = locationProvider.getFullTextRegion(obj, feature, idx); + SourceRelativeURI uri = traceURIConverter.getURIForTrace(obj.eResource()); + return new LocationData((ITextRegionWithLineInformation) region, uri); + } +} diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TracingSugar.xtend b/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TracingSugar.xtend deleted file mode 100644 index 73911f715..000000000 --- a/org.eclipse.xtext/src/org/eclipse/xtext/generator/trace/node/TracingSugar.xtend +++ /dev/null @@ -1,79 +0,0 @@ -package org.eclipse.xtext.generator.trace.node - -import com.google.inject.Inject -import org.eclipse.emf.ecore.EObject -import org.eclipse.emf.ecore.EStructuralFeature -import org.eclipse.xtend2.lib.StringConcatenationClient -import org.eclipse.xtext.generator.IFileSystemAccess2 -import org.eclipse.xtext.generator.trace.ILocationData -import org.eclipse.xtext.generator.trace.ITraceURIConverter -import org.eclipse.xtext.generator.trace.LocationData -import org.eclipse.xtext.resource.ILocationInFileProvider -import org.eclipse.xtext.util.ITextRegionWithLineInformation - -/** - * Some additional sugar extension to - * - create generator nodes for EObjects - * - create ILocationData for EObjects. - * - enhance FileSystemAccess for tracing - */ -class TracingSugar extends GeneratorNodeExtensions { - - @Inject protected ILocationInFileProvider locationProvider - @Inject protected ITraceURIConverter traceURIConverter - @Inject protected GeneratorWhiteSpaceConfig whiteSpaceConfig - @Inject protected GeneratorNodeProcessor processor - - /** - * Convenience extension, to generate traced code. - */ - def void generateTracedFile(IFileSystemAccess2 fsa, String path, EObject rootTrace, StringConcatenationClient code) { - val node = trace(rootTrace, code) - generateTracedFile(fsa, path, node) - } - - /** - * Use to generate a file based on generator node. - */ - def void generateTracedFile(IFileSystemAccess2 fsa, String path, CompositeGeneratorNode rootNode) { - val result = processor.process(rootNode) - fsa.generateFile(path, result) - } - - /** - * Convenience shorthand for obj.location.trace - */ - def CompositeGeneratorNode trace(EObject obj) { - return obj.location.trace - } - - /** - * Convenience shorthand for obj.trace.appendTemplate('''some template''') - */ - def CompositeGeneratorNode trace(EObject obj, StringConcatenationClient code) { - return obj.trace.appendTemplate(code) - } - - /** - * @return ILocationData covering the fullTextRegion of the given EObject. - */ - def ILocationData location(EObject obj) { - val region = locationProvider.getFullTextRegion(obj) - val uri = traceURIConverter.getURIForTrace(obj.eResource) - return new LocationData(region as ITextRegionWithLineInformation, uri) - } - - /** - * @param obj the EObject containing the feature - * @param feature the EStructuralFeature to trace - * @param idx the index of the value to trace, in case the feature contains a list, should be -1 otherwise. - * - * @return ILocationData covering the fullTextRegion of the given feature in the given EObject. - */ - def ILocationData location(EObject obj, EStructuralFeature feature, int idx) { - val region = locationProvider.getFullTextRegion(obj, feature, idx) - val uri = traceURIConverter.getURIForTrace(obj.eResource) - return new LocationData(region as ITextRegionWithLineInformation, uri) - } - -} diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/xtext/OriginalElement.java b/org.eclipse.xtext/src/org/eclipse/xtext/xtext/OriginalElement.java new file mode 100644 index 000000000..fbab68d26 --- /dev/null +++ b/org.eclipse.xtext/src/org/eclipse/xtext/xtext/OriginalElement.java @@ -0,0 +1,109 @@ +/** + * 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.xtext; + +import java.util.List; +import org.eclipse.emf.common.notify.Adapter; +import org.eclipse.emf.common.notify.Notifier; +import org.eclipse.emf.common.notify.impl.AdapterImpl; +import org.eclipse.xtext.AbstractElement; +import org.eclipse.xtext.xbase.lib.util.ToStringBuilder; + +/** + * @author Sebastian Zarnekow - Initial contribution and API + */ +public class OriginalElement { + public static class OriginalElementAdapter extends AdapterImpl { + private OriginalElement element; + + public OriginalElementAdapter(OriginalElement element) { + this.element = element; + } + + public OriginalElement get() { + return element; + } + + @Override + public boolean isAdapterForType(Object object) { + return object == OriginalElement.class; + } + } + + private final AbstractElement original; + + public static OriginalElement findInEmfObject(Notifier emfObject) { + for (Adapter adapter : emfObject.eAdapters()) { + if (adapter instanceof OriginalElement.OriginalElementAdapter) { + return ((OriginalElement.OriginalElementAdapter) adapter).get(); + } + } + return null; + } + + public static OriginalElement removeFromEmfObject(Notifier emfObject) { + List adapters = emfObject.eAdapters(); + for (int i = 0, max = adapters.size(); i < max; i++) { + Adapter adapter = adapters.get(i); + if (adapter instanceof OriginalElement.OriginalElementAdapter) { + emfObject.eAdapters().remove(i); + return ((OriginalElement.OriginalElementAdapter) adapter).get(); + } + } + return null; + } + + public void attachToEmfObject(Notifier emfObject) { + OriginalElement result = findInEmfObject(emfObject); + if (result != null) + throw new IllegalStateException("The given EMF object already contains an adapter for OriginalElement"); + OriginalElement.OriginalElementAdapter adapter = new OriginalElement.OriginalElementAdapter(this); + emfObject.eAdapters().add(adapter); + } + + public OriginalElement(AbstractElement original) { + this.original = original; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((original == null) ? 0 : original.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + OriginalElement other = (OriginalElement) obj; + if (original == null) { + if (other.original != null) + return false; + } else if (!original.equals(other.original)) + return false; + return true; + } + + @Override + public String toString() { + ToStringBuilder b = new ToStringBuilder(this); + b.add("original", original); + return b.toString(); + } + + public AbstractElement getOriginal() { + return original; + } +} diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/xtext/OriginalElement.xtend b/org.eclipse.xtext/src/org/eclipse/xtext/xtext/OriginalElement.xtend deleted file mode 100644 index 3163a32ba..000000000 --- a/org.eclipse.xtext/src/org/eclipse/xtext/xtext/OriginalElement.xtend +++ /dev/null @@ -1,32 +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.xtext - -import org.eclipse.xtend.lib.annotations.Data -import org.eclipse.xtext.AbstractElement -import org.eclipse.xtext.Grammar -import org.eclipse.xtext.util.internal.EmfAdaptable - -/** - * @author Sebastian Zarnekow - Initial contribution and API - */ -@EmfAdaptable -@Data -class OriginalElement { - val AbstractElement original -} - -/** - * @author Sebastian Zarnekow - Initial contribution and API - */ -@EmfAdaptable -@Data -class OriginalGrammar { - val Grammar original -} \ No newline at end of file diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/xtext/OriginalGrammar.java b/org.eclipse.xtext/src/org/eclipse/xtext/xtext/OriginalGrammar.java new file mode 100644 index 000000000..60ced899d --- /dev/null +++ b/org.eclipse.xtext/src/org/eclipse/xtext/xtext/OriginalGrammar.java @@ -0,0 +1,110 @@ +/** + * 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.xtext; + +import java.util.List; + +import org.eclipse.emf.common.notify.Adapter; +import org.eclipse.emf.common.notify.Notifier; +import org.eclipse.emf.common.notify.impl.AdapterImpl; +import org.eclipse.xtext.Grammar; +import org.eclipse.xtext.xbase.lib.util.ToStringBuilder; + +/** + * @author Sebastian Zarnekow - Initial contribution and API + */ +public class OriginalGrammar { + public static class OriginalGrammarAdapter extends AdapterImpl { + private OriginalGrammar element; + + public OriginalGrammarAdapter(OriginalGrammar element) { + this.element = element; + } + + public OriginalGrammar get() { + return element; + } + + @Override + public boolean isAdapterForType(Object object) { + return object == OriginalGrammar.class; + } + } + + private final Grammar original; + + public static OriginalGrammar findInEmfObject(Notifier emfObject) { + for (Adapter adapter : emfObject.eAdapters()) { + if (adapter instanceof OriginalGrammar.OriginalGrammarAdapter) { + return ((OriginalGrammar.OriginalGrammarAdapter) adapter).get(); + } + } + return null; + } + + public static OriginalGrammar removeFromEmfObject(Notifier emfObject) { + List adapters = emfObject.eAdapters(); + for (int i = 0, max = adapters.size(); i < max; i++) { + Adapter adapter = adapters.get(i); + if (adapter instanceof OriginalGrammar.OriginalGrammarAdapter) { + emfObject.eAdapters().remove(i); + return ((OriginalGrammar.OriginalGrammarAdapter) adapter).get(); + } + } + return null; + } + + public void attachToEmfObject(Notifier emfObject) { + OriginalGrammar result = findInEmfObject(emfObject); + if (result != null) + throw new IllegalStateException("The given EMF object already contains an adapter for OriginalGrammar"); + OriginalGrammar.OriginalGrammarAdapter adapter = new OriginalGrammar.OriginalGrammarAdapter(this); + emfObject.eAdapters().add(adapter); + } + + public OriginalGrammar(Grammar original) { + this.original = original; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((original == null) ? 0 : original.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + OriginalGrammar other = (OriginalGrammar) obj; + if (original == null) { + if (other.original != null) + return false; + } else if (!original.equals(other.original)) + return false; + return true; + } + + @Override + public String toString() { + ToStringBuilder b = new ToStringBuilder(this); + b.add("original", original); + return b.toString(); + } + + public Grammar getOriginal() { + return original; + } +} diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/xtext/RuleWithParameterValues.java b/org.eclipse.xtext/src/org/eclipse/xtext/xtext/RuleWithParameterValues.java new file mode 100644 index 000000000..021f73c6f --- /dev/null +++ b/org.eclipse.xtext/src/org/eclipse/xtext/xtext/RuleWithParameterValues.java @@ -0,0 +1,156 @@ +/** + * 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.xtext; + +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.eclipse.emf.common.notify.Adapter; +import org.eclipse.emf.common.notify.Notifier; +import org.eclipse.emf.common.notify.impl.AdapterImpl; +import org.eclipse.xtext.AbstractRule; +import org.eclipse.xtext.Parameter; +import org.eclipse.xtext.ParserRule; +import org.eclipse.xtext.xbase.lib.util.ToStringBuilder; + +/** + * @author Sebastian Zarnekow - Initial contribution and API + */ +public class RuleWithParameterValues { + public static class RuleWithParameterValuesAdapter extends AdapterImpl { + private RuleWithParameterValues element; + + public RuleWithParameterValuesAdapter(RuleWithParameterValues element) { + this.element = element; + } + + public RuleWithParameterValues get() { + return element; + } + + @Override + public boolean isAdapterForType(Object object) { + return object == RuleWithParameterValues.class; + } + } + + private final AbstractRule original; + + private final Set paramValues; + + public RuleWithParameterValues(AbstractRule original, Set paramValues) { + this.original = original; + this.paramValues = paramValues; + } + + RuleWithParameterValues(AbstractRule original) { + this(original, Collections.emptySet()); + } + + public static AbstractRule getOriginalRule(AbstractRule copy) { + return RuleWithParameterValues.findInEmfObject(copy).getOriginal(); + } + + public static AbstractRule tryGetOriginalRule(AbstractRule copy) { + RuleWithParameterValues adapter = RuleWithParameterValues.findInEmfObject(copy); + AbstractRule rule = null; + if (adapter != null) { + rule = adapter.getOriginal(); + } + return rule; + } + + public static Set getParamValues(AbstractRule copy) { + return RuleWithParameterValues.findInEmfObject(copy).getParamValues(); + } + + public static int getParamConfig(AbstractRule copy) { + RuleWithParameterValues values = RuleWithParameterValues.findInEmfObject(copy); + return ParameterConfigHelper.getParameterConfig(values.paramValues, (ParserRule) values.original); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((original == null) ? 0 : original.hashCode()); + result = prime * result + ((paramValues == null) ? 0 : paramValues.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + RuleWithParameterValues other = (RuleWithParameterValues) obj; + if (original == null) { + if (other.original != null) + return false; + } else if (!original.equals(other.original)) + return false; + if (paramValues == null) { + if (other.paramValues != null) + return false; + } else if (!paramValues.equals(other.paramValues)) + return false; + return true; + } + + @Override + public String toString() { + ToStringBuilder b = new ToStringBuilder(this); + b.add("original", original); + b.add("paramValues", paramValues); + return b.toString(); + } + + public AbstractRule getOriginal() { + return original; + } + + public Set getParamValues() { + return paramValues; + } + + public static RuleWithParameterValues findInEmfObject(Notifier emfObject) { + for (Adapter adapter : emfObject.eAdapters()) { + if (adapter instanceof RuleWithParameterValues.RuleWithParameterValuesAdapter) { + return ((RuleWithParameterValues.RuleWithParameterValuesAdapter) adapter).get(); + } + } + return null; + } + + public static RuleWithParameterValues removeFromEmfObject(Notifier emfObject) { + List adapters = emfObject.eAdapters(); + for (int i = 0, max = adapters.size(); i < max; i++) { + Adapter adapter = adapters.get(i); + if (adapter instanceof RuleWithParameterValues.RuleWithParameterValuesAdapter) { + emfObject.eAdapters().remove(i); + return ((RuleWithParameterValues.RuleWithParameterValuesAdapter) adapter).get(); + } + } + return null; + } + + public void attachToEmfObject(Notifier emfObject) { + RuleWithParameterValues result = findInEmfObject(emfObject); + if (result != null) + throw new IllegalStateException( + "The given EMF object already contains an adapter for RuleWithParameterValues"); + RuleWithParameterValues.RuleWithParameterValuesAdapter adapter = new RuleWithParameterValues.RuleWithParameterValuesAdapter( + this); + emfObject.eAdapters().add(adapter); + } +} diff --git a/org.eclipse.xtext/src/org/eclipse/xtext/xtext/RuleWithParameterValues.xtend b/org.eclipse.xtext/src/org/eclipse/xtext/xtext/RuleWithParameterValues.xtend deleted file mode 100644 index 9b2d23fc1..000000000 --- a/org.eclipse.xtext/src/org/eclipse/xtext/xtext/RuleWithParameterValues.xtend +++ /dev/null @@ -1,54 +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.xtext - -import java.util.Collections -import java.util.Set -import org.eclipse.xtend.lib.annotations.Data -import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor -import org.eclipse.xtext.AbstractRule -import org.eclipse.xtext.Parameter -import org.eclipse.xtext.ParserRule -import org.eclipse.xtext.util.internal.EmfAdaptable - -/** - * @author Sebastian Zarnekow - Initial contribution and API - */ -@Data -@EmfAdaptable -class RuleWithParameterValues { - val AbstractRule original - val Set paramValues - - @FinalFieldsConstructor - new() { - } - - package new(AbstractRule original) { - this(original, Collections.emptySet()) - } - - def static AbstractRule getOriginalRule(AbstractRule copy) { - return findInEmfObject(copy).getOriginal() - } - - def static AbstractRule tryGetOriginalRule(AbstractRule copy) { - return findInEmfObject(copy)?.getOriginal() - } - - def static Set getParamValues(AbstractRule copy) { - return findInEmfObject(copy).getParamValues() - } - - def static int getParamConfig(AbstractRule copy) { - val values = findInEmfObject(copy) - return ParameterConfigHelper.getParameterConfig(values.paramValues, values.original as ParserRule) - } - -} diff --git a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/CompositeGeneratorNode.java b/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/CompositeGeneratorNode.java deleted file mode 100644 index 87c1b3fe9..000000000 --- a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/CompositeGeneratorNode.java +++ /dev/null @@ -1,53 +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.generator.trace.node; - -import java.util.List; -import org.eclipse.xtend.lib.annotations.Accessors; -import org.eclipse.xtend2.lib.StringConcatenation; -import org.eclipse.xtext.generator.trace.node.IGeneratorNode; -import org.eclipse.xtext.xbase.lib.CollectionLiterals; -import org.eclipse.xtext.xbase.lib.Pure; - -/** - * A composite node does not contribute any output directly, but only through its children. - * Thus it is an inner node of the code generator tree. - * - * @author Sven Efftinge - Initial contribution and API - */ -@Accessors -@SuppressWarnings("all") -public class CompositeGeneratorNode implements IGeneratorNode { - private final List children = CollectionLiterals.newArrayList(); - - @Override - public String toString() { - StringConcatenation _builder = new StringConcatenation(); - String _simpleName = this.getClass().getSimpleName(); - _builder.append(_simpleName); - _builder.append(" {"); - _builder.newLineIfNotEmpty(); - { - for(final IGeneratorNode c : this.children) { - _builder.append("\t"); - String _string = c.toString(); - _builder.append(_string, "\t"); - _builder.newLineIfNotEmpty(); - } - } - _builder.append("}"); - _builder.newLine(); - return _builder.toString(); - } - - @Pure - public List getChildren() { - return this.children; - } -} diff --git a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/GeneratorNodeExtensions.java b/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/GeneratorNodeExtensions.java deleted file mode 100644 index 0434b9106..000000000 --- a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/GeneratorNodeExtensions.java +++ /dev/null @@ -1,168 +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.generator.trace.node; - -import com.google.inject.Inject; -import java.util.List; -import org.eclipse.xtend2.lib.StringConcatenationClient; -import org.eclipse.xtext.generator.trace.ILocationData; -import org.eclipse.xtext.generator.trace.node.CompositeGeneratorNode; -import org.eclipse.xtext.generator.trace.node.GeneratorWhiteSpaceConfig; -import org.eclipse.xtext.generator.trace.node.IGeneratorNode; -import org.eclipse.xtext.generator.trace.node.IndentNode; -import org.eclipse.xtext.generator.trace.node.NewLineNode; -import org.eclipse.xtext.generator.trace.node.TemplateNode; -import org.eclipse.xtext.generator.trace.node.TextNode; -import org.eclipse.xtext.generator.trace.node.TraceNode; - -/** - * A builder API to create generator node trees - * - * @author Sven Efftinge - Initial contribution and API - */ -@SuppressWarnings("all") -public class GeneratorNodeExtensions { - @Inject - private GeneratorWhiteSpaceConfig wsConfig = new GeneratorWhiteSpaceConfig(); - - /** - * @return a root trace node for the given location - */ - public CompositeGeneratorNode trace(final ILocationData data) { - final TraceNode result = new TraceNode(data); - return result; - } - - /** - * @return a root trace node for the given location - */ - public CompositeGeneratorNode trace(final ILocationData data, final boolean useForDebugging) { - final TraceNode result = new TraceNode(data); - result.setUseForDebugging(useForDebugging); - return result; - } - - /** - * @return a trace node for the given location, appended as a child on the given parent - */ - public CompositeGeneratorNode trace(final CompositeGeneratorNode parent, final ILocationData data) { - final TraceNode result = new TraceNode(data); - List _children = parent.getChildren(); - _children.add(result); - return result; - } - - /** - * @return a trace node for the given location, appended as a child on the given parent - */ - public CompositeGeneratorNode trace(final CompositeGeneratorNode parent, final ILocationData data, final boolean useForDebugging) { - final TraceNode result = new TraceNode(data); - result.setUseForDebugging(useForDebugging); - List _children = parent.getChildren(); - _children.add(result); - return result; - } - - /** - * @return an indentation node, using the default indentation string, appended as a child on the given parent - */ - public CompositeGeneratorNode indent(final CompositeGeneratorNode parent) { - return this.indent(parent, this.wsConfig.getIndentationString()); - } - - /** - * Appends the indentation string at the current position of the parent and adds a new composite node, indicating the same indentation for - * subsequent lines. - * - * @return an indentation node, using the given indentString, appended as a child on the given parent - */ - public CompositeGeneratorNode indent(final CompositeGeneratorNode parent, final String indentString) { - final IndentNode indent = new IndentNode(indentString); - List _children = parent.getChildren(); - _children.add(indent); - return indent; - } - - /** - * Appends a line separator node to the given parent. - * - * @return the given parent node - */ - public CompositeGeneratorNode appendNewLine(final CompositeGeneratorNode parent) { - List _children = parent.getChildren(); - String _lineDelimiter = this.wsConfig.getLineDelimiter(); - NewLineNode _newLineNode = new NewLineNode(_lineDelimiter, false); - _children.add(_newLineNode); - return parent; - } - - /** - * Appends a line separator node to the given parent. - * - * @return the given parent node - */ - public CompositeGeneratorNode appendNewLine(final CompositeGeneratorNode parent, final String lineSeparator) { - List _children = parent.getChildren(); - NewLineNode _newLineNode = new NewLineNode(lineSeparator, false); - _children.add(_newLineNode); - return parent; - } - - /** - * Appends a line separator node that will only be effective if the current line contains non-whitespace text. - * - * @return the given parent node - */ - public CompositeGeneratorNode appendNewLineIfNotEmpty(final CompositeGeneratorNode parent) { - List _children = parent.getChildren(); - String _lineDelimiter = this.wsConfig.getLineDelimiter(); - NewLineNode _newLineNode = new NewLineNode(_lineDelimiter, true); - _children.add(_newLineNode); - return parent; - } - - /** - * Creates a text node containing the toString() representation of the given object and - * appends it to the given parent node. - * - * @return the given parent node - */ - public CompositeGeneratorNode append(final CompositeGeneratorNode parent, final Object object) { - if ((object instanceof StringConcatenationClient)) { - this.appendTemplate(parent, ((StringConcatenationClient)object)); - } else { - if ((object instanceof IGeneratorNode)) { - List _children = parent.getChildren(); - _children.add(((IGeneratorNode)object)); - } else { - if ((object != null)) { - List _children_1 = parent.getChildren(); - String _string = object.toString(); - TextNode _textNode = new TextNode(_string); - _children_1.add(_textNode); - } - } - } - return parent; - } - - /** - * Creates a template node for the given templateString and appends it to the given parent node. - * - * Templates are translated to generator node trees and expressions in templates can be of type IGeneratorNode. - * - * @return the given parent node - */ - public CompositeGeneratorNode appendTemplate(final CompositeGeneratorNode parent, final StringConcatenationClient templateString) { - final TemplateNode proc = new TemplateNode(templateString, this); - List _children = parent.getChildren(); - _children.add(proc); - return parent; - } -} diff --git a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/IGeneratorNode.java b/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/IGeneratorNode.java deleted file mode 100644 index 352aee2d6..000000000 --- a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/IGeneratorNode.java +++ /dev/null @@ -1,18 +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.generator.trace.node; - -/** - * A node in the code generator tree. - * - * @author Sven Efftinge - Initial contribution and API - */ -@SuppressWarnings("all") -public interface IGeneratorNode { -} diff --git a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/IndentNode.java b/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/IndentNode.java deleted file mode 100644 index fffdfb2e2..000000000 --- a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/IndentNode.java +++ /dev/null @@ -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.generator.trace.node; - -import org.eclipse.xtend.lib.annotations.Accessors; -import org.eclipse.xtext.generator.trace.node.CompositeGeneratorNode; -import org.eclipse.xtext.xbase.lib.Pure; - -/** - * An indent node prepends the indentation string to each line that is generated through its children. - * - * @author Sven Efftinge - Initial contribution and API - */ -@Accessors -@SuppressWarnings("all") -public class IndentNode extends CompositeGeneratorNode { - private String indentationString; - - /** - * When this is set to {@code true}, the indentation is always inserted in the first line, otherwise it is - * inserted only if the first line has no text preceding this node. - */ - private boolean indentImmediately; - - /** - * When this is set to {@code true}, all lines are indented, otherwise only lines with text content are indented. - */ - private boolean indentEmptyLines; - - public IndentNode(final String indentationString) { - this(indentationString, true, false); - } - - public IndentNode(final String indentationString, final boolean indentImmediately, final boolean indentEmptyLines) { - if ((indentationString == null)) { - throw new NullPointerException(); - } - this.indentationString = indentationString; - this.indentImmediately = indentImmediately; - this.indentEmptyLines = indentEmptyLines; - } - - @Pure - public String getIndentationString() { - return this.indentationString; - } - - public void setIndentationString(final String indentationString) { - this.indentationString = indentationString; - } - - @Pure - public boolean isIndentImmediately() { - return this.indentImmediately; - } - - public void setIndentImmediately(final boolean indentImmediately) { - this.indentImmediately = indentImmediately; - } - - @Pure - public boolean isIndentEmptyLines() { - return this.indentEmptyLines; - } - - public void setIndentEmptyLines(final boolean indentEmptyLines) { - this.indentEmptyLines = indentEmptyLines; - } -} diff --git a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/NewLineNode.java b/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/NewLineNode.java deleted file mode 100644 index 2b6bab699..000000000 --- a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/NewLineNode.java +++ /dev/null @@ -1,78 +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.generator.trace.node; - -import org.eclipse.xtend.lib.annotations.Accessors; -import org.eclipse.xtend2.lib.StringConcatenation; -import org.eclipse.xtext.generator.trace.node.IGeneratorNode; -import org.eclipse.xtext.util.Strings; -import org.eclipse.xtext.xbase.lib.Pure; - -/** - * A new line node is a leaf in the code generator tree and produces line breaks. - * - * @author Sven Efftinge - Initial contribution and API - */ -@Accessors -@SuppressWarnings("all") -public class NewLineNode implements IGeneratorNode { - private String lineDelimiter; - - /** - * When this is set to {@code true}, the preceding line is removed if it contains only whitespace. - */ - private boolean ifNotEmpty; - - public NewLineNode(final String lineDelimiter) { - this(lineDelimiter, false); - } - - public NewLineNode(final String lineDelimiter, final boolean ifNotEmpty) { - if ((lineDelimiter == null)) { - throw new NullPointerException(); - } - this.lineDelimiter = lineDelimiter; - this.ifNotEmpty = ifNotEmpty; - } - - @Override - public String toString() { - StringConcatenation _builder = new StringConcatenation(); - String _simpleName = this.getClass().getSimpleName(); - _builder.append(_simpleName); - _builder.append(" \""); - String _convertToJavaString = Strings.convertToJavaString(this.lineDelimiter); - _builder.append(_convertToJavaString); - _builder.append("\""); - { - if (this.ifNotEmpty) { - _builder.append(" if not empty"); - } - } - return _builder.toString(); - } - - @Pure - public String getLineDelimiter() { - return this.lineDelimiter; - } - - public void setLineDelimiter(final String lineDelimiter) { - this.lineDelimiter = lineDelimiter; - } - - @Pure - public boolean isIfNotEmpty() { - return this.ifNotEmpty; - } - - public void setIfNotEmpty(final boolean ifNotEmpty) { - this.ifNotEmpty = ifNotEmpty; - } -} diff --git a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/TextNode.java b/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/TextNode.java deleted file mode 100644 index 037251bc4..000000000 --- a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/TextNode.java +++ /dev/null @@ -1,51 +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.generator.trace.node; - -import org.eclipse.xtend.lib.annotations.Accessors; -import org.eclipse.xtend2.lib.StringConcatenation; -import org.eclipse.xtext.generator.trace.node.IGeneratorNode; -import org.eclipse.xtext.util.Strings; -import org.eclipse.xtext.xbase.lib.Pure; - -/** - * A text node is a leaf in the code generator tree and produces arbitrary text. - * - * @author Sven Efftinge - Initial contribution and API - */ -@Accessors -@SuppressWarnings("all") -public class TextNode implements IGeneratorNode { - private CharSequence text; - - public TextNode(final CharSequence text) { - this.text = text; - } - - @Override - public String toString() { - StringConcatenation _builder = new StringConcatenation(); - String _simpleName = this.getClass().getSimpleName(); - _builder.append(_simpleName); - _builder.append(" \""); - String _convertToJavaString = Strings.convertToJavaString(this.text.toString()); - _builder.append(_convertToJavaString); - _builder.append("\""); - return _builder.toString(); - } - - @Pure - public CharSequence getText() { - return this.text; - } - - public void setText(final CharSequence text) { - this.text = text; - } -} diff --git a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/TraceNode.java b/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/TraceNode.java deleted file mode 100644 index 2c51bbd74..000000000 --- a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/TraceNode.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) 2017 TypeFox (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.generator.trace.node; - -import org.eclipse.xtend.lib.annotations.Accessors; -import org.eclipse.xtext.generator.trace.ILocationData; -import org.eclipse.xtext.generator.trace.node.CompositeGeneratorNode; -import org.eclipse.xtext.xbase.lib.Pure; - -/** - * A trace node maps the text generated through its children to a source location. - * - * @author Sven Efftinge - initial contribution and API - */ -@Accessors -@SuppressWarnings("all") -public class TraceNode extends CompositeGeneratorNode { - private ILocationData sourceLocation; - - public TraceNode(final ILocationData sourceLocation) { - this.sourceLocation = sourceLocation; - } - - private boolean useForDebugging; - - @Pure - public ILocationData getSourceLocation() { - return this.sourceLocation; - } - - public void setSourceLocation(final ILocationData sourceLocation) { - this.sourceLocation = sourceLocation; - } - - @Pure - public boolean isUseForDebugging() { - return this.useForDebugging; - } - - public void setUseForDebugging(final boolean useForDebugging) { - this.useForDebugging = useForDebugging; - } -} diff --git a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/TracingSugar.java b/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/TracingSugar.java deleted file mode 100644 index 035035037..000000000 --- a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/generator/trace/node/TracingSugar.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.eclipse.xtext.generator.trace.node; - -import com.google.inject.Inject; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.ecore.EStructuralFeature; -import org.eclipse.xtend2.lib.StringConcatenationClient; -import org.eclipse.xtext.generator.IFileSystemAccess2; -import org.eclipse.xtext.generator.trace.ILocationData; -import org.eclipse.xtext.generator.trace.ITraceURIConverter; -import org.eclipse.xtext.generator.trace.LocationData; -import org.eclipse.xtext.generator.trace.SourceRelativeURI; -import org.eclipse.xtext.generator.trace.node.CompositeGeneratorNode; -import org.eclipse.xtext.generator.trace.node.GeneratorNodeExtensions; -import org.eclipse.xtext.generator.trace.node.GeneratorNodeProcessor; -import org.eclipse.xtext.generator.trace.node.GeneratorWhiteSpaceConfig; -import org.eclipse.xtext.resource.ILocationInFileProvider; -import org.eclipse.xtext.util.ITextRegion; -import org.eclipse.xtext.util.ITextRegionWithLineInformation; - -/** - * Some additional sugar extension to - * - create generator nodes for EObjects - * - create ILocationData for EObjects. - * - enhance FileSystemAccess for tracing - */ -@SuppressWarnings("all") -public class TracingSugar extends GeneratorNodeExtensions { - @Inject - protected ILocationInFileProvider locationProvider; - - @Inject - protected ITraceURIConverter traceURIConverter; - - @Inject - protected GeneratorWhiteSpaceConfig whiteSpaceConfig; - - @Inject - protected GeneratorNodeProcessor processor; - - /** - * Convenience extension, to generate traced code. - */ - public void generateTracedFile(final IFileSystemAccess2 fsa, final String path, final EObject rootTrace, final StringConcatenationClient code) { - final CompositeGeneratorNode node = this.trace(rootTrace, code); - this.generateTracedFile(fsa, path, node); - } - - /** - * Use to generate a file based on generator node. - */ - public void generateTracedFile(final IFileSystemAccess2 fsa, final String path, final CompositeGeneratorNode rootNode) { - final GeneratorNodeProcessor.Result result = this.processor.process(rootNode); - fsa.generateFile(path, result); - } - - /** - * Convenience shorthand for obj.location.trace - */ - public CompositeGeneratorNode trace(final EObject obj) { - return this.trace(this.location(obj)); - } - - /** - * Convenience shorthand for obj.trace.appendTemplate('''some template''') - */ - public CompositeGeneratorNode trace(final EObject obj, final StringConcatenationClient code) { - return this.appendTemplate(this.trace(obj), code); - } - - /** - * @return ILocationData covering the fullTextRegion of the given EObject. - */ - public ILocationData location(final EObject obj) { - final ITextRegion region = this.locationProvider.getFullTextRegion(obj); - final SourceRelativeURI uri = this.traceURIConverter.getURIForTrace(obj.eResource()); - return new LocationData(((ITextRegionWithLineInformation) region), uri); - } - - /** - * @param obj the EObject containing the feature - * @param feature the EStructuralFeature to trace - * @param idx the index of the value to trace, in case the feature contains a list, should be -1 otherwise. - * - * @return ILocationData covering the fullTextRegion of the given feature in the given EObject. - */ - public ILocationData location(final EObject obj, final EStructuralFeature feature, final int idx) { - final ITextRegion region = this.locationProvider.getFullTextRegion(obj, feature, idx); - final SourceRelativeURI uri = this.traceURIConverter.getURIForTrace(obj.eResource()); - return new LocationData(((ITextRegionWithLineInformation) region), uri); - } -} diff --git a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/xtext/OriginalElement.java b/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/xtext/OriginalElement.java deleted file mode 100644 index d2d38d91c..000000000 --- a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/xtext/OriginalElement.java +++ /dev/null @@ -1,117 +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.xtext; - -import java.util.List; -import org.eclipse.emf.common.notify.Adapter; -import org.eclipse.emf.common.notify.Notifier; -import org.eclipse.emf.common.notify.impl.AdapterImpl; -import org.eclipse.xtend.lib.annotations.Data; -import org.eclipse.xtext.AbstractElement; -import org.eclipse.xtext.util.internal.EmfAdaptable; -import org.eclipse.xtext.xbase.lib.Pure; -import org.eclipse.xtext.xbase.lib.util.ToStringBuilder; - -/** - * @author Sebastian Zarnekow - Initial contribution and API - */ -@EmfAdaptable -@Data -@SuppressWarnings("all") -public class OriginalElement { - public static class OriginalElementAdapter extends AdapterImpl { - private OriginalElement element; - - public OriginalElementAdapter(final OriginalElement element) { - this.element = element; - } - - public OriginalElement get() { - return this.element; - } - - @Override - public boolean isAdapterForType(final Object object) { - return object == OriginalElement.class; - } - } - - private final AbstractElement original; - - public static OriginalElement findInEmfObject(final Notifier emfObject) { - for (Adapter adapter : emfObject.eAdapters()) { - if (adapter instanceof OriginalElement.OriginalElementAdapter) { - return ((OriginalElement.OriginalElementAdapter) adapter).get(); - } - } - return null; - } - - public static OriginalElement removeFromEmfObject(final Notifier emfObject) { - List adapters = emfObject.eAdapters(); - for(int i = 0, max = adapters.size(); i < max; i++) { - Adapter adapter = adapters.get(i); - if (adapter instanceof OriginalElement.OriginalElementAdapter) { - emfObject.eAdapters().remove(i); - return ((OriginalElement.OriginalElementAdapter) adapter).get(); - } - } - return null; - } - - public void attachToEmfObject(final Notifier emfObject) { - OriginalElement result = findInEmfObject(emfObject); - if (result != null) - throw new IllegalStateException("The given EMF object already contains an adapter for OriginalElement"); - OriginalElement.OriginalElementAdapter adapter = new OriginalElement.OriginalElementAdapter(this); - emfObject.eAdapters().add(adapter); - } - - public OriginalElement(final AbstractElement original) { - super(); - this.original = original; - } - - @Override - @Pure - public int hashCode() { - return 31 * 1 + ((this.original== null) ? 0 : this.original.hashCode()); - } - - @Override - @Pure - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - OriginalElement other = (OriginalElement) obj; - if (this.original == null) { - if (other.original != null) - return false; - } else if (!this.original.equals(other.original)) - return false; - return true; - } - - @Override - @Pure - public String toString() { - ToStringBuilder b = new ToStringBuilder(this); - b.add("original", this.original); - return b.toString(); - } - - @Pure - public AbstractElement getOriginal() { - return this.original; - } -} diff --git a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/xtext/OriginalGrammar.java b/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/xtext/OriginalGrammar.java deleted file mode 100644 index 45a108d56..000000000 --- a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/xtext/OriginalGrammar.java +++ /dev/null @@ -1,117 +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.xtext; - -import java.util.List; -import org.eclipse.emf.common.notify.Adapter; -import org.eclipse.emf.common.notify.Notifier; -import org.eclipse.emf.common.notify.impl.AdapterImpl; -import org.eclipse.xtend.lib.annotations.Data; -import org.eclipse.xtext.Grammar; -import org.eclipse.xtext.util.internal.EmfAdaptable; -import org.eclipse.xtext.xbase.lib.Pure; -import org.eclipse.xtext.xbase.lib.util.ToStringBuilder; - -/** - * @author Sebastian Zarnekow - Initial contribution and API - */ -@EmfAdaptable -@Data -@SuppressWarnings("all") -public class OriginalGrammar { - public static class OriginalGrammarAdapter extends AdapterImpl { - private OriginalGrammar element; - - public OriginalGrammarAdapter(final OriginalGrammar element) { - this.element = element; - } - - public OriginalGrammar get() { - return this.element; - } - - @Override - public boolean isAdapterForType(final Object object) { - return object == OriginalGrammar.class; - } - } - - private final Grammar original; - - public static OriginalGrammar findInEmfObject(final Notifier emfObject) { - for (Adapter adapter : emfObject.eAdapters()) { - if (adapter instanceof OriginalGrammar.OriginalGrammarAdapter) { - return ((OriginalGrammar.OriginalGrammarAdapter) adapter).get(); - } - } - return null; - } - - public static OriginalGrammar removeFromEmfObject(final Notifier emfObject) { - List adapters = emfObject.eAdapters(); - for(int i = 0, max = adapters.size(); i < max; i++) { - Adapter adapter = adapters.get(i); - if (adapter instanceof OriginalGrammar.OriginalGrammarAdapter) { - emfObject.eAdapters().remove(i); - return ((OriginalGrammar.OriginalGrammarAdapter) adapter).get(); - } - } - return null; - } - - public void attachToEmfObject(final Notifier emfObject) { - OriginalGrammar result = findInEmfObject(emfObject); - if (result != null) - throw new IllegalStateException("The given EMF object already contains an adapter for OriginalGrammar"); - OriginalGrammar.OriginalGrammarAdapter adapter = new OriginalGrammar.OriginalGrammarAdapter(this); - emfObject.eAdapters().add(adapter); - } - - public OriginalGrammar(final Grammar original) { - super(); - this.original = original; - } - - @Override - @Pure - public int hashCode() { - return 31 * 1 + ((this.original== null) ? 0 : this.original.hashCode()); - } - - @Override - @Pure - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - OriginalGrammar other = (OriginalGrammar) obj; - if (this.original == null) { - if (other.original != null) - return false; - } else if (!this.original.equals(other.original)) - return false; - return true; - } - - @Override - @Pure - public String toString() { - ToStringBuilder b = new ToStringBuilder(this); - b.add("original", this.original); - return b.toString(); - } - - @Pure - public Grammar getOriginal() { - return this.original; - } -} diff --git a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/xtext/RuleWithParameterValues.java b/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/xtext/RuleWithParameterValues.java deleted file mode 100644 index fc967f7ab..000000000 --- a/org.eclipse.xtext/xtend-gen/org/eclipse/xtext/xtext/RuleWithParameterValues.java +++ /dev/null @@ -1,167 +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.xtext; - -import java.util.Collections; -import java.util.List; -import java.util.Set; -import org.eclipse.emf.common.notify.Adapter; -import org.eclipse.emf.common.notify.Notifier; -import org.eclipse.emf.common.notify.impl.AdapterImpl; -import org.eclipse.xtend.lib.annotations.Data; -import org.eclipse.xtend.lib.annotations.FinalFieldsConstructor; -import org.eclipse.xtext.AbstractRule; -import org.eclipse.xtext.Parameter; -import org.eclipse.xtext.ParserRule; -import org.eclipse.xtext.util.internal.EmfAdaptable; -import org.eclipse.xtext.xbase.lib.Pure; -import org.eclipse.xtext.xbase.lib.util.ToStringBuilder; -import org.eclipse.xtext.xtext.ParameterConfigHelper; - -/** - * @author Sebastian Zarnekow - Initial contribution and API - */ -@Data -@EmfAdaptable -@SuppressWarnings("all") -public class RuleWithParameterValues { - public static class RuleWithParameterValuesAdapter extends AdapterImpl { - private RuleWithParameterValues element; - - public RuleWithParameterValuesAdapter(final RuleWithParameterValues element) { - this.element = element; - } - - public RuleWithParameterValues get() { - return this.element; - } - - @Override - public boolean isAdapterForType(final Object object) { - return object == RuleWithParameterValues.class; - } - } - - private final AbstractRule original; - - private final Set paramValues; - - @FinalFieldsConstructor - public RuleWithParameterValues(final AbstractRule original, final Set paramValues) { - super(); - this.original = original; - this.paramValues = paramValues; - } - - RuleWithParameterValues(final AbstractRule original) { - this(original, Collections.emptySet()); - } - - public static AbstractRule getOriginalRule(final AbstractRule copy) { - return RuleWithParameterValues.findInEmfObject(copy).getOriginal(); - } - - public static AbstractRule tryGetOriginalRule(final AbstractRule copy) { - RuleWithParameterValues _findInEmfObject = RuleWithParameterValues.findInEmfObject(copy); - AbstractRule _original = null; - if (_findInEmfObject!=null) { - _original=_findInEmfObject.getOriginal(); - } - return _original; - } - - public static Set getParamValues(final AbstractRule copy) { - return RuleWithParameterValues.findInEmfObject(copy).getParamValues(); - } - - public static int getParamConfig(final AbstractRule copy) { - final RuleWithParameterValues values = RuleWithParameterValues.findInEmfObject(copy); - return ParameterConfigHelper.getParameterConfig(values.paramValues, ((ParserRule) values.original)); - } - - @Override - @Pure - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((this.original== null) ? 0 : this.original.hashCode()); - return prime * result + ((this.paramValues== null) ? 0 : this.paramValues.hashCode()); - } - - @Override - @Pure - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - RuleWithParameterValues other = (RuleWithParameterValues) obj; - if (this.original == null) { - if (other.original != null) - return false; - } else if (!this.original.equals(other.original)) - return false; - if (this.paramValues == null) { - if (other.paramValues != null) - return false; - } else if (!this.paramValues.equals(other.paramValues)) - return false; - return true; - } - - @Override - @Pure - public String toString() { - ToStringBuilder b = new ToStringBuilder(this); - b.add("original", this.original); - b.add("paramValues", this.paramValues); - return b.toString(); - } - - @Pure - public AbstractRule getOriginal() { - return this.original; - } - - @Pure - public Set getParamValues() { - return this.paramValues; - } - - public static RuleWithParameterValues findInEmfObject(final Notifier emfObject) { - for (Adapter adapter : emfObject.eAdapters()) { - if (adapter instanceof RuleWithParameterValues.RuleWithParameterValuesAdapter) { - return ((RuleWithParameterValues.RuleWithParameterValuesAdapter) adapter).get(); - } - } - return null; - } - - public static RuleWithParameterValues removeFromEmfObject(final Notifier emfObject) { - List adapters = emfObject.eAdapters(); - for(int i = 0, max = adapters.size(); i < max; i++) { - Adapter adapter = adapters.get(i); - if (adapter instanceof RuleWithParameterValues.RuleWithParameterValuesAdapter) { - emfObject.eAdapters().remove(i); - return ((RuleWithParameterValues.RuleWithParameterValuesAdapter) adapter).get(); - } - } - return null; - } - - public void attachToEmfObject(final Notifier emfObject) { - RuleWithParameterValues result = findInEmfObject(emfObject); - if (result != null) - throw new IllegalStateException("The given EMF object already contains an adapter for RuleWithParameterValues"); - RuleWithParameterValues.RuleWithParameterValuesAdapter adapter = new RuleWithParameterValues.RuleWithParameterValuesAdapter(this); - emfObject.eAdapters().add(adapter); - } -}