Search in sources :

Example 6 with DocumentContext

use of com.github._1c_syntax.bsl.languageserver.context.DocumentContext in project bsl-language-server by 1c-syntax.

the class CallHierarchyProvider method incomingCalls.

public List<CallHierarchyIncomingCall> incomingCalls(DocumentContext documentContext, CallHierarchyIncomingCallsParams params) {
    URI uri = documentContext.getUri();
    CallHierarchyItem item = params.getItem();
    Position position = item.getSelectionRange().getStart();
    return referenceResolver.findReference(uri, position).flatMap(Reference::getSourceDefinedSymbol).stream().map(referenceIndex::getReferencesTo).flatMap(Collection::stream).collect(groupingBy(Reference::getFrom, mapping(Reference::getSelectionRange, toCollection(ArrayList::new)))).entrySet().stream().map(entry -> new CallHierarchyIncomingCall(getCallHierarchyItem(entry.getKey()), entry.getValue())).collect(Collectors.toList());
}
Also used : ReferenceResolver(com.github._1c_syntax.bsl.languageserver.references.ReferenceResolver) Collection(java.util.Collection) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) MdoRefBuilder(com.github._1c_syntax.bsl.languageserver.utils.MdoRefBuilder) DocumentContext(com.github._1c_syntax.bsl.languageserver.context.DocumentContext) SourceDefinedSymbol(com.github._1c_syntax.bsl.languageserver.context.symbol.SourceDefinedSymbol) Collectors(java.util.stream.Collectors) CallHierarchyItem(org.eclipse.lsp4j.CallHierarchyItem) ArrayList(java.util.ArrayList) Reference(com.github._1c_syntax.bsl.languageserver.references.Reference) CallHierarchyIncomingCall(org.eclipse.lsp4j.CallHierarchyIncomingCall) ReferenceIndex(com.github._1c_syntax.bsl.languageserver.references.ReferenceIndex) Collectors.toCollection(java.util.stream.Collectors.toCollection) Component(org.springframework.stereotype.Component) List(java.util.List) CallHierarchyOutgoingCallsParams(org.eclipse.lsp4j.CallHierarchyOutgoingCallsParams) CallHierarchyOutgoingCall(org.eclipse.lsp4j.CallHierarchyOutgoingCall) Collectors.mapping(java.util.stream.Collectors.mapping) Position(org.eclipse.lsp4j.Position) URI(java.net.URI) CallHierarchyIncomingCallsParams(org.eclipse.lsp4j.CallHierarchyIncomingCallsParams) CallHierarchyPrepareParams(org.eclipse.lsp4j.CallHierarchyPrepareParams) Collections(java.util.Collections) CallHierarchyIncomingCall(org.eclipse.lsp4j.CallHierarchyIncomingCall) Position(org.eclipse.lsp4j.Position) Reference(com.github._1c_syntax.bsl.languageserver.references.Reference) CallHierarchyItem(org.eclipse.lsp4j.CallHierarchyItem) URI(java.net.URI)

Example 7 with DocumentContext

use of com.github._1c_syntax.bsl.languageserver.context.DocumentContext in project bsl-language-server by 1c-syntax.

the class TypoDiagnostic method check.

@Override
protected void check() {
    String lang = info.getResourceString("diagnosticLanguage");
    Map<String, Boolean> checkedWordsForLang = checkedWords.get(lang);
    Map<String, List<Token>> tokensMap = getTokensMap(documentContext);
    // build string of unchecked words
    Set<String> uncheckedWords = tokensMap.keySet().stream().filter(word -> !checkedWordsForLang.containsKey(word)).collect(Collectors.toSet());
    if (uncheckedWords.isEmpty()) {
        fireDiagnosticOnCheckedWordsWithErrors(tokensMap);
        return;
    }
    // Join with double \n to force LT make paragraph after each word.
    // Otherwise results may be flaky cause of sort order of words in file.
    String uncheckedWordsString = String.join("\n\n", uncheckedWords);
    JLanguageTool languageTool = acquireLanguageTool(lang);
    List<RuleMatch> matches = Collections.emptyList();
    try {
        matches = languageTool.check(uncheckedWordsString, true, JLanguageTool.ParagraphHandling.ONLYNONPARA);
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    } finally {
        releaseLanguageTool(lang, languageTool);
    }
    // check words and mark matched as checked
    matches.stream().map(ruleMatch -> ruleMatch.getSentence().getTokens()[1].getToken()).forEach(word -> checkedWordsForLang.put(word, true));
    // mark unmatched words without errors as checked
    uncheckedWords.forEach(word -> checkedWordsForLang.putIfAbsent(word, false));
    fireDiagnosticOnCheckedWordsWithErrors(tokensMap);
}
Also used : Arrays(java.util.Arrays) Getter(lombok.Getter) Token(org.antlr.v4.runtime.Token) HashMap(java.util.HashMap) DocumentContext(com.github._1c_syntax.bsl.languageserver.context.DocumentContext) JLanguageTool(org.languagetool.JLanguageTool) DiagnosticTag(com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) DiagnosticSeverity(com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity) DiagnosticMetadata(com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata) AccessLevel(lombok.AccessLevel) Map(java.util.Map) BSLParserRuleContext(com.github._1c_syntax.bsl.parser.BSLParserRuleContext) DiagnosticParameter(com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticParameter) AmericanEnglish(org.languagetool.language.AmericanEnglish) Predicate(java.util.function.Predicate) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) RuleMatch(org.languagetool.rules.RuleMatch) Set(java.util.Set) BSLParser(com.github._1c_syntax.bsl.parser.BSLParser) IOException(java.io.IOException) DiagnosticType(com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType) Collectors(java.util.stream.Collectors) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) JLanguageToolPool(com.github._1c_syntax.bsl.languageserver.diagnostics.typo.JLanguageToolPool) Pattern(java.util.regex.Pattern) Trees(com.github._1c_syntax.bsl.languageserver.utils.Trees) CaseInsensitivePattern(com.github._1c_syntax.utils.CaseInsensitivePattern) Collections(java.util.Collections) Russian(org.languagetool.language.Russian) RuleMatch(org.languagetool.rules.RuleMatch) JLanguageTool(org.languagetool.JLanguageTool) ArrayList(java.util.ArrayList) List(java.util.List) IOException(java.io.IOException)

Example 8 with DocumentContext

use of com.github._1c_syntax.bsl.languageserver.context.DocumentContext in project bsl-language-server by 1c-syntax.

the class InvalidCharacterInFileDiagnostic method getQuickFixes.

@Override
public List<CodeAction> getQuickFixes(List<Diagnostic> diagnostics, CodeActionParams params, DocumentContext documentContext) {
    List<TextEdit> textEdits = new ArrayList<>();
    diagnostics.stream().filter(diagnostic -> diagnostic.getMessage().equals(diagnosticMessageSpace)).forEach((Diagnostic diagnostic) -> {
        Range range = diagnostic.getRange();
        TextEdit textEdit = new TextEdit(range, ILLEGAL_SPACE_PATTERN.matcher(documentContext.getText(range)).replaceAll(" "));
        textEdits.add(textEdit);
    });
    diagnostics.stream().filter(diagnostic -> diagnostic.getMessage().equals(diagnosticMessageDash)).forEach((Diagnostic diagnostic) -> {
        Range range = diagnostic.getRange();
        TextEdit textEdit = new TextEdit(range, ILLEGAL_PATTERN.matcher(documentContext.getText(range)).replaceAll("-"));
        textEdits.add(textEdit);
    });
    return CodeActionProvider.createCodeActions(textEdits, info.getResourceString("quickFixMessage"), documentContext.getUri(), diagnostics);
}
Also used : CodeAction(org.eclipse.lsp4j.CodeAction) CodeActionProvider(com.github._1c_syntax.bsl.languageserver.providers.CodeActionProvider) BSLLexer(com.github._1c_syntax.bsl.parser.BSLLexer) Token(org.antlr.v4.runtime.Token) Diagnostic(org.eclipse.lsp4j.Diagnostic) Range(org.eclipse.lsp4j.Range) DiagnosticType(com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType) DocumentContext(com.github._1c_syntax.bsl.languageserver.context.DocumentContext) DiagnosticTag(com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag) ArrayList(java.util.ArrayList) Lexer(org.antlr.v4.runtime.Lexer) DiagnosticSeverity(com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity) CodeActionParams(org.eclipse.lsp4j.CodeActionParams) List(java.util.List) DiagnosticMetadata(com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata) TextEdit(org.eclipse.lsp4j.TextEdit) PostConstruct(javax.annotation.PostConstruct) Pattern(java.util.regex.Pattern) TextEdit(org.eclipse.lsp4j.TextEdit) ArrayList(java.util.ArrayList) Diagnostic(org.eclipse.lsp4j.Diagnostic) Range(org.eclipse.lsp4j.Range)

Example 9 with DocumentContext

use of com.github._1c_syntax.bsl.languageserver.context.DocumentContext in project bsl-language-server by 1c-syntax.

the class MethodSymbolMarkupContentBuilderTest method testContentFromDirectFile.

@Test
void testContentFromDirectFile() {
    // given
    DocumentContext documentContext = TestUtils.getDocumentContextFromFile(PATH_TO_FILE);
    var methodSymbol = documentContext.getSymbolTree().getMethodSymbol("ИмяФункции").orElseThrow();
    // when
    var content = markupContentBuilder.getContent(methodSymbol).getValue();
    assertThat(content).isNotEmpty();
    var blocks = Arrays.asList(content.split("---\n?"));
    assertThat(blocks).hasSize(5);
    assertThat(blocks.get(0)).isEqualTo("```bsl\n" + "Функция ИмяФункции(Знач П1: Дата | Число, П2: Число = -10, П2_5, Знач П3: Структура = \"\", " + "П4: Массив | СписокЗначений, ПДата: См. ОбщийМодуль.СуперМетод() = '20100101', ПДатаВремя = '20110101121212', " + "П6 = Ложь, П7 = Истина, П8 = Неопределено, П9 = NULL) Экспорт: Строка | Структура\n```\n\n");
    assertThat(blocks.get(1)).matches("Метод из file://.*/src/test/resources/hover/methodSymbolMarkupContentBuilder.bsl\n\n");
    assertThat(blocks.get(2)).isEqualTo("Описание функции.\nМногострочное.\n\n");
    assertThat(blocks.get(3)).isEqualTo("**Параметры:**\n\n" + "* **П1**: `Дата` | `Число` - Описание даты/числа  \n" + "* **П2**: `Число` - Описание числа  \n" + "* **П2_5**:   \n" + "* **П3**: `Структура` - Описание строки<br>&nbsp;&nbsp;продолжается на следующей строкке:  \n" + "  * **Поле1**: `Число` - Описание поле1  \n" + "  * **Поле2**: `Строка` - Описание поле2  \n" + "  * **Поле3**: `Структура` :  \n" + "    * **Поле31**: `строка`  \n" + "    * **Поле32**: `Структура` :  \n" + "      * **Поле321**: `Число` - Описание поля 321  \n" + "    * **Поле33**: `строка`  \n" + "  * **Поле4**: `строка`  \n" + "* **П4**:   \n" + "&nbsp;&nbsp;`Массив` - Описание Массива  \n" + "&nbsp;&nbsp;`СписокЗначений` - Описание списка  \n" + "* **ПДата**: [См. ОбщийМодуль.СуперМетод()](ОбщийМодуль.СуперМетод())  \n" + "* **ПДатаВремя**:   \n" + "* **П6**:   \n" + "* **П7**:   \n" + "* **П8**:   \n" + "* **П9**: \n" + "\n");
    assertThat(blocks.get(4)).isEqualTo("**Возвращаемое значение:**\n\n" + "&nbsp;&nbsp;`Строка` - вернувшаяся строка  \n" + "&nbsp;&nbsp;`Структура` - Описание строки<br>&nbsp;&nbsp;продолжается на следующей строкке:  \n" + "  * **Поле1**: `Число` - Описание поле1  \n" + "  * **Поле2**: `Строка` - Описание поле2  \n" + "  * **Поле3**: `Структура` :  \n" + "    * **Поле31**: `строка`  \n" + "    * **Поле32**: `Структура`\n\n");
}
Also used : DocumentContext(com.github._1c_syntax.bsl.languageserver.context.DocumentContext) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 10 with DocumentContext

use of com.github._1c_syntax.bsl.languageserver.context.DocumentContext in project bsl-language-server by 1c-syntax.

the class VariableSymbolMarkupContentBuilderTest method testMethodVarContentFromDirectFile_2_comments_strings.

@Test
void testMethodVarContentFromDirectFile_2_comments_strings() {
    // given
    DocumentContext documentContext = TestUtils.getDocumentContextFromFile(PATH_TO_FILE);
    final var symbolTree = documentContext.getSymbolTree();
    var methodSymbol = symbolTree.getMethodSymbol("ИмяФункции").orElseThrow();
    var varSymbol = symbolTree.getVariableSymbol("Имя_ОписаниеСверхуДвеСтроки_Функция", methodSymbol).orElseThrow();
    // when
    var content = markupContentBuilder.getContent(varSymbol).getValue();
    assertThat(content).isNotEmpty();
    var blocks = Arrays.asList(content.split("---\n?"));
    assertThat(blocks).hasSize(3);
    assertThat(blocks.get(0)).isEqualTo("```bsl\n" + "Перем Имя_ОписаниеСверхуДвеСтроки_Функция\n" + "```\n" + "\n");
    assertThat(blocks.get(1)).matches("Переменная из file://.*/src/test/resources/hover/variableSymbolMarkupContentBuilder.bsl.ИмяФункции\n" + "\n");
    // TODO баг - нет \n для многострочного описания переменной
    assertThat(blocks.get(2)).matches("описание 1 строка\n2 строка\n" + "\n");
}
Also used : DocumentContext(com.github._1c_syntax.bsl.languageserver.context.DocumentContext) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Aggregations

DocumentContext (com.github._1c_syntax.bsl.languageserver.context.DocumentContext)86 Test (org.junit.jupiter.api.Test)69 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)57 Diagnostic (org.eclipse.lsp4j.Diagnostic)36 List (java.util.List)22 Position (org.eclipse.lsp4j.Position)21 SneakyThrows (lombok.SneakyThrows)17 Path (java.nio.file.Path)16 CodeAction (org.eclipse.lsp4j.CodeAction)16 TestUtils (com.github._1c_syntax.bsl.languageserver.util.TestUtils)15 Autowired (org.springframework.beans.factory.annotation.Autowired)15 Collectors (java.util.stream.Collectors)14 Range (org.eclipse.lsp4j.Range)13 ArrayList (java.util.ArrayList)12 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)12 CodeActionParams (org.eclipse.lsp4j.CodeActionParams)12 TextDocumentIdentifier (org.eclipse.lsp4j.TextDocumentIdentifier)12 LanguageServerConfiguration (com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration)11 MethodSymbol (com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol)10 MDCommonModule (com.github._1c_syntax.mdclasses.mdo.MDCommonModule)10