Search in sources :

Example 6 with PrepareRenameResult

use of org.eclipse.lsp4j.PrepareRenameResult in project eclipse.jdt.ls by eclipse.

the class PrepareRenameHandlerTest method testRenameTypeParameterInMethod.

@Test
public void testRenameTypeParameterInMethod() throws JavaModelException, BadLocationException {
    IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
    String[] codes = { "package test1;\n", "public class B<T> {\n", "	private T t;\n", "	public <U|* extends Number> inspect(U u) { return u; }\n", "}\n" };
    StringBuilder builder = new StringBuilder();
    Position pos = mergeCode(builder, codes);
    ICompilationUnit cu = pack1.createCompilationUnit("B.java", builder.toString(), false, null);
    Either<Range, PrepareRenameResult> result = prepareRename(cu, pos, "UU");
    assertNotNull(result.getLeft());
    assertTrue(result.getLeft().getStart().getLine() > 0);
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) Position(org.eclipse.lsp4j.Position) PrepareRenameResult(org.eclipse.lsp4j.PrepareRenameResult) Range(org.eclipse.lsp4j.Range) AbstractProjectsManagerBasedTest(org.eclipse.jdt.ls.core.internal.managers.AbstractProjectsManagerBasedTest) Test(org.junit.Test)

Example 7 with PrepareRenameResult

use of org.eclipse.lsp4j.PrepareRenameResult in project n4js by eclipse.

the class AbstractRenameTest method performTestAtPosition.

private void performTestAtPosition(RenamePosition pos, RenameTestConfiguration config) throws InterruptedException, ExecutionException {
    FileURI fileURI = getFileURIFromModuleName(pos.moduleName);
    String uriStr = fileURI.toString();
    // ensure the file with URI 'fileURI' is open and is the only opened file
    if (!getOpenFiles().equals(Collections.singleton(fileURI))) {
        closeAllFiles();
        joinServerRequests();
        openFile(fileURI);
        joinServerRequests();
    }
    String sourceBefore = config.projectsModulesSourcesBefore.get(pos.projectName).get(pos.moduleName);
    PrepareRenameParams prepareRenameParams = new PrepareRenameParams();
    prepareRenameParams.setTextDocument(new TextDocumentIdentifier(uriStr));
    prepareRenameParams.setPosition(new Position(pos.line, pos.column));
    Either<Range, PrepareRenameResult> result1 = languageServer.prepareRename(prepareRenameParams).get();
    if (result1 == null || (result1.getLeft() == null && result1.getRight() == null)) {
        fail("element cannot be renamed", sourceBefore, pos);
    }
    RenameParams renameParams = new RenameParams();
    renameParams.setTextDocument(new TextDocumentIdentifier(uriStr));
    renameParams.setPosition(new Position(pos.line, pos.column));
    renameParams.setNewName(config.newName);
    WorkspaceEdit workspaceEdit = languageServer.rename(renameParams).get();
    Map<FileURI, String> fileURI2ActualSourceAfter = applyWorkspaceEdit(config.projectsModulesSourcesBefore, workspaceEdit, pos, config);
    Set<FileURI> checkedFileURIs = new LinkedHashSet<>();
    for (Map<String, String> moduleName2ExpectedSourceAfter : config.projectsModulesExpectedSourcesAfter.values()) {
        for (Entry<String, String> entry : moduleName2ExpectedSourceAfter.entrySet()) {
            String moduleName = entry.getKey();
            String expectedSourceAfter = entry.getValue();
            FileURI changedFileURI = getFileURIFromModuleName(moduleName);
            String actualSourceAfter = fileURI2ActualSourceAfter.get(changedFileURI);
            if (actualSourceAfter == null) {
                fail("expected changes in module '" + moduleName + "' but rename did not lead to any changes in this module", sourceBefore, pos);
            } else if (!actualSourceAfter.equals(expectedSourceAfter)) {
                fail("rename led to incorrect source code changes in module '" + moduleName + "'", sourceBefore, pos, expectedSourceAfter, actualSourceAfter);
            }
            checkedFileURIs.add(changedFileURI);
        }
    }
    for (Entry<FileURI, String> entry : fileURI2ActualSourceAfter.entrySet()) {
        FileURI changedFileURI = entry.getKey();
        String actualSourceAfter = entry.getValue();
        if (!checkedFileURIs.contains(changedFileURI)) {
            fail("rename led to unexpected changes in file '" + changedFileURI.getName() + "'", sourceBefore, pos, null, actualSourceAfter);
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) TextDocumentIdentifier(org.eclipse.lsp4j.TextDocumentIdentifier) Position(org.eclipse.lsp4j.Position) RenameParams(org.eclipse.lsp4j.RenameParams) PrepareRenameParams(org.eclipse.lsp4j.PrepareRenameParams) WorkspaceEdit(org.eclipse.lsp4j.WorkspaceEdit) PrepareRenameResult(org.eclipse.lsp4j.PrepareRenameResult) PrepareRenameParams(org.eclipse.lsp4j.PrepareRenameParams) Range(org.eclipse.lsp4j.Range) FileURI(org.eclipse.n4js.workspace.locations.FileURI)

Example 8 with PrepareRenameResult

use of org.eclipse.lsp4j.PrepareRenameResult in project magik-tools by StevenLooman.

the class RenameProvider method providePrepareRename.

/**
 * Provide prepare rename.
 * @param magikFile Magik file.
 * @param position Position in magik source.
 * @return Prepare rename or null if no rename possible.
 */
public Either<org.eclipse.lsp4j.Range, PrepareRenameResult> providePrepareRename(final MagikTypedFile magikFile, final Position position) {
    // Parse magik.
    final AstNode topNode = magikFile.getTopNode();
    // Should always be on an identifier.
    final AstNode node = AstQuery.nodeAt(topNode, Lsp4jConversion.positionFromLsp4j(position), MagikGrammar.IDENTIFIER);
    if (node == null) {
        return null;
    }
    // Set up scope.
    final ScopeEntry scopeEntry = this.findScopeEntry(magikFile, node);
    if (scopeEntry == null || scopeEntry.isType(ScopeEntry.Type.GLOBAL) || scopeEntry.isType(ScopeEntry.Type.DYNAMIC) || scopeEntry.isType(ScopeEntry.Type.IMPORT)) {
        return null;
    }
    final Range range = new Range(node);
    final org.eclipse.lsp4j.Range rangeLsp4j = Lsp4jConversion.rangeToLsp4j(range);
    final String identifier = node.getTokenOriginalValue();
    final PrepareRenameResult result = new PrepareRenameResult(rangeLsp4j, identifier);
    return Either.forRight(result);
}
Also used : ScopeEntry(nl.ramsolutions.sw.magik.analysis.scope.ScopeEntry) PrepareRenameResult(org.eclipse.lsp4j.PrepareRenameResult) Range(nl.ramsolutions.sw.magik.analysis.Range) AstNode(com.sonar.sslr.api.AstNode)

Example 9 with PrepareRenameResult

use of org.eclipse.lsp4j.PrepareRenameResult in project xtext-core by eclipse.

the class RenamePositionTest method renameAndFail.

protected void renameAndFail(String model, Position position, String messageFragment) {
    String modelFile = writeFile("MyType.testlang", model);
    initialize();
    try {
        TextDocumentIdentifier identifier = new TextDocumentIdentifier(modelFile);
        Either<Range, PrepareRenameResult> prepareRenameResult = languageServer.prepareRename(new PrepareRenameParams(identifier, position)).get();
        Assert.assertNull("expected null result got " + prepareRenameResult + " instead", prepareRenameResult);
        RenameParams renameParams = new RenameParams(new TextDocumentIdentifier(modelFile), position, "Tescht");
        languageServer.rename(renameParams).get();
        Assert.fail("Rename should have failed");
    } catch (Exception exc) {
        Throwable rootCause = Throwables.getRootCause(exc);
        Assert.assertTrue(rootCause instanceof ResponseErrorException);
        ResponseError error = ((ResponseErrorException) rootCause).getResponseError();
        Assert.assertTrue(error.getData().toString().contains(messageFragment));
    }
}
Also used : TextDocumentIdentifier(org.eclipse.lsp4j.TextDocumentIdentifier) ResponseErrorException(org.eclipse.lsp4j.jsonrpc.ResponseErrorException) ResponseError(org.eclipse.lsp4j.jsonrpc.messages.ResponseError) PrepareRenameParams(org.eclipse.lsp4j.PrepareRenameParams) RenameParams(org.eclipse.lsp4j.RenameParams) PrepareRenameResult(org.eclipse.lsp4j.PrepareRenameResult) Range(org.eclipse.lsp4j.Range) PrepareRenameParams(org.eclipse.lsp4j.PrepareRenameParams) ResponseErrorException(org.eclipse.lsp4j.jsonrpc.ResponseErrorException)

Example 10 with PrepareRenameResult

use of org.eclipse.lsp4j.PrepareRenameResult in project xtext-core by eclipse.

the class RenameService2 method rename.

@Override
public WorkspaceEdit rename(IRenameService2.Options options) {
    try {
        TextDocumentIdentifier textDocument = options.getRenameParams().getTextDocument();
        String uri = textDocument.getUri();
        ServerRefactoringIssueAcceptor issueAcceptor = issueProvider.get();
        boolean shouldPrepareRename = shouldPrepareRename(options.getLanguageServerAccess());
        return options.getLanguageServerAccess().doRead(uri, (ILanguageServerAccess.Context context) -> {
            if (shouldPrepareRename) {
                TextDocumentIdentifier identifier = new TextDocumentIdentifier(textDocument.getUri());
                Position position = options.getRenameParams().getPosition();
                PrepareRenameParams positionParams = new PrepareRenameParams(identifier, position);
                Resource resource = context.getResource();
                Document document = context.getDocument();
                CancelIndicator cancelIndicator = options.getCancelIndicator();
                Either<Range, PrepareRenameResult> prepareRenameResult = doPrepareRename(resource, document, positionParams, cancelIndicator);
                if (!mayPerformRename(prepareRenameResult, options.getRenameParams())) {
                    return null;
                }
            }
            WorkspaceEdit workspaceEdit = new WorkspaceEdit();
            ResourceSet resourceSet = options.getLanguageServerAccess().newLiveScopeResourceSet(context.getResource().getURI());
            Resource xtextResource = resourceSet.getResource(context.getResource().getURI(), true);
            if (xtextResource instanceof XtextResource) {
                Position position = options.getRenameParams().getPosition();
                EObject element = null;
                try {
                    element = getElementAtOffset((XtextResource) xtextResource, context.getDocument(), position);
                } catch (IndexOutOfBoundsException e) {
                    issueAcceptor.add(RefactoringIssueAcceptor.Severity.FATAL, "Invalid document " + toPositionFragment(position, uri));
                }
                if (element == null || element.eIsProxy()) {
                    issueAcceptor.add(RefactoringIssueAcceptor.Severity.FATAL, "No element found at " + toPositionFragment(position, uri));
                } else {
                    applyModifications(element, workspaceEdit, issueAcceptor, options, context);
                }
            } else {
                issueAcceptor.add(RefactoringIssueAcceptor.Severity.FATAL, "Loaded resource is not an XtextResource", context.getResource().getURI());
            }
            issueAcceptor.checkSeverity();
            return workspaceEdit;
        }).exceptionally((Throwable exception) -> {
            try {
                Throwable rootCause = Throwables.getRootCause(exception);
                if (rootCause instanceof FileNotFoundException) {
                    if (shouldPrepareRename) {
                        return null;
                    }
                }
                throw exception;
            } catch (Throwable e) {
                throw Exceptions.sneakyThrow(e);
            }
        }).get();
    } catch (InterruptedException | ExecutionException e) {
        throw Exceptions.sneakyThrow(e);
    }
}
Also used : RenameContext(org.eclipse.xtext.ide.refactoring.RenameContext) TextDocumentIdentifier(org.eclipse.lsp4j.TextDocumentIdentifier) Position(org.eclipse.lsp4j.Position) Resource(org.eclipse.emf.ecore.resource.Resource) XtextResource(org.eclipse.xtext.resource.XtextResource) FileNotFoundException(java.io.FileNotFoundException) WorkspaceEdit(org.eclipse.lsp4j.WorkspaceEdit) XtextResource(org.eclipse.xtext.resource.XtextResource) PrepareRenameResult(org.eclipse.lsp4j.PrepareRenameResult) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) PrepareRenameParams(org.eclipse.lsp4j.PrepareRenameParams) Document(org.eclipse.xtext.ide.server.Document) Range(org.eclipse.lsp4j.Range) EObject(org.eclipse.emf.ecore.EObject) CancelIndicator(org.eclipse.xtext.util.CancelIndicator) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

PrepareRenameResult (org.eclipse.lsp4j.PrepareRenameResult)16 Range (org.eclipse.lsp4j.Range)15 Position (org.eclipse.lsp4j.Position)14 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)9 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)9 AbstractProjectsManagerBasedTest (org.eclipse.jdt.ls.core.internal.managers.AbstractProjectsManagerBasedTest)9 Test (org.junit.Test)9 PrepareRenameParams (org.eclipse.lsp4j.PrepareRenameParams)4 RenameParams (org.eclipse.lsp4j.RenameParams)3 TextDocumentIdentifier (org.eclipse.lsp4j.TextDocumentIdentifier)3 WorkspaceEdit (org.eclipse.lsp4j.WorkspaceEdit)3 ExecutionException (java.util.concurrent.ExecutionException)2 Test (org.junit.jupiter.api.Test)2 JsonArray (com.google.gson.JsonArray)1 AstNode (com.sonar.sslr.api.AstNode)1 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Collection (java.util.Collection)1