Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code cleanup #1006

Merged
merged 9 commits into from
May 21, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ private CompletableFuture<Void> sendBreakpoints() {
Source source = entry.getKey();
List<SourceBreakpoint> bps = entry.getValue();
int[] lines = bps.stream().mapToInt(SourceBreakpoint::getLine).toArray();
SourceBreakpoint[] sourceBps = bps.toArray(new SourceBreakpoint[bps.size()]);
SourceBreakpoint[] sourceBps = bps.toArray(SourceBreakpoint[]::new);

final var arguments = new SetBreakpointsArguments();
arguments.setSource(source);
Expand All @@ -238,7 +238,7 @@ private CompletableFuture<Void> sendBreakpoints() {
iterator.remove();
}
}
return CompletableFuture.allOf(all.toArray(new CompletableFuture[all.size()]));
return CompletableFuture.allOf(all.toArray(CompletableFuture[]::new));
}

public void breakpointEvent(BreakpointEventArguments args) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ public IVariable[] getVariables() throws DebugException {
scope.getVariablesReference());
vars.add(variable);
}
cachedVariables = vars.toArray(new IVariable[vars.size()]);
cachedVariables = vars.toArray(IVariable[]::new);
}
return cachedVariables;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -228,13 +228,14 @@ public IStackFrame getTopStackFrame() throws DebugException {
}
}

@Override public IStackFrame[] getStackFrames() throws DebugException {
@Override
public IStackFrame[] getStackFrames() throws DebugException {
if (!isSuspended()) {
return new IStackFrame[0];
}
if (!refreshFrames.getAndSet(false)) {
synchronized (frames) {
return frames.toArray(new DSPStackFrame[frames.size()]);
return frames.toArray(DSPStackFrame[]::new);
}
}
try {
Expand All @@ -255,7 +256,7 @@ public IStackFrame getTopStackFrame() throws DebugException {
}
}
frames.subList(backendFrames.length, frames.size()).clear();
return frames.toArray(new DSPStackFrame[frames.size()]);
return frames.toArray(DSPStackFrame[]::new);
}
});
return future.get();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public IVariable[] getVariables() throws DebugException {
variable.getValue(), variable.getVariablesReference()));
}

cachedVariables = variables.toArray(new DSPVariable[variables.size()]);
cachedVariables = variables.toArray(DSPVariable[]::new);
}
return cachedVariables;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ public void initializeFrom(ILaunchConfiguration configuration) {
} else if (args.size() == 1) {
debugArgsText.setText(args.get(0));
} else {
debugArgsText.setText(String.join(" ", args.toArray(new String[args.size()])));
debugArgsText.setText(String.join(" ", args.toArray(String[]::new)));
}
monitorAdapterLauncherProcessCheckbox
.setSelection(configuration.getAttribute(DSPPlugin.ATTR_DSP_MONITOR_DEBUG_ADAPTER, false));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public DocumentContentSynchronizer(@NonNull LanguageServerWrapper languageServer

List<IContentType> contentTypes = LSPEclipseUtils.getDocumentContentTypes(this.document);

String languageId = languageServerWrapper.getLanguageId(contentTypes.toArray(new IContentType[0]));
String languageId = languageServerWrapper.getLanguageId(contentTypes.toArray(IContentType[]::new));

if (languageId == null && this.fileUri.getPath() != null) {
IPath path = Path.fromPortableString(this.fileUri.getPath());
Expand Down
6 changes: 3 additions & 3 deletions org.eclipse.lsp4e/src/org/eclipse/lsp4e/LSPEclipseUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -921,7 +921,7 @@ public static void applyWorkspaceEdit(WorkspaceEdit wsEdit) {

/**
* Applies a workspace edit. It does simply change the underlying documents if all are currently
* open in an editor, otherwise, it performs a Refactoring that will result on filesystem changes.
* open in an editor, otherwise, it performs a refactoring that will result on filesystem changes.
*
* @param wsEdit
* @param label
Expand Down Expand Up @@ -1200,10 +1200,10 @@ private static CompositeChange toCompositeChange(WorkspaceEdit wsEdit, String na
}

private static final Range DEFAULT_RANGE = new Range(new Position(0, 0), new Position(0, 0));
/*

/**
* Reports the URI and the start range of the given text edit, if exists.
*
*
* @param textEdits A list of textEdits sorted in reversed order
*/
private static void collectChangedURI(URI uri, List<TextEdit> textEdits, Map<URI, Range> collector) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,7 @@ public static <T> Stream<T> streamSafely(@Nullable Collection<T> col) {
}

/**
* Retrieves the intialized servers and apply the given query.
* Retrieves the initialized servers and apply the given query.
* <p>The query must ideally be a direct query to the language server
* (not chained with other futures) so cancelling the futures in
* this stream will send a cancellation event to the LSs.</p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
Expand Down Expand Up @@ -322,9 +321,10 @@ private void initialize() {
}

private IEvaluationContext evaluationContext() {
return Optional.ofNullable(PlatformUI.getWorkbench().getService(IHandlerService.class))//
.map(IHandlerService::getCurrentState)//
.orElse(null);
final var handlerService = PlatformUI.getWorkbench().getService(IHandlerService.class);
return handlerService == null
? null
: handlerService.getCurrentState();
}

private void persistContentTypeToLaunchConfigurationMapping() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public class CallHierarchyViewTreeNode {
private final @Nullable Range callSite;

private @Nullable CallHierarchyViewTreeNode parent;
private @Nullable CallHierarchyViewTreeNode[] children;
private CallHierarchyViewTreeNode @Nullable [] children;

/**
* Creates a new instance of {@link CallHierarchyViewTreeNode}.
Expand Down Expand Up @@ -84,7 +84,7 @@ public void setParent(final CallHierarchyViewTreeNode parent) {
*
* @return this node's children.
*/
public @Nullable CallHierarchyViewTreeNode[] getChildren() {
public CallHierarchyViewTreeNode @Nullable [] getChildren() {
return children;
}

Expand All @@ -95,7 +95,7 @@ public void setParent(final CallHierarchyViewTreeNode parent) {
* the new children.
*/
public void setChildren(final @NonNull List<CallHierarchyViewTreeNode> children) {
this.children = children.toArray(new CallHierarchyViewTreeNode[children.size()]);
this.children = children.toArray(CallHierarchyViewTreeNode[]::new);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import com.google.gson.GsonBuilder;

/**
* This converter can be used to serialize/deserailize instances of LSP {@link Command}s.
* This converter can be used to serialize/deserialize instances of LSP {@link Command}s.
*/
public class CommandConverter extends AbstractParameterValueConverter {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ private IRegion[] getChangedLineRegions(IDocument oldDocument, IDocument current
}
}

return regions.toArray(new IRegion[regions.size()]);
return regions.toArray(IRegion[]::new);
}
});
return result[0];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
package org.eclipse.lsp4e.internal;

import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
Expand Down Expand Up @@ -88,8 +87,10 @@ Boolean matches(@NonNull CompletableFuture<@Nullable LanguageServerWrapper> wrap

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
Optional.ofNullable(UI.asTextEditor(HandlerUtil.getActiveEditor(event)))
.ifPresent(textEditor -> execute(event, textEditor));
final var textEditor = UI.asTextEditor(HandlerUtil.getActiveEditor(event));
if (textEditor != null) {
execute(event, textEditor);
}
return null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationC
.forEach(action -> processNewProposal(invocationContext, new CodeActionCompletionProposal(action, w)))));

CompletableFuture<?> aggregateFutures = CompletableFuture
.allOf(futures.toArray(new CompletableFuture[futures.size()]));
.allOf(futures.toArray(CompletableFuture[]::new));

try {
// If the result completes quickly without blocking the UI, then return result directly
Expand All @@ -167,7 +167,7 @@ public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationC
}
}
}
return proposals.toArray(new ICompletionProposal[proposals.size()]);
return proposals.toArray(ICompletionProposal[]::new);
}

private void processNewProposal(IQuickAssistInvocationContext invocationContext, ICompletionProposal p) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ public static int getCategoryOfFilterMatch(String documentFilter, String complet
* completionFilter: xaxxbc<br>
* result: 5<br>
* logic:<br>
* There is 1 character before the 'a' and there is 4 charachters before the
* There is 1 character before the 'a' and there is 4 characters before the
* 'b', because the 'c' is directly after the 'b', it's prefix is ignored,<br>
* 1+4=5
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int
completeProposals[i] = completeProposal;
i++;
} else {
return proposals.toArray(new ICompletionProposal[proposals.size()]);
return proposals.toArray(ICompletionProposal[]::new);
}
}
Arrays.sort(completeProposals, proposalComparator);
Expand Down Expand Up @@ -308,7 +308,7 @@ public IContextInformation[] computeContextInformation(ITextViewer viewer, int o
LanguageServerPlugin.logWarning("Could not compute context information due to timeout after " + CONTEXT_INFORMATION_TIMEOUT + " milliseconds", e); //$NON-NLS-1$//$NON-NLS-2$
return new IContextInformation[] { /* TODO? show error in context information */ };
}
return contextInformations.toArray(new IContextInformation[0]);
return contextInformations.toArray(IContextInformation[]::new);
}

private static IContextInformation toContextInformation(SignatureInformation information) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boo
if (allLinks.isEmpty()) {
return null;
}
return allLinks.values().toArray(new IHyperlink[allLinks.size()]);
return allLinks.values().toArray(IHyperlink[]::new);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ private void updateEditorAnnotations(@NonNull ISourceViewer sourceViewer, Publis
LanguageServerPlugin.logError(ex);
}
});
annotationModelExtension.replaceAnnotations(toRemove.toArray(new Annotation[toRemove.size()]), toAdd);
annotationModelExtension.replaceAnnotations(toRemove.toArray(Annotation[]::new), toAdd);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ private void applyFolding(List<FoldingRange> ranges) {
}
// send the calculated updates to the annotations to the
// annotation model
theProjectionAnnotationModel.modifyAnnotations(deletions.toArray(new Annotation[1]), additions,
theProjectionAnnotationModel.modifyAnnotations(deletions.toArray(Annotation[]::new), additions,
new Annotation[0]);
}
}
Expand Down Expand Up @@ -230,7 +230,7 @@ public void projectionEnabled() {
* @param existing
* the existing folding annotations.
* @param additions
* annoation to add
* annotation to add
* @param line
* the line index
* @param endLineNumber
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ private void updateAnnotations(@Nullable List<? extends DocumentHighlight> highl
annotationModel.addAnnotation(mapEntry.getKey(), mapEntry.getValue());
}
}
fOccurrenceAnnotations = annotationMap.keySet().toArray(new Annotation[annotationMap.size()]);
fOccurrenceAnnotations = annotationMap.keySet().toArray(Annotation[]::new);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
*******************************************************************************/
package org.eclipse.lsp4e.operations.references;

import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
Expand Down Expand Up @@ -148,11 +149,11 @@ private static Match toMatch(@NonNull Location location) {
return new FileMatch((IFile) resource, 0, 0, lineEntry);
}
try {
return new URIMatch(location);
} catch (BadLocationException ex) {
return URIMatch.create(location);
} catch (BadLocationException | URISyntaxException ex) {
LanguageServerPlugin.logError(ex);
return null;
}
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,28 @@
package org.eclipse.lsp4e.operations.references;

import java.net.URI;
import java.net.URISyntaxException;

import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.lsp4e.LSPEclipseUtils;
import org.eclipse.lsp4j.Location;
import org.eclipse.search.ui.text.Match;

public class URIMatch extends Match {

public final @NonNull Location location;
public static URIMatch create(final Location location) throws BadLocationException, URISyntaxException {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's wrong with sticking to a constructor here?

Copy link
Member Author

@sebthom sebthom May 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problem is that the first invocation in a constructor needs to be a super() call, that's why the current implementation parses the URI three times instead of once and then reusing the uri object to construct arguments for the parent constructor. which is very inefficient.

That is what we have currently:

public URIMatch(@NonNull Location location) throws BadLocationException {
	super(
		URI.create(location.getUri()),
		LSPEclipseUtils.toOffset(location.getRange().getStart(), LSPEclipseUtils.getDocument(URI.create(location.getUri()))),
		LSPEclipseUtils.toOffset(location.getRange().getEnd(),  LSPEclipseUtils.getDocument(URI.create(location.getUri()))) - LSPEclipseUtils.toOffset(location.getRange().getStart(), LSPEclipseUtils.getDocument(URI.create(location.getUri()))));
	this.location = location;
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, thanks. Can't wait for https://openjdk.org/jeps/447 ;)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, thanks. Can't wait for openjdk.org/jeps/447 ;)

Me too!

final URI uri = new URI(location.getUri());
final IDocument doc = LSPEclipseUtils.getDocument(uri);
final int offset = LSPEclipseUtils.toOffset(location.getRange().getStart(), doc);
final int length = LSPEclipseUtils.toOffset(location.getRange().getEnd(), doc) - LSPEclipseUtils.toOffset(location.getRange().getStart(), doc);
return new URIMatch(location, uri, offset, length);
}

public final Location location;

public URIMatch(@NonNull Location location) throws BadLocationException {
super(URI.create(location.getUri()), //
LSPEclipseUtils.toOffset(location.getRange().getStart(), LSPEclipseUtils.getDocument(URI.create(location.getUri()))),
LSPEclipseUtils.toOffset(location.getRange().getEnd(), LSPEclipseUtils.getDocument(URI.create(location.getUri()))) - LSPEclipseUtils.toOffset(location.getRange().getStart(), LSPEclipseUtils.getDocument(URI.create(location.getUri()))));
protected URIMatch(final Location location, final URI uri, final int offset, final int length) {
super(uri, offset, length);
this.location = location;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
package org.eclipse.lsp4e.operations.semanticTokens;

import java.util.function.Consumer;
import java.util.function.LongConsumer;

import org.eclipse.jface.text.IDocument;
import org.eclipse.lsp4e.Versioned;
Expand All @@ -35,7 +36,7 @@ public VersionedSemanticTokens(long version, Pair<SemanticTokens, SemanticTokens
* to compute the edits
*
*/
public void apply(Consumer<Pair<SemanticTokens, SemanticTokensLegend>> first, Consumer<Long> second) {
public void apply(Consumer<Pair<SemanticTokens, SemanticTokensLegend>> first, LongConsumer second) {
if (sourceDocumentVersion == DocumentUtil.getDocumentModificationStamp(document)) {
first.accept(data);
second.accept(sourceDocumentVersion);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public QuickAccessElement[] computeElements(String query, IProgressMonitor monit
LanguageServerPlugin.logWarning("Could not get workspace symbols due to timeout after 1 second in `workspace/symbol`", e); //$NON-NLS-1$
}

return res.toArray(new QuickAccessElement[res.size()]);
return res.toArray(QuickAccessElement[]::new);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public Object[] getElements(Object inputElement) {
.computeFirst((wrapper, ls) -> ls.getTextDocumentService().prepareTypeHierarchy(prepare).thenApply(items -> new SimpleEntry<>(wrapper, items)))
.thenApply(entry -> {
wrapper = entry.map(Entry::getKey).orElse(null);
return entry.map(Entry::getValue).map(list -> list.toArray(Object[]::new)).orElse(new Object[0]);
return entry.map(Entry::getValue).map(list -> list.toArray()).orElse(new Object[0]);
}).get(500, TimeUnit.MILLISECONDS);
} catch (Exception e) {
LanguageServerPlugin.logError(e);
Expand All @@ -70,7 +70,7 @@ public Object[] getChildren(Object parentElement) {
? textDocumentService.typeHierarchySupertypes(new TypeHierarchySupertypesParams(parentItem))
: textDocumentService.typeHierarchySubtypes(new TypeHierarchySubtypesParams(parentItem));
})
.thenApply(list -> list == null ? new Object[0] : list.toArray(Object[]::new))
.thenApply(list -> list == null ? new Object[0] : list.toArray())
.get(500, TimeUnit.MILLISECONDS);
} catch (Exception e) {
LanguageServerPlugin.logError(e);
Expand Down
Loading