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

Выведение типов #3268

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import org.eclipse.lsp4j.CodeActionOptions;
import org.eclipse.lsp4j.CodeLensOptions;
import org.eclipse.lsp4j.ColorProviderOptions;
import org.eclipse.lsp4j.CompletionOptions;
import org.eclipse.lsp4j.DefinitionOptions;
import org.eclipse.lsp4j.DocumentFormattingOptions;
import org.eclipse.lsp4j.DocumentLinkOptions;
Expand Down Expand Up @@ -123,6 +124,7 @@ public CompletableFuture<InitializeResult> initialize(InitializeParams params) {
capabilities.setRenameProvider(getRenameProvider(params));
capabilities.setInlayHintProvider(getInlayHintProvider());
capabilities.setExecuteCommandProvider(getExecuteCommandProvider());
capabilities.setCompletionProvider(getCompletionProvider());

var result = new InitializeResult(capabilities, serverInfo);

Expand Down Expand Up @@ -336,4 +338,13 @@ private ExecuteCommandOptions getExecuteCommandProvider() {
executeCommandOptions.setWorkDoneProgress(Boolean.FALSE);
return executeCommandOptions;
}

private CompletionOptions getCompletionProvider() {
var completionOptions = new CompletionOptions();
completionOptions.setTriggerCharacters(List.of("."));
completionOptions.setResolveProvider(Boolean.FALSE);
completionOptions.setWorkDoneProgress(Boolean.FALSE);

return completionOptions;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import com.github._1c_syntax.bsl.languageserver.providers.CodeActionProvider;
import com.github._1c_syntax.bsl.languageserver.providers.CodeLensProvider;
import com.github._1c_syntax.bsl.languageserver.providers.ColorProvider;
import com.github._1c_syntax.bsl.languageserver.providers.CompletionProvider;
import com.github._1c_syntax.bsl.languageserver.providers.DefinitionProvider;
import com.github._1c_syntax.bsl.languageserver.providers.DiagnosticProvider;
import com.github._1c_syntax.bsl.languageserver.providers.DocumentLinkProvider;
Expand Down Expand Up @@ -60,6 +61,9 @@
import org.eclipse.lsp4j.ColorPresentation;
import org.eclipse.lsp4j.ColorPresentationParams;
import org.eclipse.lsp4j.Command;
import org.eclipse.lsp4j.CompletionItem;
import org.eclipse.lsp4j.CompletionList;
import org.eclipse.lsp4j.CompletionParams;
import org.eclipse.lsp4j.DefinitionParams;
import org.eclipse.lsp4j.DidChangeTextDocumentParams;
import org.eclipse.lsp4j.DidCloseTextDocumentParams;
Expand Down Expand Up @@ -125,6 +129,7 @@ public class BSLTextDocumentService implements TextDocumentService, ProtocolExte
private final ColorProvider colorProvider;
private final RenameProvider renameProvider;
private final InlayHintProvider inlayHintProvider;
private final CompletionProvider completionProvider;

private final ExecutorService executorService = Executors.newCachedThreadPool(new CustomizableThreadFactory("text-document-service-"));

Expand Down Expand Up @@ -370,6 +375,19 @@ public CompletableFuture<List<InlayHint>> inlayHint(InlayHintParams params) {
);
}

@Override
public CompletableFuture<Either<List<CompletionItem>, CompletionList>> completion(CompletionParams params) {
var documentContext = context.getDocument(params.getTextDocument().getUri());
if (documentContext == null) {
return CompletableFuture.completedFuture(null);
}

return CompletableFuture.supplyAsync(
() -> completionProvider.getCompletions(documentContext, params),
executorService
);
}

@Override
public void didOpen(DidOpenTextDocumentParams params) {
var textDocumentItem = params.getTextDocument();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
package com.github._1c_syntax.bsl.languageserver.hover;

import com.github._1c_syntax.bsl.languageserver.context.symbol.Symbol;
import com.github._1c_syntax.bsl.languageserver.references.model.Reference;
import org.eclipse.lsp4j.MarkupContent;
import org.eclipse.lsp4j.SymbolKind;

Expand All @@ -34,10 +35,11 @@ public interface MarkupContentBuilder<T extends Symbol> {
/**
* Возвращает контент для всплывающего окна на основе символа.
*
* @param symbol Символ, для которого нужно построить контент.
* @param reference Ссылка на символ, для которого нужно построить контент.
* @param symbol Символ с приведенным типом, для которого нужно построить контент.
* @return Сконструированный контент.
*/
MarkupContent getContent(T symbol);
MarkupContent getContent(Reference reference, T symbol);

/**
* Тип символа, на основе которого работает данный построитель.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import com.github._1c_syntax.bsl.languageserver.context.symbol.description.MethodDescription;
import com.github._1c_syntax.bsl.languageserver.context.symbol.description.ParameterDescription;
import com.github._1c_syntax.bsl.languageserver.context.symbol.description.TypeDescription;
import com.github._1c_syntax.bsl.languageserver.references.model.Reference;
import com.github._1c_syntax.bsl.languageserver.utils.MdoRefBuilder;
import com.github._1c_syntax.bsl.languageserver.utils.Resources;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -63,7 +64,7 @@ public class MethodSymbolMarkupContentBuilder implements MarkupContentBuilder<Me
private final LanguageServerConfiguration configuration;

@Override
public MarkupContent getContent(MethodSymbol symbol) {
public MarkupContent getContent(Reference reference, MethodSymbol symbol) {
var markupBuilder = new StringJoiner("\n");

// сигнатура
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration;
import com.github._1c_syntax.bsl.languageserver.context.symbol.VariableSymbol;
import com.github._1c_syntax.bsl.languageserver.context.symbol.variable.VariableDescription;
import com.github._1c_syntax.bsl.languageserver.references.model.Reference;
import com.github._1c_syntax.bsl.languageserver.types.Type;
import com.github._1c_syntax.bsl.languageserver.types.TypeResolver;
import com.github._1c_syntax.bsl.languageserver.utils.MdoRefBuilder;
import com.github._1c_syntax.bsl.languageserver.utils.Resources;
import lombok.RequiredArgsConstructor;
Expand All @@ -32,7 +35,9 @@
import org.eclipse.lsp4j.SymbolKind;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
Expand All @@ -41,10 +46,11 @@ public class VariableSymbolMarkupContentBuilder implements MarkupContentBuilder<
private static final String VARIABLE_KEY = "var";
private static final String EXPORT_KEY = "export";

private final TypeResolver typeResolver;
private final LanguageServerConfiguration configuration;

@Override
public MarkupContent getContent(VariableSymbol symbol) {
public MarkupContent getContent(Reference reference, VariableSymbol symbol) {
var markupBuilder = new StringJoiner("\n");

// сигнатура
Expand All @@ -69,6 +75,10 @@ public MarkupContent getContent(VariableSymbol symbol) {
.map(VariableDescription::getPurposeDescription)
.ifPresent(trailingDescription -> addSectionIfNotEmpty(markupBuilder, trailingDescription));

var types = typeResolver.findTypes(reference);
var typeDescription = getTypeDescription(types);
addSectionIfNotEmpty(markupBuilder, typeDescription);

String content = markupBuilder.toString();

return new MarkupContent(MarkupKind.MARKDOWN, content);
Expand Down Expand Up @@ -112,6 +122,18 @@ private static String getLocation(VariableSymbol symbol) {
);
}

private static String getTypeDescription(List<Type> types) {
var typeDescription = types.stream()
.map(Type::getName)
.collect(Collectors.joining(" | "));

if (!typeDescription.isEmpty()) {
typeDescription = "`" + typeDescription + "`";
}

return typeDescription;
}

private static void addSectionIfNotEmpty(StringJoiner markupBuilder, String newContent) {
if (!newContent.isEmpty()) {
markupBuilder.add(newContent);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package com.github._1c_syntax.bsl.languageserver.providers;

import com.github._1c_syntax.bsl.languageserver.context.DocumentContext;
import com.github._1c_syntax.bsl.languageserver.context.symbol.SourceDefinedSymbol;
import com.github._1c_syntax.bsl.languageserver.context.symbol.Symbol;
import com.github._1c_syntax.bsl.languageserver.types.KnownTypes;
import com.github._1c_syntax.bsl.languageserver.types.TypeResolver;
import com.github._1c_syntax.bsl.languageserver.utils.Ranges;
import com.github._1c_syntax.bsl.languageserver.utils.Trees;
import com.github._1c_syntax.bsl.parser.BSLLexer;
import lombok.RequiredArgsConstructor;
import org.eclipse.lsp4j.CompletionItem;
import org.eclipse.lsp4j.CompletionItemKind;
import org.eclipse.lsp4j.CompletionList;
import org.eclipse.lsp4j.CompletionParams;
import org.eclipse.lsp4j.Range;
import org.eclipse.lsp4j.SymbolKind;
import org.eclipse.lsp4j.jsonrpc.messages.Either;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Component
@RequiredArgsConstructor
public class CompletionProvider {

private final TypeResolver typeResolver;
private final KnownTypes knownTypes;

public Either<List<CompletionItem>, CompletionList> getCompletions(DocumentContext documentContext, CompletionParams params) {

var completionList = new CompletionList();

var position = params.getPosition();
var terminalNode = Trees.findTerminalNodeContainsPosition(documentContext.getAst(), position).orElseThrow();

if (terminalNode.getSymbol().getType() != BSLLexer.DOT) {
return Either.forRight(completionList);
}

var previousToken = Trees.getPreviousTokenFromDefaultChannel(documentContext.getTokens(), terminalNode.getSymbol().getTokenIndex() - 1);
var completionItems = previousToken
.map(Ranges::create)
.map(Range::getStart)
.map(previousTokenPosition -> typeResolver.findTypes(documentContext.getUri(), previousTokenPosition))
.stream()
.flatMap(Collection::stream)
.map(knownTypes::getSymbolByType)
.filter(Optional::isPresent)
.map(Optional::get)
.flatMap(symbol -> getChildren(symbol).stream())
.map(symbol -> {
var completionItem = new CompletionItem();
completionItem.setLabel(symbol.getName());
completionItem.setKind(getCompletionItemKind(symbol.getSymbolKind()));

return completionItem;
})
.toList();

completionList.setItems(completionItems);

return Either.forRight(completionList);
}

private CompletionItemKind getCompletionItemKind(SymbolKind symbolKind) {
return switch (symbolKind) {
case Class -> CompletionItemKind.Class;
case Method -> CompletionItemKind.Method;
case Variable -> CompletionItemKind.Variable;
case Module -> CompletionItemKind.Module;
default -> CompletionItemKind.Text;
};
}

private List<? extends Symbol> getChildren(Symbol symbol) {
if (!(symbol instanceof SourceDefinedSymbol sourceDefinedSymbol)) {
return Collections.emptyList();
}

return sourceDefinedSymbol.getChildren();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
public final class HoverProvider {

private final ReferenceResolver referenceResolver;
private final Map<SymbolKind, MarkupContentBuilder<Symbol>> markupContentBuilders;

Check failure on line 44 in src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/HoverProvider.java

View workflow job for this annotation

GitHub Actions / Qodana for JVM

Incorrect autowiring in Spring bean components

Could not autowire. No beans of 'Map\>' type found.

public Optional<Hover> getHover(DocumentContext documentContext, HoverParams params) {
Position position = params.getPosition();
Expand All @@ -52,7 +52,7 @@
var range = reference.getSelectionRange();

return Optional.ofNullable(markupContentBuilders.get(symbol.getSymbolKind()))
.map(markupContentBuilder -> markupContentBuilder.getContent(symbol))
.map(markupContentBuilder -> markupContentBuilder.getContent(reference, symbol))
.map(content -> new Hover(content, range));
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.github._1c_syntax.bsl.languageserver.types;

import com.github._1c_syntax.bsl.languageserver.context.events.DocumentContextContentChangedEvent;
import com.github._1c_syntax.bsl.languageserver.context.symbol.Symbol;
import org.apache.commons.io.FilenameUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class KnownTypes {

private final Map<Type, Symbol> knownTypes = new ConcurrentHashMap<>();

public void addType(Type type, Symbol symbol) {
knownTypes.put(type, symbol);
}

public Optional<Symbol> getSymbolByType(Type type) {
return Optional.ofNullable(knownTypes.get(type));
}

public void clear() {
knownTypes.clear();
}

@EventListener
public void handleEvent(DocumentContextContentChangedEvent event) {
var documentContext = event.getSource();
// TODO: this logic should be moved to somewhere else. It will break for BSL files.
var typeName = FilenameUtils.getBaseName(documentContext.getUri().getPath());
var module = documentContext.getSymbolTree().getModule();

addType(new Type(typeName), module);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* This file is a part of BSL Language Server.
*
* Copyright (c) 2018-2024
* Alexey Sosnoviy <labotamy@gmail.com>, Nikita Fedkin <nixel2007@gmail.com> and contributors
*
* SPDX-License-Identifier: LGPL-3.0-or-later
*
* BSL Language Server is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* BSL Language Server is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BSL Language Server.
*/
package com.github._1c_syntax.bsl.languageserver.types;

import lombok.Value;

@Value
public class Type {
private final String name;

Check warning on line 28 in src/main/java/com/github/_1c_syntax/bsl/languageserver/types/Type.java

View workflow job for this annotation

GitHub Actions / Qodana for JVM

@Value modifiers

@value already marks non-static fields final.

Check warning on line 28 in src/main/java/com/github/_1c_syntax/bsl/languageserver/types/Type.java

View workflow job for this annotation

GitHub Actions / Qodana for JVM

@Value modifiers

@value already marks non-static, package-local fields private.

Check warning

Code scanning / QDJVM

@Value modifiers Warning

@Value already marks non-static fields final.

Check warning

Code scanning / QDJVM

@Value modifiers Warning

@Value already marks non-static, package-local fields private.
}
Loading
Loading