From 27d3059416eb084c42f794bc43d83e69b3da3524 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Tue, 31 Mar 2020 21:52:22 +0300 Subject: [PATCH 001/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D0=B8=D0=BD=D1=84=D0=BE=D1=80=D0=BC=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D1=8F=20=D0=BE=20=D0=BF=D0=B0=D1=80=D0=B0=D0=BC?= =?UTF-8?q?=D0=B5=D1=82=D1=80=D0=B0=D1=85=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../computer/MethodSymbolComputer.java | 49 ++++++++++++++++--- .../context/symbol/MethodSymbol.java | 3 ++ .../context/symbol/ParameterDefinition.java | 37 ++++++++++++++ .../context/DocumentContextTest.java | 33 ++++++++++++- .../resources/context/DocumentContextTest.bsl | 4 ++ 5 files changed, 119 insertions(+), 7 deletions(-) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/ParameterDefinition.java diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java index b9089d3b377..60bb704c81b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java @@ -24,6 +24,7 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodDescription; import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.ParameterDefinition; 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.BSLParser; @@ -34,8 +35,10 @@ import org.antlr.v4.runtime.tree.TerminalNode; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Optional; +import java.util.stream.Collectors; public final class MethodSymbolComputer extends BSLParserBaseVisitor @@ -70,14 +73,30 @@ public ParseTree visitFunction(BSLParser.FunctionContext ctx) { return ctx; } - MethodSymbol methodSymbol = MethodSymbol.builder() + MethodSymbol.MethodSymbolBuilder builder = MethodSymbol.builder() .name(declaration.subName().getText()) .range(Ranges.create(startNode, stopNode)) .subNameRange(Ranges.create(declaration.subName())) .function(true) .export(declaration.EXPORT_KEYWORD() != null) - .description(createDescription(startNode.getSymbol())) - .build(); + .description(createDescription(startNode.getSymbol())); + + List parameters = Optional.ofNullable(declaration.paramList()) + .map(paramList -> paramList.param().stream() + .filter(param -> param.IDENTIFIER() != null) + .map(param -> + ParameterDefinition.builder() + .name(param.IDENTIFIER().getText()) + .byValue(param.VAL_KEYWORD() != null) + .optional(param.defaultValue() != null) + .build() + ).collect(Collectors.toList()) + ) + .orElseGet(Collections::emptyList); + + builder.parameters(parameters); + + MethodSymbol methodSymbol = builder.build(); methods.add(methodSymbol); @@ -99,14 +118,32 @@ public ParseTree visitProcedure(BSLParser.ProcedureContext ctx) { return ctx; } - MethodSymbol methodSymbol = MethodSymbol.builder() + MethodSymbol.MethodSymbolBuilder builder = MethodSymbol.builder() .name(declaration.subName().getText()) .range(Ranges.create(startNode, stopNode)) .subNameRange(Ranges.create(declaration.subName())) .function(false) .export(declaration.EXPORT_KEYWORD() != null) - .description(createDescription(startNode.getSymbol())) - .build(); + .description(createDescription(startNode.getSymbol())); + + List parameters = Optional.ofNullable(declaration.paramList()) + .map(paramList -> paramList.param().stream() + .filter(param -> param.IDENTIFIER() != null) + .map(param -> + ParameterDefinition.builder() + .name(param + .IDENTIFIER() + .getText()) + .byValue(param.VAL_KEYWORD() != null) + .optional(param.defaultValue() != null) + .build() + ).collect(Collectors.toList()) + ) + .orElseGet(Collections::emptyList); + + builder.parameters(parameters); + + MethodSymbol methodSymbol = builder.build(); methods.add(methodSymbol); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java index 676ca369fb7..337583fadaa 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java @@ -57,6 +57,9 @@ public class MethodSymbol implements Symbol { boolean export; Optional description; + @Builder.Default + List parameters = new ArrayList<>(); + public Optional getRegion() { return getParent() .filter(symbol -> symbol instanceof RegionSymbol) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/ParameterDefinition.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/ParameterDefinition.java new file mode 100644 index 00000000000..7da5671b7b5 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/ParameterDefinition.java @@ -0,0 +1,37 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.context.symbol; + +import lombok.Builder; +import lombok.Value; + +/** + * Класс хранит информацию о параметре метода. + * См. {@link MethodSymbol} + */ +@Value +@Builder +public class ParameterDefinition { + String name; + boolean byValue; + boolean optional; +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java index 7f8e516573c..bae3d5373f8 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java @@ -69,7 +69,38 @@ void testMethodCompute() { DocumentContext documentContext = getDocumentContext(); - assertThat(documentContext.getSymbolTree().getMethods().size()).isEqualTo(2); + assertThat(documentContext.getSymbolTree().getMethods().size()).isEqualTo(3); + + } + + @Test + void testMethodParametersComputesCorrectly() { + DocumentContext documentContext = getDocumentContext(); + assertThat(documentContext.getSymbolTree().getMethods()) + .filteredOn(methodSymbol -> methodSymbol.getName().equals("ФункцияСПараметрами")) + .flatExtracting(MethodSymbol::getParameters) + .hasSize(4) + .anyMatch(parameterDefinition -> + parameterDefinition.getName().equals("Парам1") + && !parameterDefinition.isByValue() + && !parameterDefinition.isOptional() + ) + .anyMatch(parameterDefinition -> + parameterDefinition.getName().equals("Парам2") + && parameterDefinition.isByValue() + && !parameterDefinition.isOptional() + ) + .anyMatch(parameterDefinition -> + parameterDefinition.getName().equals("Парам3") + && !parameterDefinition.isByValue() + && parameterDefinition.isOptional() + ) + .anyMatch(parameterDefinition -> + parameterDefinition.getName().equals("Парам4") + && parameterDefinition.isByValue() + && parameterDefinition.isOptional() + ) + ; } diff --git a/src/test/resources/context/DocumentContextTest.bsl b/src/test/resources/context/DocumentContextTest.bsl index 1bfe22fbe76..f6c9e8f83e5 100644 --- a/src/test/resources/context/DocumentContextTest.bsl +++ b/src/test/resources/context/DocumentContextTest.bsl @@ -30,3 +30,7 @@ #КонецОбласти #КонецОбласти + +Функция ФункцияСПараметрами(Парам1, Знач Парам2, Парам3 = 0, Знач Парам4 = 0) + +КонецФункции From f1f311ab2154622703aa0baad00a67c6b5d55fbd Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Wed, 1 Apr 2020 13:04:19 +0300 Subject: [PATCH 002/444] Fix QF --- .../computer/MethodSymbolComputer.java | 106 +++++++++--------- 1 file changed, 56 insertions(+), 50 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java index 60bb704c81b..73f5ccab7a1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java @@ -34,6 +34,7 @@ import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -73,30 +74,14 @@ public ParseTree visitFunction(BSLParser.FunctionContext ctx) { return ctx; } - MethodSymbol.MethodSymbolBuilder builder = MethodSymbol.builder() - .name(declaration.subName().getText()) - .range(Ranges.create(startNode, stopNode)) - .subNameRange(Ranges.create(declaration.subName())) - .function(true) - .export(declaration.EXPORT_KEYWORD() != null) - .description(createDescription(startNode.getSymbol())); - - List parameters = Optional.ofNullable(declaration.paramList()) - .map(paramList -> paramList.param().stream() - .filter(param -> param.IDENTIFIER() != null) - .map(param -> - ParameterDefinition.builder() - .name(param.IDENTIFIER().getText()) - .byValue(param.VAL_KEYWORD() != null) - .optional(param.defaultValue() != null) - .build() - ).collect(Collectors.toList()) - ) - .orElseGet(Collections::emptyList); - - builder.parameters(parameters); - - MethodSymbol methodSymbol = builder.build(); + MethodSymbol methodSymbol = createMethodSymbol( + startNode, + stopNode, + declaration.subName(), + declaration.paramList(), + true, + declaration.EXPORT_KEYWORD() != null + ); methods.add(methodSymbol); @@ -118,38 +103,39 @@ public ParseTree visitProcedure(BSLParser.ProcedureContext ctx) { return ctx; } - MethodSymbol.MethodSymbolBuilder builder = MethodSymbol.builder() - .name(declaration.subName().getText()) - .range(Ranges.create(startNode, stopNode)) - .subNameRange(Ranges.create(declaration.subName())) - .function(false) - .export(declaration.EXPORT_KEYWORD() != null) - .description(createDescription(startNode.getSymbol())); - - List parameters = Optional.ofNullable(declaration.paramList()) - .map(paramList -> paramList.param().stream() - .filter(param -> param.IDENTIFIER() != null) - .map(param -> - ParameterDefinition.builder() - .name(param - .IDENTIFIER() - .getText()) - .byValue(param.VAL_KEYWORD() != null) - .optional(param.defaultValue() != null) - .build() - ).collect(Collectors.toList()) - ) - .orElseGet(Collections::emptyList); - - builder.parameters(parameters); - - MethodSymbol methodSymbol = builder.build(); + MethodSymbol methodSymbol = createMethodSymbol( + startNode, + stopNode, + declaration.subName(), + declaration.paramList(), + false, + declaration.EXPORT_KEYWORD() != null + ); methods.add(methodSymbol); return ctx; } + private MethodSymbol createMethodSymbol( + TerminalNode startNode, + TerminalNode stopNode, + BSLParser.SubNameContext subName, + BSLParser.ParamListContext paramList, + boolean function, + boolean export + ) { + return MethodSymbol.builder() + .name(subName.getText()) + .range(Ranges.create(startNode, stopNode)) + .subNameRange(Ranges.create(subName)) + .function(function) + .export(export) + .description(createDescription(startNode.getSymbol())) + .parameters(createParameters(paramList)) + .build(); + } + private Optional createDescription(Token token) { List comments = Trees.getComments(documentContext.getTokens(), token); if (comments.isEmpty()) { @@ -159,4 +145,24 @@ private Optional createDescription(Token token) { return Optional.of(new MethodDescription(comments)); } + private static List createParameters(@Nullable BSLParser.ParamListContext paramList) { + if (paramList == null) { + return Collections.emptyList(); + } + + return paramList.param().stream() + .map(param -> + ParameterDefinition.builder() + .name(getParameterName(param.IDENTIFIER())) + .byValue(param.VAL_KEYWORD() != null) + .optional(param.defaultValue() != null) + .build() + ).collect(Collectors.toList()); + } + + private static String getParameterName(TerminalNode identifier) { + return Optional.ofNullable(identifier) + .map(ParseTree::getText) + .orElse(""); + } } From 936b52d4133909233a3c70769a1748782db03bac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BD=D1=82=D0=BE=D0=BD=20=D0=A1=D1=82=D0=B5=D0=BF?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Wed, 8 Apr 2020 09:02:34 +0300 Subject: [PATCH 003/444] =?UTF-8?q?=D0=98=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D1=8F=20=D0=BF=D0=BE=D0=B4=20mkdocs=20material=205?= =?UTF-8?q?.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mkdocs.en.yml | 12 ++++++++---- mkdocs.yml | 12 ++++++++---- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/mkdocs.en.yml b/mkdocs.en.yml index 5b577871237..fc4e2eaee09 100644 --- a/mkdocs.en.yml +++ b/mkdocs.en.yml @@ -15,12 +15,10 @@ theme: primary: 'white' accent: 'indigo' extra: - search: - language: 'en, ru' social: - - type: 'github' + - icon: fontawesome/brands/github link: 'https://github.com/1c-syntax' - - type: 'telegram' + - icon: fontawesome/brands/telegram link: 'https://t.me/bsl_language_server' extra_css: - 'assets/stylesheets/extra.css' @@ -30,6 +28,12 @@ markdown_extensions: - toc: permalink: Link +plugins: + - search: + lang: + - en + - ru + site_url: 'https://1c-syntax.github.io/bsl-language-server' repo_name: '1c-syntax/bsl-language-server' repo_url: 'https://github.com/1c-syntax/bsl-language-server' diff --git a/mkdocs.yml b/mkdocs.yml index 40bda54d463..c418be1157b 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -15,12 +15,10 @@ theme: primary: 'white' accent: 'indigo' extra: - search: - language: 'en, ru' social: - - type: 'github' + - icon: fontawesome/brands/github link: 'https://github.com/1c-syntax' - - type: 'telegram' + - icon: fontawesome/brands/telegram link: 'https://t.me/bsl_language_server' extra_css: - 'assets/stylesheets/extra.css' @@ -30,6 +28,12 @@ markdown_extensions: - toc: permalink: true +plugins: + - search: + lang: + - en + - ru + site_url: 'https://1c-syntax.github.io/bsl-language-server' repo_name: '1c-syntax/bsl-language-server' repo_url: 'https://github.com/1c-syntax/bsl-language-server' From fe5b2aa9d1711b1d70d5663702beff74cbb0ea7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BD=D1=82=D0=BE=D0=BD=20=D0=A1=D1=82=D0=B5=D0=BF?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Wed, 8 Apr 2020 09:27:44 +0300 Subject: [PATCH 004/444] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D1=83=D0=B5=D1=85=D0=B0=D0=B2=D1=88=D0=B5=D0=B5?= =?UTF-8?q?=20=D1=81=D0=BE=D0=B4=D0=B5=D1=80=D0=B6=D0=B0=D0=BD=D0=B8=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/assets/stylesheets/extra.css | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/docs/assets/stylesheets/extra.css b/docs/assets/stylesheets/extra.css index 8b4682f140c..ac4d06e2db3 100644 --- a/docs/assets/stylesheets/extra.css +++ b/docs/assets/stylesheets/extra.css @@ -1,19 +1,22 @@ .md-content { - margin-right: 0; + margin-right: 0; } + .md-sidebar--secondary { - margin-top: 220px; - margin-left: 12.1rem; + margin-top: 220px; + margin-left: 0.5rem; } + .md-typeset__table { - padding: 0; + padding: 0; } + .md-typeset table:not([class]) { - font-size: .54rem; + font-size: .54rem; } @media only screen and (min-width:59.9375em) and (max-width:80em) { - .md-sidebar--secondary { - display: none; - } -} + .md-sidebar--secondary { + display: none; + } +} \ No newline at end of file From 2835d9859d2eb73d59c7749a47de98327847bf8d Mon Sep 17 00:00:00 2001 From: Oleg Tymko Date: Wed, 8 Apr 2020 14:24:58 +0700 Subject: [PATCH 005/444] Update extra.css --- docs/assets/stylesheets/extra.css | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/assets/stylesheets/extra.css b/docs/assets/stylesheets/extra.css index ac4d06e2db3..c4ae4fa2c89 100644 --- a/docs/assets/stylesheets/extra.css +++ b/docs/assets/stylesheets/extra.css @@ -7,6 +7,11 @@ margin-left: 0.5rem; } +/* для отступа заголовка "Содержание" */ +.md-sidebar--secondary .md-nav__title { + padding-left: 0px; +} + .md-typeset__table { padding: 0; } @@ -19,4 +24,4 @@ .md-sidebar--secondary { display: none; } -} \ No newline at end of file +} From 03b0563b6456756d8f6cedae3e3fe1c87b8c1247 Mon Sep 17 00:00:00 2001 From: Aleksandr Ponkratov Date: Thu, 9 Apr 2020 15:31:47 +0300 Subject: [PATCH 006/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D0=BD=D0=BE=D0=B2=D0=B0=D1=8F=20=D0=B4?= =?UTF-8?q?=D0=B8=D0=B0=D0=B3=D0=BD=D0=BE=D1=81=D1=82=D0=B8=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/DeprecatedCurrentDate.md | 50 ++++++++++ docs/diagnostics/index.md | 5 +- docs/en/diagnostics/DeprecatedCurrentDate.md | 52 +++++++++++ docs/en/diagnostics/index.md | 5 +- .../DeprecatedCurrentDateDiagnostic.java | 91 +++++++++++++++++++ .../configuration/diagnostics-schema.json | 10 ++ .../languageserver/configuration/schema.json | 3 + ...recatedCurrentDateDiagnostic_en.properties | 4 + ...recatedCurrentDateDiagnostic_ru.properties | 4 + .../DeprecatedCurrentDateDiagnosticTest.java | 75 +++++++++++++++ .../DeprecatedCurrentDateDiagnostic.bsl | 13 +++ 11 files changed, 308 insertions(+), 4 deletions(-) create mode 100644 docs/diagnostics/DeprecatedCurrentDate.md create mode 100644 docs/en/diagnostics/DeprecatedCurrentDate.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/DeprecatedCurrentDateDiagnostic.bsl diff --git a/docs/diagnostics/DeprecatedCurrentDate.md b/docs/diagnostics/DeprecatedCurrentDate.md new file mode 100644 index 00000000000..8f6ebe8ab83 --- /dev/null +++ b/docs/diagnostics/DeprecatedCurrentDate.md @@ -0,0 +1,50 @@ +# Использование устаревшего метода "ТекущаяДата" (DeprecatedCurrentDate) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Ошибка` | `BSL` | `Важный` | `Да` | `1` | `standard`
`badpractice`
`unpredictable` | + + +## Описание диагностики + +Функция "ТекущаяДата" является устаревшей. Рекомендуется использовать функцию "ТекущаяДатаСеанса". + +## Примеры +Неправильно: + +```bsl +ДатаОперации = ТекущаяДата(); +``` + + +Правильно: + +```bsl +ДатаОперации = ТекущаяДатаСеанса(); +``` + +## Источники + + + +* Источник: [Создание и изменение объектов метаданных. Работа в разных часовых поясах](https://its.1c.ru/db/v8std/content/643/hdoc) + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:DeprecatedCurrentDate-off +// BSLLS:DeprecatedCurrentDate-on +``` + +### Параметр конфигурационного файла + +```json +"DeprecatedCurrentDate": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 573e91bbc65..714322ae9c1 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,11 +8,11 @@ ## Список реализованных диагностик -Общее количество: **85** +Общее количество: **86** * Дефект кода: **54** * Уязвимость: **2** -* Ошибка: **27** +* Ошибка: **28** * Потенциальная уязвимость: **2** | Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги | @@ -29,6 +29,7 @@ | [CreateQueryInCycle](CreateQueryInCycle.md) | Выполнение запроса в цикле | Да | Критичный | Ошибка | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Цикломатическая сложность | Да | Критичный | Дефект кода | `brainoverload` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Удаление элемента при обходе коллекции посредством оператора "Для каждого ... Из ... Цикл" | Да | Важный | Ошибка | `standard`
`error` | +| [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Использование устаревшего метода "ТекущаяДата" | Да | Важный | Ошибка | `standard`
`badpractice`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Использование устаревшего метода "Найти" | Да | Незначительный | Дефект кода | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Ограничение на использование устаревшего метода "Сообщить" | Да | Незначительный | Дефект кода | `standard`
`deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Устаревшее использование типа "УправляемаяФорма" | Да | Информационный | Дефект кода | `standard`
`deprecated` | diff --git a/docs/en/diagnostics/DeprecatedCurrentDate.md b/docs/en/diagnostics/DeprecatedCurrentDate.md new file mode 100644 index 00000000000..b1c426815ad --- /dev/null +++ b/docs/en/diagnostics/DeprecatedCurrentDate.md @@ -0,0 +1,52 @@ +# Using of the deprecated method "CurrentDate" (DeprecatedCurrentDate) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Error` | `BSL` | `Major` | `Yes` | `1` | `standard`
`badpractice`
`unpredictable` | + + +## Description + +Method "CurrentDate" is deprecated. Use "CurrentSessionDate" instead. + +## Examples + + +Incorrect: + +```bsl +OperationDate = CurrentDate(); +``` + + +Correct: + +```bsl +OperationDate = CurrentSessionDate(); +``` + +## Sources + + + +* Reference: [Metadata creation and change. Work in different timezones](https://its.1c.ru/db/v8std/content/643/hdoc) + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:DeprecatedCurrentDate-off +// BSLLS:DeprecatedCurrentDate-on +``` + +### Parameter for config + +```json +"DeprecatedCurrentDate": false +``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 1a93fcbc2b8..53c9f527dee 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,9 +8,9 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **85** +Total: **86** -* Error: **27** +* Error: **28** * Code smell: **54** * Vulnerability: **2** * Security Hotspot: **2** @@ -29,6 +29,7 @@ Total: **85** | [CreateQueryInCycle](CreateQueryInCycle.md) | Execution query on cycle | Yes | Critical | Error | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Cyclomatic complexity | Yes | Critical | Code smell | `brainoverload` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Deleting an item when iterating through collection using the operator "For each ... In ... Do" | Yes | Major | Error | `standard`
`error` | +| [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Using of the deprecated method "CurrentDate" | Yes | Major | Error | `standard`
`badpractice`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Using of the deprecated method "Find" | Yes | Minor | Code smell | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Restriction on the use of deprecated "Message" method | Yes | Minor | Code smell | `standard`
`deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Deprecated ManagedForm type | Yes | Info | Code smell | `standard`
`deprecated` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic.java new file mode 100644 index 00000000000..0da8ef09873 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic.java @@ -0,0 +1,91 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.providers.CodeActionProvider; +import com.github._1c_syntax.bsl.parser.BSLParser; +import org.eclipse.lsp4j.CodeAction; +import org.eclipse.lsp4j.CodeActionParams; +import org.eclipse.lsp4j.Diagnostic; +import org.eclipse.lsp4j.TextEdit; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.ERROR, + severity = DiagnosticSeverity.MAJOR, + scope = DiagnosticScope.BSL, + minutesToFix = 1, + tags = { + DiagnosticTag.STANDARD, + DiagnosticTag.BADPRACTICE, + DiagnosticTag.UNPREDICTABLE + } + +) +public class DeprecatedCurrentDateDiagnostic extends AbstractFindMethodDiagnostic implements QuickFixProvider { + private static final Pattern currentDatePattern = Pattern.compile( + "(текущаядата|currentdate)", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE + ); + + public DeprecatedCurrentDateDiagnostic(DiagnosticInfo info) { + super(info, currentDatePattern); + } + + @Override + protected boolean checkMethodCall(BSLParser.MethodCallContext ctx) { + return false; + } + + @Override + public List getQuickFixes( + List diagnostics, + CodeActionParams params, + DocumentContext documentContext + ) { + + List textEdits = new ArrayList<>(); + + diagnostics.forEach((Diagnostic diagnostic) -> { + TextEdit textEdit = new TextEdit(diagnostic.getRange(), info.getResourceString("changeFix")); + textEdits.add(textEdit); + }); + + return CodeActionProvider.createCodeActions( + textEdits, + info.getResourceString("quickFixMessage"), + documentContext.getUri(), + diagnostics + ); + } + +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json index eb14827c367..3dc40d9cd0a 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json @@ -160,6 +160,16 @@ "title": "Deleting an item when iterating through collection using the operator \"For each ... In ... Do\"", "$id": "#/definitions/DeletingCollectionItem" }, + "DeprecatedCurrentDate": { + "description": "Using of the deprecated method \"CurrentDate\"", + "default": null, + "type": [ + "boolean", + "object" + ], + "title": "Using of the deprecated method \"CurrentDate\"", + "$id": "#/definitions/DeprecatedCurrentDate" + }, "DeprecatedFind": { "description": "Using of the deprecated method \"Find\"", "default": null, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 3509853659b..b714b7bc2f0 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -137,6 +137,9 @@ "DeletingCollectionItem": { "$ref": "diagnostics-schema.json#/definitions/DeletingCollectionItem" }, + "DeprecatedCurrentDate": { + "$ref": "diagnostics-schema.json#/definitions/DeprecatedCurrentDate" + }, "DeprecatedFind": { "$ref": "diagnostics-schema.json#/definitions/DeprecatedFind" }, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic_en.properties new file mode 100644 index 00000000000..2c0494f5763 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic_en.properties @@ -0,0 +1,4 @@ +changeFix=CurrentSessionDate +diagnosticMessage=Use "CurrentSessionDate" instead of deprecated "CurrentDate" +diagnosticName=Using of the deprecated method "CurrentDate" +quickFixMessage=Replace to CurrentSessionDate diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic_ru.properties new file mode 100644 index 00000000000..72a7ece2ec4 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic_ru.properties @@ -0,0 +1,4 @@ +changeFix=ТекущаяДатаСеанса +diagnosticMessage=Используйте "ТекущаяДатаСеанса" вместо устаревшего "ТекущаяДата" +diagnosticName=Использование устаревшего метода "ТекущаяДата" +quickFixMessage=Заменить на "ТекущаяДатаСеанса" diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnosticTest.java new file mode 100644 index 00000000000..7c061bfb8ee --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnosticTest.java @@ -0,0 +1,75 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import org.eclipse.lsp4j.CodeAction; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class DeprecatedCurrentDateDiagnosticTest extends AbstractDiagnosticTest { + DeprecatedCurrentDateDiagnosticTest() { + super(DeprecatedCurrentDateDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(2); + assertThat(diagnostics, true) + .hasRange(2, 19, 2, 30) + .hasRange(11, 16, 11, 27); + + } + + @Test + void testQuickFixes() { + + final DocumentContext documentContext = getDocumentContext(); + List diagnostics = getDiagnostics(); + final Diagnostic diagnostic = diagnostics.get(0); + final String replacementText = "ТекущаяДатаСеанса"; + + List QuickFixes = getQuickFixes(diagnostic); + assertThat(QuickFixes).hasSize(1); + + final CodeAction quickFix = QuickFixes.get(0); + + assertThat(quickFix) + .of(diagnosticInstance) + .in(documentContext) + .fixes(diagnostic); + + assertThat(quickFix) + .in(documentContext) + .hasChanges(1) + .hasNewText(replacementText); + + } + +} diff --git a/src/test/resources/diagnostics/DeprecatedCurrentDateDiagnostic.bsl b/src/test/resources/diagnostics/DeprecatedCurrentDateDiagnostic.bsl new file mode 100644 index 00000000000..2542499a06b --- /dev/null +++ b/src/test/resources/diagnostics/DeprecatedCurrentDateDiagnostic.bsl @@ -0,0 +1,13 @@ + +Процедура А() + ДатаПроверки = ТекущаяДата(); // Диагностика должна сработать здесь +КонецПроцедуры + +Процедура Б() + ДатаПроверки = ТекущаяДатаСеанса(); + Модуль.ТекущаяДата(); +КонецПроцедуры + +Procedure A() + CheckDate = CurrentDate(); // Диагностика должна сработать здесь +EndProcedure \ No newline at end of file From 4513d90231d2b7b9e1553b15452704ad87e58c77 Mon Sep 17 00:00:00 2001 From: Aleksandr Ponkratov Date: Thu, 9 Apr 2020 16:56:31 +0300 Subject: [PATCH 007/444] =?UTF-8?q?=D0=A3=D0=B1=D1=80=D0=B0=D0=BD=20quickF?= =?UTF-8?q?ix,=20=D0=BE=D0=B1=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=D0=BD?= =?UTF-8?q?=D1=8B=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=87=D0=B0=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/DeprecatedCurrentDate.md | 2 +- docs/diagnostics/index.md | 2 +- docs/en/diagnostics/DeprecatedCurrentDate.md | 2 +- docs/en/diagnostics/index.md | 2 +- .../DeprecatedCurrentDateDiagnostic.java | 28 ++----------------- ...recatedCurrentDateDiagnostic_en.properties | 3 +- ...recatedCurrentDateDiagnostic_ru.properties | 3 +- .../DeprecatedCurrentDateDiagnosticTest.java | 27 ------------------ 8 files changed, 9 insertions(+), 60 deletions(-) diff --git a/docs/diagnostics/DeprecatedCurrentDate.md b/docs/diagnostics/DeprecatedCurrentDate.md index 8f6ebe8ab83..1709042e12b 100644 --- a/docs/diagnostics/DeprecatedCurrentDate.md +++ b/docs/diagnostics/DeprecatedCurrentDate.md @@ -2,7 +2,7 @@ | Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Ошибка` | `BSL` | `Важный` | `Да` | `1` | `standard`
`badpractice`
`unpredictable` | +| `Ошибка` | `BSL` | `Важный` | `Да` | `5` | `standard`
`deprecated`
`unpredictable` | ## Описание диагностики diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 714322ae9c1..1f246c6e30d 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -29,7 +29,7 @@ | [CreateQueryInCycle](CreateQueryInCycle.md) | Выполнение запроса в цикле | Да | Критичный | Ошибка | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Цикломатическая сложность | Да | Критичный | Дефект кода | `brainoverload` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Удаление элемента при обходе коллекции посредством оператора "Для каждого ... Из ... Цикл" | Да | Важный | Ошибка | `standard`
`error` | -| [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Использование устаревшего метода "ТекущаяДата" | Да | Важный | Ошибка | `standard`
`badpractice`
`unpredictable` | +| [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Использование устаревшего метода "ТекущаяДата" | Да | Важный | Ошибка | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Использование устаревшего метода "Найти" | Да | Незначительный | Дефект кода | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Ограничение на использование устаревшего метода "Сообщить" | Да | Незначительный | Дефект кода | `standard`
`deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Устаревшее использование типа "УправляемаяФорма" | Да | Информационный | Дефект кода | `standard`
`deprecated` | diff --git a/docs/en/diagnostics/DeprecatedCurrentDate.md b/docs/en/diagnostics/DeprecatedCurrentDate.md index b1c426815ad..03c282d3862 100644 --- a/docs/en/diagnostics/DeprecatedCurrentDate.md +++ b/docs/en/diagnostics/DeprecatedCurrentDate.md @@ -2,7 +2,7 @@ | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Error` | `BSL` | `Major` | `Yes` | `1` | `standard`
`badpractice`
`unpredictable` | +| `Error` | `BSL` | `Major` | `Yes` | `5` | `standard`
`deprecated`
`unpredictable` | ## Description diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 53c9f527dee..01ff325fefd 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -29,7 +29,7 @@ Total: **86** | [CreateQueryInCycle](CreateQueryInCycle.md) | Execution query on cycle | Yes | Critical | Error | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Cyclomatic complexity | Yes | Critical | Code smell | `brainoverload` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Deleting an item when iterating through collection using the operator "For each ... In ... Do" | Yes | Major | Error | `standard`
`error` | -| [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Using of the deprecated method "CurrentDate" | Yes | Major | Error | `standard`
`badpractice`
`unpredictable` | +| [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Using of the deprecated method "CurrentDate" | Yes | Major | Error | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Using of the deprecated method "Find" | Yes | Minor | Code smell | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Restriction on the use of deprecated "Message" method | Yes | Minor | Code smell | `standard`
`deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Deprecated ManagedForm type | Yes | Info | Code smell | `standard`
`deprecated` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic.java index 0da8ef09873..1695355841f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic.java @@ -43,15 +43,15 @@ type = DiagnosticType.ERROR, severity = DiagnosticSeverity.MAJOR, scope = DiagnosticScope.BSL, - minutesToFix = 1, + minutesToFix = 5, tags = { DiagnosticTag.STANDARD, - DiagnosticTag.BADPRACTICE, + DiagnosticTag.DEPRECATED, DiagnosticTag.UNPREDICTABLE } ) -public class DeprecatedCurrentDateDiagnostic extends AbstractFindMethodDiagnostic implements QuickFixProvider { +public class DeprecatedCurrentDateDiagnostic extends AbstractFindMethodDiagnostic { private static final Pattern currentDatePattern = Pattern.compile( "(текущаядата|currentdate)", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE @@ -66,26 +66,4 @@ protected boolean checkMethodCall(BSLParser.MethodCallContext ctx) { return false; } - @Override - public List getQuickFixes( - List diagnostics, - CodeActionParams params, - DocumentContext documentContext - ) { - - List textEdits = new ArrayList<>(); - - diagnostics.forEach((Diagnostic diagnostic) -> { - TextEdit textEdit = new TextEdit(diagnostic.getRange(), info.getResourceString("changeFix")); - textEdits.add(textEdit); - }); - - return CodeActionProvider.createCodeActions( - textEdits, - info.getResourceString("quickFixMessage"), - documentContext.getUri(), - diagnostics - ); - } - } diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic_en.properties index 2c0494f5763..94e8e0bd00e 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic_en.properties @@ -1,4 +1,3 @@ -changeFix=CurrentSessionDate diagnosticMessage=Use "CurrentSessionDate" instead of deprecated "CurrentDate" diagnosticName=Using of the deprecated method "CurrentDate" -quickFixMessage=Replace to CurrentSessionDate + diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic_ru.properties index 72a7ece2ec4..3b3e3a3f0ca 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic_ru.properties @@ -1,4 +1,3 @@ -changeFix=ТекущаяДатаСеанса diagnosticMessage=Используйте "ТекущаяДатаСеанса" вместо устаревшего "ТекущаяДата" diagnosticName=Использование устаревшего метода "ТекущаяДата" -quickFixMessage=Заменить на "ТекущаяДатаСеанса" + diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnosticTest.java index 7c061bfb8ee..93e253b7c92 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnosticTest.java @@ -21,8 +21,6 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; -import org.eclipse.lsp4j.CodeAction; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; @@ -47,29 +45,4 @@ void test() { } - @Test - void testQuickFixes() { - - final DocumentContext documentContext = getDocumentContext(); - List diagnostics = getDiagnostics(); - final Diagnostic diagnostic = diagnostics.get(0); - final String replacementText = "ТекущаяДатаСеанса"; - - List QuickFixes = getQuickFixes(diagnostic); - assertThat(QuickFixes).hasSize(1); - - final CodeAction quickFix = QuickFixes.get(0); - - assertThat(quickFix) - .of(diagnosticInstance) - .in(documentContext) - .fixes(diagnostic); - - assertThat(quickFix) - .in(documentContext) - .hasChanges(1) - .hasNewText(replacementText); - - } - } From a5facba85096122cf5be2ef0085e0d8a8d0a15b1 Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Thu, 9 Apr 2020 22:04:02 +0300 Subject: [PATCH 008/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=B7=D0=B0=D0=B1=D1=8B=D1=82=D1=83=D1=8E=20=D0=BD?= =?UTF-8?q?=D0=B0=D1=81=D1=82=D1=80=D0=BE=D0=B9=D0=BA=D1=83=20=D0=B4=D0=BB?= =?UTF-8?q?=D1=8F=20=D0=B8=D1=81=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D1=8F=20=D0=BE=D1=82=D0=BB=D0=B0=D0=B4=D1=87?= =?UTF-8?q?=D0=B8=D0=BA=D0=B0=20AST?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/contributing/FastStart.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/contributing/FastStart.md b/docs/contributing/FastStart.md index dfe1dab3cb0..04e325cd8b4 100644 --- a/docs/contributing/FastStart.md +++ b/docs/contributing/FastStart.md @@ -23,7 +23,10 @@ 2. Склонировать в созданный каталог репозиторий проекта `https://github.com/1c-syntax/bsl-parser.git` 3. Выполнить настройку окружения по [инструкции](EnvironmentSetting.md) _(если ранее не выполнялась)_ 4. Установить плагин `ANTLR v4 grammar plugin` -5. Открыть файл `build.gradle.kts` из каталога проекта, согласиться с импортом зависимостей, дождаться их скачивания -6. Открыть файл `src/main/antlr/BSLParser.g4` -7. Установить курсор на любую строку с кодом _(не комментарий)_ и выбрать пункт контекстного меню `Test Rule file` -8. В открывшемся окне выбрать bsl-файл либо вставить текст из буфера обмена + - перезапустить IDEA при необходимости +5. Настроить плагин - `File | Settings | Languages & Frameworks | ANTLR v4 default project settings` `ANTLR v4 grammar plugin` + - Установить настройку `Case transformation in the Preview window` в `Transform to uppercase when lexing` +6. Открыть файл `build.gradle.kts` из каталога проекта, согласиться с импортом зависимостей, дождаться их скачивания +7. Открыть файл `src/main/antlr/BSLParser.g4` +8. Установить курсор на любую строку с кодом _(не комментарий)_ и выбрать пункт контекстного меню `Test Rule file` +9. В открывшемся окне выбрать bsl-файл либо вставить текст из буфера обмена From e929547fcec98efe6c24c36f1c2c81596fa7599f Mon Sep 17 00:00:00 2001 From: Aleksandr Ponkratov Date: Fri, 10 Apr 2020 11:33:37 +0300 Subject: [PATCH 009/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D0=BD=D0=BE=D0=B2=D0=B0=D1=8F=20=D0=B4?= =?UTF-8?q?=D0=B8=D0=B0=D0=B3=D0=BD=D0=BE=D1=81=D1=82=D0=B8=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../MissingVariablesDescriptionDiagnostic.md | 52 +++++++++++++++ docs/diagnostics/index.md | 5 +- .../MissingVariablesDescriptionDiagnostic.md | 51 +++++++++++++++ docs/en/diagnostics/index.md | 5 +- .../context/symbol/SymbolTree.java | 24 +++++++ ...iablesDescriptionDiagnosticDiagnostic.java | 63 +++++++++++++++++++ .../configuration/diagnostics-schema.json | 10 +++ .../languageserver/configuration/schema.json | 3 + ...criptionDiagnosticDiagnostic_en.properties | 2 + ...criptionDiagnosticDiagnostic_ru.properties | 2 + ...esDescriptionDiagnosticDiagnosticTest.java | 46 ++++++++++++++ ...riablesDescriptionDiagnosticDiagnostic.bsl | 4 ++ 12 files changed, 263 insertions(+), 4 deletions(-) create mode 100644 docs/diagnostics/MissingVariablesDescriptionDiagnostic.md create mode 100644 docs/en/diagnostics/MissingVariablesDescriptionDiagnostic.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic.bsl diff --git a/docs/diagnostics/MissingVariablesDescriptionDiagnostic.md b/docs/diagnostics/MissingVariablesDescriptionDiagnostic.md new file mode 100644 index 00000000000..4cfdb7895cb --- /dev/null +++ b/docs/diagnostics/MissingVariablesDescriptionDiagnostic.md @@ -0,0 +1,52 @@ +# Все объявления переменных должны иметь описание (MissingVariablesDescriptionDiagnostic) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Дефект кода` | `BSL`
`OS` | `Незначительный` | `Да` | `5` | `standard` | + + +## Описание диагностики + +Все переменные модулей, а также все экспортируемые переменные должны иметь комментарии. Комментарии ставятся в той же строке после переменной. + +## Примеры + + +## Примеры +Неправильно: + +```bsl +Перем Контекст; +``` + +Правильно: + +```bsl +Перем Контекст; // Некое подробное описание, которое объясняет назначение переменной +``` + +## Источники + + + +* Источник: [Соглашения при написания кода. Структура модуля](https://its.1c.ru/db/v8std#content:455:hdoc ) + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:MissingVariablesDescriptionDiagnostic-off +// BSLLS:MissingVariablesDescriptionDiagnostic-on +``` + +### Параметр конфигурационного файла + +```json +"MissingVariablesDescriptionDiagnostic": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 1f246c6e30d..327c36740fa 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,9 +8,9 @@ ## Список реализованных диагностик -Общее количество: **86** +Общее количество: **87** -* Дефект кода: **54** +* Дефект кода: **55** * Уязвимость: **2** * Ошибка: **28** * Потенциальная уязвимость: **2** @@ -54,6 +54,7 @@ | [MissingCodeTryCatchEx](MissingCodeTryCatchEx.md) | Конструкция "Попытка...Исключение...КонецПопытки" не содержит кода в исключении | Да | Важный | Ошибка | `standard`
`badpractice` | | [MissingSpace](MissingSpace.md) | Пропущены пробелы слева или справа от операторов `+ - * / = % < > <> <= >=`, а так же справа от `,` и `;` | Да | Информационный | Дефект кода | `badpractice` | | [MissingTemporaryFileDeletion](MissingTemporaryFileDeletion.md) | Отсутствует удаление временного файла после использования | Да | Важный | Ошибка | `badpractice`
`standard` | +| [MissingVariablesDescriptionDiagnostic](MissingVariablesDescriptionDiagnostic.md) | Все объявления переменных должны иметь описание | Да | Незначительный | Дефект кода | `standard` | | [MultilingualStringHasAllDeclaredLanguages](MultilingualStringHasAllDeclaredLanguages.md) | Есть локализованный текст для всех заявленных в конфигурации языков | Да | Незначительный | Ошибка | `error`
`localize` | | [MultilingualStringUsingWithTemplate](MultilingualStringUsingWithTemplate.md) | Частично локализованный текст используется в функции СтрШаблон | Да | Важный | Ошибка | `error`
`localize` | | [NestedConstructorsInStructureDeclaration](NestedConstructorsInStructureDeclaration.md) | Использование конструкторов с параметрами при объявлении структуры | Да | Незначительный | Дефект кода | `badpractice`
`brainoverload` | diff --git a/docs/en/diagnostics/MissingVariablesDescriptionDiagnostic.md b/docs/en/diagnostics/MissingVariablesDescriptionDiagnostic.md new file mode 100644 index 00000000000..7ed4dd0e39f --- /dev/null +++ b/docs/en/diagnostics/MissingVariablesDescriptionDiagnostic.md @@ -0,0 +1,51 @@ +# All variables declarations must have a description (MissingVariablesDescriptionDiagnostic) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Code smell` | `BSL`
`OS` | `Minor` | `Yes` | `5` | `standard` | + + +## Description + + +All module variables and export variables, must have comments. Comments are placed on the same line after the variable. + +## Examples + +Incorrect: + +```bsl +Var Context; +``` + +Correct: + +```bsl +Var Context; // Detailed description that explains the purpose of the variable +``` + +## Sources + + + +* Reference [Code conventions. Module structure](https://its.1c.ru/db/v8std#content:455:hdoc) + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:MissingVariablesDescriptionDiagnostic-off +// BSLLS:MissingVariablesDescriptionDiagnostic-on +``` + +### Parameter for config + +```json +"MissingVariablesDescriptionDiagnostic": false +``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 01ff325fefd..c272aae6e75 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,10 +8,10 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **86** +Total: **87** * Error: **28** -* Code smell: **54** +* Code smell: **55** * Vulnerability: **2** * Security Hotspot: **2** @@ -54,6 +54,7 @@ Total: **86** | [MissingCodeTryCatchEx](MissingCodeTryCatchEx.md) | Missing code in Raise block in "Try ... Raise ... EndTry" | Yes | Major | Error | `standard`
`badpractice` | | [MissingSpace](MissingSpace.md) | Missing spaces to the left or right of operators + - * / = % < > <> <= >=, and also to the right of , and ; | Yes | Info | Code smell | `badpractice` | | [MissingTemporaryFileDeletion](MissingTemporaryFileDeletion.md) | Missing temporary file deletion after using | Yes | Major | Error | `badpractice`
`standard` | +| [MissingVariablesDescriptionDiagnostic](MissingVariablesDescriptionDiagnostic.md) | All variables declarations must have a description | Yes | Minor | Code smell | `standard` | | [MultilingualStringHasAllDeclaredLanguages](MultilingualStringHasAllDeclaredLanguages.md) | There is a localized text for all languages declared in the configuration | Yes | Minor | Error | `error`
`localize` | | [MultilingualStringUsingWithTemplate](MultilingualStringUsingWithTemplate.md) | Partially localized text is used in the StrTemplate function | Yes | Major | Error | `error`
`localize` | | [NestedConstructorsInStructureDeclaration](NestedConstructorsInStructureDeclaration.md) | Nested constructors with parameters in structure declaration | Yes | Minor | Code smell | `badpractice`
`brainoverload` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java index b37a545968d..d58da5a8515 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java @@ -88,6 +88,30 @@ public Optional getMethodSymbol(BSLParserRuleContext ctx) { .findAny(); } + public List getVariables() { + return getChildrenFlat(VariableSymbol.class); + } + + public Optional getVariableSymbol(BSLParserRuleContext ctx) { + + BSLParserRuleContext varNameNode; + + if (Trees.nodeContainsErrors(ctx)) { + varNameNode = ctx; + } else if (ctx instanceof BSLParser.ModuleVarDeclarationContext) { + varNameNode = ((BSLParser.ModuleVarDeclarationContext) ctx).var_name(); + } else if (ctx instanceof BSLParser.SubVarDeclarationContext) { + varNameNode = ((BSLParser.SubVarDeclarationContext) ctx).var_name(); + } else { + varNameNode = ctx; + } + + Range variableNameRange = Ranges.create(varNameNode); + + return getVariables().stream() + .filter(variableSymbol -> variableSymbol.getVariableNameRange().equals(variableNameRange)) + .findAny(); + } private List getSelfAndChildrenRecursive(Symbol symbol) { var list = new ArrayList(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic.java new file mode 100644 index 00000000000..2d80b0cdcc9 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic.java @@ -0,0 +1,63 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.symbol.VariableSymbol; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.parser.BSLParser; +import org.antlr.v4.runtime.tree.ParseTree; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.MINOR, + minutesToFix = 5, + tags = { + DiagnosticTag.STANDARD + } + +) +public class MissingVariablesDescriptionDiagnosticDiagnostic extends AbstractVisitorDiagnostic { + public MissingVariablesDescriptionDiagnosticDiagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + public ParseTree visitModuleVarDeclaration(BSLParser.ModuleVarDeclarationContext ctx) { + documentContext + .getSymbolTree() + .getVariableSymbol(ctx) + .flatMap(VariableSymbol::getDescription) + .ifPresent(variableDescription -> { + if (variableDescription.getTrailingDescription().isEmpty()){ + diagnosticStorage.addDiagnostic(ctx); + } + } + ); + + return ctx; + } + +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json index 3dc40d9cd0a..bcd3395e736 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json @@ -504,6 +504,16 @@ }, "$id": "#/definitions/MissingTemporaryFileDeletion" }, + "MissingVariablesDescriptionDiagnostic": { + "description": "All variables declarations must have a description", + "default": null, + "type": [ + "boolean", + "object" + ], + "title": "All variables declarations must have a description", + "$id": "#/definitions/MissingVariablesDescriptionDiagnostic" + }, "MultilingualStringHasAllDeclaredLanguages": { "description": "There is a localized text for all languages declared in the configuration", "default": null, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index b714b7bc2f0..4b88b584286 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -212,6 +212,9 @@ "MissingTemporaryFileDeletion": { "$ref": "diagnostics-schema.json#/definitions/MissingTemporaryFileDeletion" }, + "MissingVariablesDescriptionDiagnostic": { + "$ref": "diagnostics-schema.json#/definitions/MissingVariablesDescriptionDiagnostic" + }, "MultilingualStringHasAllDeclaredLanguages": { "$ref": "diagnostics-schema.json#/definitions/MultilingualStringHasAllDeclaredLanguages" }, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic_en.properties new file mode 100644 index 00000000000..d553b7c926f --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Add a description of the variable +diagnosticName=All variables declarations must have a description diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic_ru.properties new file mode 100644 index 00000000000..44f3007a379 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Добавьте описание переменной +diagnosticName=Все объявления переменных должны иметь описание diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnosticTest.java new file mode 100644 index 00000000000..5f2d064f01a --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnosticTest.java @@ -0,0 +1,46 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class MissingVariablesDescriptionDiagnosticDiagnosticTest extends AbstractDiagnosticTest { + MissingVariablesDescriptionDiagnosticDiagnosticTest() { + super(MissingVariablesDescriptionDiagnosticDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(1, 6, 1, 27); + + } +} diff --git a/src/test/resources/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic.bsl b/src/test/resources/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic.bsl new file mode 100644 index 00000000000..4adb1b20ec1 --- /dev/null +++ b/src/test/resources/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic.bsl @@ -0,0 +1,4 @@ +// Диагностика сработает здесь +Перем ПеременнаяБезОписания; + +Перем ПеременнаяСОписанием; // Диагностика здесь не сработает \ No newline at end of file From 1fa64437f48a22e7858f67f420812739203b6134 Mon Sep 17 00:00:00 2001 From: Aleksandr Ponkratov Date: Fri, 10 Apr 2020 14:32:40 +0300 Subject: [PATCH 010/444] =?UTF-8?q?=D0=98=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=BB=D0=BE=D0=B3=D0=B8=D0=BA=D0=B0=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8,=20=D0=B8=D1=81?= =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D1=8B=20=D0=B7=D0=B0?= =?UTF-8?q?=D0=BC=D0=B5=D1=87=D0=B0=D0=BD=D0=B8=D1=8F=20=D0=B8=D0=B7=20PR?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...stic.md => MissingVariablesDescription.md} | 17 ++++++++------ docs/diagnostics/index.md | 2 +- ...stic.md => MissingVariablesDescription.md} | 15 ++++++++----- docs/en/diagnostics/index.md | 2 +- .../computer/VariableSymbolComputer.java | 4 ---- ...issingVariablesDescriptionDiagnostic.java} | 10 +++++---- .../configuration/diagnostics-schema.json | 4 ++-- .../languageserver/configuration/schema.json | 4 ++-- ...iablesDescriptionDiagnostic_en.properties} | 0 ...iablesDescriptionDiagnostic_ru.properties} | 0 ...esDescriptionDiagnosticDiagnosticTest.java | 11 ++++++---- .../MissingVariablesDescriptionDiagnostic.bsl | 22 +++++++++++++++++++ ...riablesDescriptionDiagnosticDiagnostic.bsl | 4 ---- 13 files changed, 60 insertions(+), 35 deletions(-) rename docs/diagnostics/{MissingVariablesDescriptionDiagnostic.md => MissingVariablesDescription.md} (84%) rename docs/en/diagnostics/{MissingVariablesDescriptionDiagnostic.md => MissingVariablesDescription.md} (83%) rename src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/{MissingVariablesDescriptionDiagnosticDiagnostic.java => MissingVariablesDescriptionDiagnostic.java} (87%) rename src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/{MissingVariablesDescriptionDiagnosticDiagnostic_en.properties => MissingVariablesDescriptionDiagnostic_en.properties} (100%) rename src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/{MissingVariablesDescriptionDiagnosticDiagnostic_ru.properties => MissingVariablesDescriptionDiagnostic_ru.properties} (100%) create mode 100644 src/test/resources/diagnostics/MissingVariablesDescriptionDiagnostic.bsl delete mode 100644 src/test/resources/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic.bsl diff --git a/docs/diagnostics/MissingVariablesDescriptionDiagnostic.md b/docs/diagnostics/MissingVariablesDescription.md similarity index 84% rename from docs/diagnostics/MissingVariablesDescriptionDiagnostic.md rename to docs/diagnostics/MissingVariablesDescription.md index 4cfdb7895cb..6de1e307d85 100644 --- a/docs/diagnostics/MissingVariablesDescriptionDiagnostic.md +++ b/docs/diagnostics/MissingVariablesDescription.md @@ -1,13 +1,13 @@ -# Все объявления переменных должны иметь описание (MissingVariablesDescriptionDiagnostic) +# Все объявления переменных должны иметь описание (MissingVariablesDescription) | Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Дефект кода` | `BSL`
`OS` | `Незначительный` | `Да` | `5` | `standard` | +| `Дефект кода` | `BSL`
`OS` | `Незначительный` | `Да` | `1` | `standard` | ## Описание диагностики -Все переменные модулей, а также все экспортируемые переменные должны иметь комментарии. Комментарии ставятся в той же строке после переменной. +Все переменные модулей, а также все экспортируемые переменные должны иметь комментарии. ## Примеры @@ -23,6 +23,9 @@ ```bsl Перем Контекст; // Некое подробное описание, которое объясняет назначение переменной + +// Некое подробное описание, которое объясняет назначение переменной +Перем Контекст; ``` ## Источники @@ -33,7 +36,7 @@ * Полезная информаця: [Отказ от использования модальных окон](https://its.1c.ru/db/metod8dev#content:5272:hdoc) * Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) --> -* Источник: [Соглашения при написания кода. Структура модуля](https://its.1c.ru/db/v8std#content:455:hdoc ) +* Источник: [Соглашения при написания кода. Структура модуля](https://its.1c.ru/db/v8std#content:455:hdoc) ## Сниппеты @@ -41,12 +44,12 @@ ### Экранирование кода ```bsl -// BSLLS:MissingVariablesDescriptionDiagnostic-off -// BSLLS:MissingVariablesDescriptionDiagnostic-on +// BSLLS:MissingVariablesDescription-off +// BSLLS:MissingVariablesDescription-on ``` ### Параметр конфигурационного файла ```json -"MissingVariablesDescriptionDiagnostic": false +"MissingVariablesDescription": false ``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 327c36740fa..53ae4ea5032 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -54,7 +54,7 @@ | [MissingCodeTryCatchEx](MissingCodeTryCatchEx.md) | Конструкция "Попытка...Исключение...КонецПопытки" не содержит кода в исключении | Да | Важный | Ошибка | `standard`
`badpractice` | | [MissingSpace](MissingSpace.md) | Пропущены пробелы слева или справа от операторов `+ - * / = % < > <> <= >=`, а так же справа от `,` и `;` | Да | Информационный | Дефект кода | `badpractice` | | [MissingTemporaryFileDeletion](MissingTemporaryFileDeletion.md) | Отсутствует удаление временного файла после использования | Да | Важный | Ошибка | `badpractice`
`standard` | -| [MissingVariablesDescriptionDiagnostic](MissingVariablesDescriptionDiagnostic.md) | Все объявления переменных должны иметь описание | Да | Незначительный | Дефект кода | `standard` | +| [MissingVariablesDescription](MissingVariablesDescription.md) | Все объявления переменных должны иметь описание | Да | Незначительный | Дефект кода | `standard` | | [MultilingualStringHasAllDeclaredLanguages](MultilingualStringHasAllDeclaredLanguages.md) | Есть локализованный текст для всех заявленных в конфигурации языков | Да | Незначительный | Ошибка | `error`
`localize` | | [MultilingualStringUsingWithTemplate](MultilingualStringUsingWithTemplate.md) | Частично локализованный текст используется в функции СтрШаблон | Да | Важный | Ошибка | `error`
`localize` | | [NestedConstructorsInStructureDeclaration](NestedConstructorsInStructureDeclaration.md) | Использование конструкторов с параметрами при объявлении структуры | Да | Незначительный | Дефект кода | `badpractice`
`brainoverload` | diff --git a/docs/en/diagnostics/MissingVariablesDescriptionDiagnostic.md b/docs/en/diagnostics/MissingVariablesDescription.md similarity index 83% rename from docs/en/diagnostics/MissingVariablesDescriptionDiagnostic.md rename to docs/en/diagnostics/MissingVariablesDescription.md index 7ed4dd0e39f..489a9e55df2 100644 --- a/docs/en/diagnostics/MissingVariablesDescriptionDiagnostic.md +++ b/docs/en/diagnostics/MissingVariablesDescription.md @@ -1,14 +1,14 @@ -# All variables declarations must have a description (MissingVariablesDescriptionDiagnostic) +# All variables declarations must have a description (MissingVariablesDescription) | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Code smell` | `BSL`
`OS` | `Minor` | `Yes` | `5` | `standard` | +| `Code smell` | `BSL`
`OS` | `Minor` | `Yes` | `1` | `standard` | ## Description -All module variables and export variables, must have comments. Comments are placed on the same line after the variable. +All module variables and export variables must have comments. ## Examples @@ -22,6 +22,9 @@ Correct: ```bsl Var Context; // Detailed description that explains the purpose of the variable + +// Detailed description that explains the purpose of the variable +Var Context; ``` ## Sources @@ -40,12 +43,12 @@ Var Context; // Detailed description that explains the purpose of the variable ### Diagnostic ignorance in code ```bsl -// BSLLS:MissingVariablesDescriptionDiagnostic-off -// BSLLS:MissingVariablesDescriptionDiagnostic-on +// BSLLS:MissingVariablesDescription-off +// BSLLS:MissingVariablesDescription-on ``` ### Parameter for config ```json -"MissingVariablesDescriptionDiagnostic": false +"MissingVariablesDescription": false ``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index c272aae6e75..246b94d7e89 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -54,7 +54,7 @@ Total: **87** | [MissingCodeTryCatchEx](MissingCodeTryCatchEx.md) | Missing code in Raise block in "Try ... Raise ... EndTry" | Yes | Major | Error | `standard`
`badpractice` | | [MissingSpace](MissingSpace.md) | Missing spaces to the left or right of operators + - * / = % < > <> <= >=, and also to the right of , and ; | Yes | Info | Code smell | `badpractice` | | [MissingTemporaryFileDeletion](MissingTemporaryFileDeletion.md) | Missing temporary file deletion after using | Yes | Major | Error | `badpractice`
`standard` | -| [MissingVariablesDescriptionDiagnostic](MissingVariablesDescriptionDiagnostic.md) | All variables declarations must have a description | Yes | Minor | Code smell | `standard` | +| [MissingVariablesDescription](MissingVariablesDescription.md) | All variables declarations must have a description | Yes | Minor | Code smell | `standard` | | [MultilingualStringHasAllDeclaredLanguages](MultilingualStringHasAllDeclaredLanguages.md) | There is a localized text for all languages declared in the configuration | Yes | Minor | Error | `error`
`localize` | | [MultilingualStringUsingWithTemplate](MultilingualStringUsingWithTemplate.md) | Partially localized text is used in the StrTemplate function | Yes | Major | Error | `error`
`localize` | | [NestedConstructorsInStructureDeclaration](NestedConstructorsInStructureDeclaration.md) | Nested constructors with parameters in structure declaration | Yes | Minor | Code smell | `badpractice`
`brainoverload` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java index d17795f8005..c787509ae39 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java @@ -87,11 +87,7 @@ private VariableSymbol createVariableSymbol( private Optional createDescription(Token token) { List tokens = documentContext.getTokens(); - List comments = Trees.getComments(tokens, token); - if (comments.isEmpty()) { - return Optional.empty(); - } String commentsText = comments.stream().map(Token::getText).reduce("", String::concat); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnostic.java similarity index 87% rename from src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic.java rename to src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnostic.java index 2d80b0cdcc9..423d281d248 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnostic.java @@ -33,25 +33,27 @@ @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, severity = DiagnosticSeverity.MINOR, - minutesToFix = 5, + minutesToFix = 1, tags = { DiagnosticTag.STANDARD } ) -public class MissingVariablesDescriptionDiagnosticDiagnostic extends AbstractVisitorDiagnostic { - public MissingVariablesDescriptionDiagnosticDiagnostic(DiagnosticInfo info) { +public class MissingVariablesDescriptionDiagnostic extends AbstractVisitorDiagnostic { + public MissingVariablesDescriptionDiagnostic(DiagnosticInfo info) { super(info); } @Override public ParseTree visitModuleVarDeclaration(BSLParser.ModuleVarDeclarationContext ctx) { + documentContext .getSymbolTree() .getVariableSymbol(ctx) .flatMap(VariableSymbol::getDescription) .ifPresent(variableDescription -> { - if (variableDescription.getTrailingDescription().isEmpty()){ + if (variableDescription.getDescription().isEmpty() + && variableDescription.getTrailingDescription().isEmpty()) { diagnosticStorage.addDiagnostic(ctx); } } diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json index bcd3395e736..e50e2182208 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json @@ -504,7 +504,7 @@ }, "$id": "#/definitions/MissingTemporaryFileDeletion" }, - "MissingVariablesDescriptionDiagnostic": { + "MissingVariablesDescription": { "description": "All variables declarations must have a description", "default": null, "type": [ @@ -512,7 +512,7 @@ "object" ], "title": "All variables declarations must have a description", - "$id": "#/definitions/MissingVariablesDescriptionDiagnostic" + "$id": "#/definitions/MissingVariablesDescription" }, "MultilingualStringHasAllDeclaredLanguages": { "description": "There is a localized text for all languages declared in the configuration", diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 4b88b584286..f31df27a92d 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -212,8 +212,8 @@ "MissingTemporaryFileDeletion": { "$ref": "diagnostics-schema.json#/definitions/MissingTemporaryFileDeletion" }, - "MissingVariablesDescriptionDiagnostic": { - "$ref": "diagnostics-schema.json#/definitions/MissingVariablesDescriptionDiagnostic" + "MissingVariablesDescription": { + "$ref": "diagnostics-schema.json#/definitions/MissingVariablesDescription" }, "MultilingualStringHasAllDeclaredLanguages": { "$ref": "diagnostics-schema.json#/definitions/MultilingualStringHasAllDeclaredLanguages" diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnostic_en.properties similarity index 100% rename from src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic_en.properties rename to src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnostic_en.properties diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnostic_ru.properties similarity index 100% rename from src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic_ru.properties rename to src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnostic_ru.properties diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnosticTest.java index 5f2d064f01a..6d0ab8c6454 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnosticTest.java @@ -28,9 +28,9 @@ import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; -class MissingVariablesDescriptionDiagnosticDiagnosticTest extends AbstractDiagnosticTest { +class MissingVariablesDescriptionDiagnosticDiagnosticTest extends AbstractDiagnosticTest { MissingVariablesDescriptionDiagnosticDiagnosticTest() { - super(MissingVariablesDescriptionDiagnosticDiagnostic.class); + super(MissingVariablesDescriptionDiagnostic.class); } @Test @@ -38,9 +38,12 @@ void test() { List diagnostics = getDiagnostics(); - assertThat(diagnostics).hasSize(1); + assertThat(diagnostics).hasSize(4); assertThat(diagnostics, true) - .hasRange(1, 6, 1, 27); + .hasRange(1, 6, 1, 27) + .hasRange(3, 6, 3, 45) + .hasRange(17, 6, 17, 38) + .hasRange(21, 6, 21, 56); } } diff --git a/src/test/resources/diagnostics/MissingVariablesDescriptionDiagnostic.bsl b/src/test/resources/diagnostics/MissingVariablesDescriptionDiagnostic.bsl new file mode 100644 index 00000000000..fadeb3074e6 --- /dev/null +++ b/src/test/resources/diagnostics/MissingVariablesDescriptionDiagnostic.bsl @@ -0,0 +1,22 @@ + +Перем ПеременнаяБезОписания; + +Перем ЭкспортнаяПеременнаяБезОписания Экспорт; + +Перем ПеременнаяСОписанием; // описание + +Перем ЭкспортнаяПеременнаяСОписанием Экспорт; // описание + +// описание +Перем ПеременнаяСОписаниемВыше; + +// описание +Перем ЭкспортнаяПеременнаяСОписаниемВыше Экспорт; + + // неточное описание + +Перем ПеременнаяСНевернымОписаниемВыше; + + // неточное описание + +Перем ЭкспортнаяПеременнаяСНевернымОписаниемВыше Экспорт; diff --git a/src/test/resources/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic.bsl b/src/test/resources/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic.bsl deleted file mode 100644 index 4adb1b20ec1..00000000000 --- a/src/test/resources/diagnostics/MissingVariablesDescriptionDiagnosticDiagnostic.bsl +++ /dev/null @@ -1,4 +0,0 @@ -// Диагностика сработает здесь -Перем ПеременнаяБезОписания; - -Перем ПеременнаяСОписанием; // Диагностика здесь не сработает \ No newline at end of file From 2154f6c2f34e5e6e6c9e2e64492a6a676aaa023e Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Fri, 10 Apr 2020 20:32:20 +0700 Subject: [PATCH 011/444] =?UTF-8?q?=D0=A1=D0=BA=D1=80=D0=B8=D0=BF=D1=82=20?= =?UTF-8?q?=D1=84=D0=BE=D1=80=D0=BC=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=80=D0=B0=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D0=B8=D0=B7=D0=B2=D0=BE=D0=B4=D0=B8=D1=82=D0=B5?= =?UTF-8?q?=D0=BB=D1=8C=D0=BD=D0=BE=D1=81=D1=82=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/bechmark.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 .github/scripts/bechmark.py diff --git a/.github/scripts/bechmark.py b/.github/scripts/bechmark.py new file mode 100644 index 00000000000..e515afdce7b --- /dev/null +++ b/.github/scripts/bechmark.py @@ -0,0 +1,29 @@ +import pytest +import os +import re +import ntpath + +pattern = r"bsl.+\.jar" +dirName = os.getcwd() + "/build/libs" + +def test_analyze_ssl31(benchmark): + benchmark(some_func, None) + +def some_func(arg): + fullname = get_bslls_jar(dirName) + cmdArgs = ['java'] + cmdArgs.append('-jar') + cmdArgs.append(dirName + '/' + fullname) + cmdArgs.append('-a') + cmdArgs.append('-s') + cmdArgs.append('ssl') + cmd = ' '.join(cmdArgs) + os.system(cmd) + +def get_bslls_jar(dir): + names = os.listdir(dir) + for name in names: + fullname = os.path.join(dir, name) + if os.path.isfile(fullname) and re.search(pattern, fullname) and fullname.find('sources.jar') == -1 and fullname.find('javadoc.jar') == -1: + return ntpath.basename(fullname) + return None From 2c9073f717fcafc4e447e92b9e39afe0f6140d83 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Fri, 10 Apr 2020 20:32:32 +0700 Subject: [PATCH 012/444] =?UTF-8?q?=D0=92=D0=BE=D1=80=D0=BA=D1=84=D0=BB?= =?UTF-8?q?=D0=BE=D1=83=20=D0=B4=D0=BB=D1=8F=20=D0=B7=D0=B0=D0=BC=D0=B5?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=20=D0=BF=D1=80=D0=BE=D0=B8=D0=B7=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4=D0=B8=D1=82=D0=B5=D0=BB=D1=8C=D0=BD=D0=BE=D1=81=D1=82?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/bechmark.yml | 64 ++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 .github/workflows/bechmark.yml diff --git a/.github/workflows/bechmark.yml b/.github/workflows/bechmark.yml new file mode 100644 index 00000000000..c1fecdb24dc --- /dev/null +++ b/.github/workflows/bechmark.yml @@ -0,0 +1,64 @@ +name: Benchmark + +on: + push: + branches: + - develop + - master + pull_request: + +jobs: + Benchmark: + runs-on: ubuntu-latest + steps: + - name: Checkout project + uses: actions/checkout@v2 + + - name: Setup JDK 11 + uses: actions/setup-java@v1 + with: + java-version: 11 + + - name: Build with Gradle + run: ./gradlew jar + + - name: Set up Python + uses: actions/setup-python@v1 + with: + python-version: '3.7' + + - name: Setup pytest-benchmark + run: pip install pytest pytest-benchmark + + - name: Download SSL 3.1 + run: git clone https://github.com/1c-syntax/ssl_3_1.git ssl + + - name: Analyze ssl + run: pytest .github/scripts/bechmark.py --benchmark-min-rounds=1 --benchmark-timer=time.time --benchmark-json=output.json --benchmark-verbose + + - name: Check benchmark result for pull request + if: github.event_name == 'pull_request' + uses: otymko/github-action-benchmark@v1 + with: + name: BSL LS perfomance measurement (SSL 3.1) + tool: 'pytest' + output-file-path: output.json + github-token: ${{ secrets.GITHUB_TOKEN }} + alert-threshold: '10%' + comment-on-alert: true + fail-on-alert: true + alert-comment-cc-users: '@otymko' + + - name: Store benchmark result into branch + if: github.event_name == 'push' + uses: otymko/github-action-benchmark@v1 + with: + name: BSL LS perfomance measurement (SSL 3.1) + tool: 'pytest' + output-file-path: output.json + github-token: ${{ secrets.GITHUB_TOKEN }} + auto-push: true + alert-threshold: '10%' + comment-on-alert: true + fail-on-alert: true + alert-comment-cc-users: '@otymko' From 4823ad129c82bdbbb1c6efec96e2f862d5f45e8c Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Fri, 10 Apr 2020 20:32:45 +0700 Subject: [PATCH 013/444] =?UTF-8?q?=D0=A1=D1=81=D1=8B=D0=BB=D0=BA=D0=B0=20?= =?UTF-8?q?=D0=B2=20readme=20=D0=B8=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 ++ docs/en/index.md | 2 ++ docs/index.md | 2 ++ 3 files changed, 6 insertions(+) diff --git a/README.md b/README.md index f29d1f6ec3f..08a460d11bb 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,8 @@ Сайт проекта - https://1c-syntax.github.io/bsl-language-server +Замеры производительности - [SSL 3.1](https://1c-syntax.github.io/bsl-language-serve/bench/index.html) + [English version](docs/en/index.md) ## Возможности diff --git a/docs/en/index.md b/docs/en/index.md index 3b2b4f08865..823698fdf6d 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -25,6 +25,8 @@ +Perfomance measurement - [SSL 3.1](bench/index.html) + ## Capabilities - File formatting diff --git a/docs/index.md b/docs/index.md index 083e8ab4c1a..e0b3101bb1e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -25,6 +25,8 @@ +Замеры производительности - [SSL 3.1](bench/index.html) + ## Возможности * Форматирование файла From a169a5af6d95aced6084df4e06c814d0f94a4bba Mon Sep 17 00:00:00 2001 From: Aleksandr Ponkratov Date: Fri, 10 Apr 2020 18:14:29 +0300 Subject: [PATCH 014/444] =?UTF-8?q?=D0=98=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=20=D0=BA=D0=BE=D0=BD=D1=81=D1=82=D1=80=D1=83=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D1=80,=20=D1=81=D0=BA=D0=BE=D1=80=D1=80=D0=B5=D0=BA?= =?UTF-8?q?=D1=82=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D0=B0=20=D0=B4=D0=B8?= =?UTF-8?q?=D0=B0=D0=B3=D0=BD=D0=BE=D1=81=D1=82=D0=B8=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../computer/VariableSymbolComputer.java | 7 ++- ...MissingVariablesDescriptionDiagnostic.java | 10 +--- ...esDescriptionDiagnosticDiagnosticTest.java | 49 ------------------- 3 files changed, 8 insertions(+), 58 deletions(-) delete mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnosticTest.java diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java index c787509ae39..b668f25d21f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java @@ -88,10 +88,15 @@ private VariableSymbol createVariableSymbol( private Optional createDescription(Token token) { List tokens = documentContext.getTokens(); List comments = Trees.getComments(tokens, token); + Optional trailingComments = Trees.getTrailingComment(tokens, token); + + if (comments.isEmpty() && trailingComments.isEmpty()) { + return Optional.empty(); + } String commentsText = comments.stream().map(Token::getText).reduce("", String::concat); - var trailingDescription = Trees.getTrailingComment(tokens, token) + var trailingDescription = trailingComments .map(trailingComment -> VariableDescription.builder() .description(trailingComment.getText()) .range(Ranges.create(trailingComment)) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnostic.java index 423d281d248..8dfecd6e396 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnostic.java @@ -50,14 +50,8 @@ public ParseTree visitModuleVarDeclaration(BSLParser.ModuleVarDeclarationContext documentContext .getSymbolTree() .getVariableSymbol(ctx) - .flatMap(VariableSymbol::getDescription) - .ifPresent(variableDescription -> { - if (variableDescription.getDescription().isEmpty() - && variableDescription.getTrailingDescription().isEmpty()) { - diagnosticStorage.addDiagnostic(ctx); - } - } - ); + .filter(variableSymbol -> variableSymbol.getDescription().isEmpty()) + .ifPresent(noneDescription -> diagnosticStorage.addDiagnostic(ctx)); return ctx; } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnosticTest.java deleted file mode 100644 index 6d0ab8c6454..00000000000 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticDiagnosticTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * This file is a part of BSL Language Server. - * - * Copyright © 2018-2020 - * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; - -import org.eclipse.lsp4j.Diagnostic; -import org.junit.jupiter.api.Test; - -import java.util.List; - -import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; - -class MissingVariablesDescriptionDiagnosticDiagnosticTest extends AbstractDiagnosticTest { - MissingVariablesDescriptionDiagnosticDiagnosticTest() { - super(MissingVariablesDescriptionDiagnostic.class); - } - - @Test - void test() { - - List diagnostics = getDiagnostics(); - - assertThat(diagnostics).hasSize(4); - assertThat(diagnostics, true) - .hasRange(1, 6, 1, 27) - .hasRange(3, 6, 3, 45) - .hasRange(17, 6, 17, 38) - .hasRange(21, 6, 21, 56); - - } -} From 7d097c42a787d4fd4bc98fa14d4a3f7f144ba291 Mon Sep 17 00:00:00 2001 From: Aleksandr Ponkratov Date: Fri, 10 Apr 2020 18:37:46 +0300 Subject: [PATCH 015/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=20=D0=BF=D0=BE=D1=82=D0=B5=D1=80=D1=8F=D0=BD=D0=BD?= =?UTF-8?q?=D1=8B=D0=B9=20=D1=82=D0=B5=D1=81=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...ingVariablesDescriptionDiagnosticTest.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticTest.java diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticTest.java new file mode 100644 index 00000000000..72b12244d64 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticTest.java @@ -0,0 +1,49 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class MissingVariablesDescriptionDiagnosticTest extends AbstractDiagnosticTest { + MissingVariablesDescriptionDiagnosticTest() { + super(MissingVariablesDescriptionDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(4); + assertThat(diagnostics, true) + .hasRange(1, 6, 1, 27) + .hasRange(3, 6, 3, 45) + .hasRange(17, 6, 17, 38) + .hasRange(21, 6, 21, 56); + + } +} From 3f93459039c1d702a3a38ed25f1fc31e9e7e10d4 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sat, 11 Apr 2020 02:18:36 +0700 Subject: [PATCH 016/444] =?UTF-8?q?=D0=B3=D0=B5=D0=BD=D0=B5=D1=80=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D1=8F=20=D0=B1=D0=B5=D0=B9=D0=B4=D0=B6=D0=B0=20?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=BE=D1=81=D0=BD=D0=BE=D0=B2=D0=B5=20=D1=82?= =?UTF-8?q?=D0=B5=D0=BA=D1=83=D1=89=D0=B8=D1=85=20=D0=B7=D0=B0=D0=BC=D0=B5?= =?UTF-8?q?=D1=80=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/gen-bandge.py | 13 +++++++++++++ .github/workflows/bechmark.yml | 32 ++++++++++++++++++-------------- 2 files changed, 31 insertions(+), 14 deletions(-) create mode 100644 .github/scripts/gen-bandge.py diff --git a/.github/scripts/gen-bandge.py b/.github/scripts/gen-bandge.py new file mode 100644 index 00000000000..2195d8385f3 --- /dev/null +++ b/.github/scripts/gen-bandge.py @@ -0,0 +1,13 @@ +import json +from pybadges import badge + +value = '0' +with open("output.json", "r") as file: + data = json.load(file) + total = data.get('benchmarks')[0].get('stats').get('total') + value = '{:.2f}'.format(total) + +svg = badge(left_text='Benckmark (SSL 1.0)', right_text=value) +f = open('benchmark.svg', 'w') +f.write(svg) +f.close() \ No newline at end of file diff --git a/.github/workflows/bechmark.yml b/.github/workflows/bechmark.yml index c1fecdb24dc..220bfd3fe76 100644 --- a/.github/workflows/bechmark.yml +++ b/.github/workflows/bechmark.yml @@ -1,7 +1,7 @@ name: Benchmark on: - push: + push: branches: - develop - master @@ -25,10 +25,10 @@ jobs: - name: Set up Python uses: actions/setup-python@v1 with: - python-version: '3.7' + python-version: "3.7" - - name: Setup pytest-benchmark - run: pip install pytest pytest-benchmark + - name: Setup Python libs + run: pip install pytest pytest-benchmark && pip install pybadges - name: Download SSL 3.1 run: git clone https://github.com/1c-syntax/ssl_3_1.git ssl @@ -36,29 +36,33 @@ jobs: - name: Analyze ssl run: pytest .github/scripts/bechmark.py --benchmark-min-rounds=1 --benchmark-timer=time.time --benchmark-json=output.json --benchmark-verbose + - name: Generation badge benchmark + if: github.event_name == 'push' + run: python .github/scripts/gen-bandge.py + - name: Check benchmark result for pull request if: github.event_name == 'pull_request' - uses: otymko/github-action-benchmark@v1 + uses: otymko/github-action-benchmark@v1.1 with: name: BSL LS perfomance measurement (SSL 3.1) - tool: 'pytest' + tool: "pytest" output-file-path: output.json github-token: ${{ secrets.GITHUB_TOKEN }} - alert-threshold: '10%' + alert-threshold: "110%" comment-on-alert: true - fail-on-alert: true - alert-comment-cc-users: '@otymko' + fail-on-alert: false + alert-comment-cc-users: "@otymko" - name: Store benchmark result into branch if: github.event_name == 'push' - uses: otymko/github-action-benchmark@v1 + uses: otymko/github-action-benchmark@v1.1 with: name: BSL LS perfomance measurement (SSL 3.1) - tool: 'pytest' + tool: "pytest" output-file-path: output.json github-token: ${{ secrets.GITHUB_TOKEN }} auto-push: true - alert-threshold: '10%' + alert-threshold: "110%" comment-on-alert: true - fail-on-alert: true - alert-comment-cc-users: '@otymko' + fail-on-alert: false + alert-comment-cc-users: "@otymko" From 5ebcc70f0b078b6efe7a88db5a01a63d5b736bef Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sat, 11 Apr 2020 02:18:59 +0700 Subject: [PATCH 017/444] =?UTF-8?q?=D0=B1=D0=B5=D0=B9=D0=B4=D0=B6=20=D0=B7?= =?UTF-8?q?=D0=B0=D0=BC=D0=B5=D1=80=D0=BE=D0=B2=20=D0=B2=20=D0=B4=D0=BE?= =?UTF-8?q?=D0=BA=D1=83=D0=BC=D0=B5=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/index.md | 1 + docs/index.md | 1 + 2 files changed, 2 insertions(+) diff --git a/docs/en/index.md b/docs/en/index.md index 823698fdf6d..e1bdd5980f4 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -8,6 +8,7 @@ [![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=alert_status)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) [![Maintainability](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=coverage)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) +[![Benchmark](bench/benchmark.svg)](bench/index.html) [![telegram](https://img.shields.io/badge/telegram-chat-green.svg)](https://t.me/bsl_language_server) [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) implementation for 1C (BSL) - 1C:Enterprise 8 and [OneScript](http://oscript.io) languages. diff --git a/docs/index.md b/docs/index.md index e0b3101bb1e..2346487ee19 100644 --- a/docs/index.md +++ b/docs/index.md @@ -8,6 +8,7 @@ [![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=alert_status)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) [![Maintainability](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=coverage)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) +[![Benchmark](bench/benchmark.svg)](bench/index.html) [![telegram](https://img.shields.io/badge/telegram-chat-green.svg)](https://t.me/bsl_language_server) Реализация протокола [language server protocol](https://microsoft.github.io/language-server-protocol/) для языка 1C (BSL) - языка 1С:Предприятие 8 и [OneScript](http://oscript.io). From 06b641dfdde85e9b7c42f9c6ae62373c0f10bcd2 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sat, 11 Apr 2020 02:22:38 +0700 Subject: [PATCH 018/444] =?UTF-8?q?=D0=91=D0=B5=D0=B9=D0=B4=D0=B6=20=D0=B2?= =?UTF-8?q?=20=D1=80=D0=B8=D0=B4=D0=BC=D0=B8,=20=D0=BF=D0=BE=D1=82=D0=BE?= =?UTF-8?q?=D0=BC=20=D1=81=D0=B4=D0=B5=D0=BB=D0=B0=D1=82=D1=8C=20=D0=B4?= =?UTF-8?q?=D0=BB=D1=8F=20=D0=B4=D0=B2=D1=83=D1=85=20=D0=B2=D0=B5=D1=82?= =?UTF-8?q?=D0=BE=D0=BA=20(=D0=BC=D0=B0=D1=81=D1=82=D0=B5=D1=80=20/=20?= =?UTF-8?q?=D0=B4=D0=B5=D0=B2=D0=B5=D0=BB=D0=BE=D0=BF)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 08a460d11bb..f63eb6fdc0c 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ [![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=alert_status)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) [![Maintainability](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=coverage)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) +[![Benchmark](https://1c-syntax.github.io/bsl-language-server/dev/bench/benchmark.svg)](https://1c-syntax.github.io/bsl-language-server/dev/bench/index.html) [![telegram](https://img.shields.io/badge/telegram-chat-green.svg)](https://t.me/bsl_language_server) Реализация протокола [language server protocol](https://microsoft.github.io/language-server-protocol/) для языка 1C (BSL) - языка 1С:Предприятие 8 и [OneScript](http://oscript.io). From c7fdd290b1271788cd09559efb3553c655d0cb01 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sat, 11 Apr 2020 20:48:15 +0700 Subject: [PATCH 019/444] =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B5=D0=B8=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D0=BE=D0=B2=D0=B0=D0=BD=D1=8B=D0=B5=20=D1=84=D0=B0?= =?UTF-8?q?=D0=B9=D0=BB=D0=BE=D0=B2=20=D0=B7=D0=B0=D0=BF=D1=83=D1=81=D0=BA?= =?UTF-8?q?=D0=B0=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=80=D0=BE=D0=B2=20(=D0=B1?= =?UTF-8?q?=D1=8B=D0=BB=D0=B0=20=D0=BE=D0=BF=D0=B5=D1=87=D0=B0=D1=82=D0=BA?= =?UTF-8?q?=D0=B0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/{bechmark.py => benchmark.py} | 0 .github/workflows/{bechmark.yml => benchmark.yml} | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename .github/scripts/{bechmark.py => benchmark.py} (100%) rename .github/workflows/{bechmark.yml => benchmark.yml} (92%) diff --git a/.github/scripts/bechmark.py b/.github/scripts/benchmark.py similarity index 100% rename from .github/scripts/bechmark.py rename to .github/scripts/benchmark.py diff --git a/.github/workflows/bechmark.yml b/.github/workflows/benchmark.yml similarity index 92% rename from .github/workflows/bechmark.yml rename to .github/workflows/benchmark.yml index 220bfd3fe76..fced97e3f2b 100644 --- a/.github/workflows/bechmark.yml +++ b/.github/workflows/benchmark.yml @@ -34,7 +34,7 @@ jobs: run: git clone https://github.com/1c-syntax/ssl_3_1.git ssl - name: Analyze ssl - run: pytest .github/scripts/bechmark.py --benchmark-min-rounds=1 --benchmark-timer=time.time --benchmark-json=output.json --benchmark-verbose + run: pytest .github/scripts/benchmark.py --benchmark-min-rounds=1 --benchmark-timer=time.time --benchmark-json=output.json --benchmark-verbose - name: Generation badge benchmark if: github.event_name == 'push' From 7a0d3a7c161f2b3a1946b28e323e1968b3098cf0 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sat, 11 Apr 2020 20:49:58 +0700 Subject: [PATCH 020/444] =?UTF-8?q?=D1=81=D0=BE=D1=85=D1=80=D0=B0=D0=BD?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BF=D0=B0=D0=BF=D0=BA=D0=B8=20ben?= =?UTF-8?q?ch=20=D0=BF=D1=80=D0=B8=20build=20gh-pages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/gh-pages.yml | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index ac5a64cfbf9..84fb4cebea5 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -32,6 +32,7 @@ jobs: run: | wget https://github.com/${{ github.repository }}/archive/gh-pages.zip || true unzip gh-pages.zip || true + mkdir tmp-bench - name: Save latest Develop if: github.ref == 'refs/heads/master' @@ -47,6 +48,16 @@ jobs: cp -R ${GITHUB_REPOSITORY#*/}-gh-pages/. public || true rm -rf public/dev || true mkdir public/dev + + - name: Backup benchmark (master) + if: github.ref == 'refs/heads/master' + run: | + cp -R ${GITHUB_REPOSITORY#*/}-gh-pages/bench/. tmp-bench || true + + - name: Backup benchmark (develop) + if: github.ref == 'refs/heads/develop' + run: | + cp -R ${GITHUB_REPOSITORY#*/}-gh-pages/dev/bench/. tmp-bench || true - name: Patch Develop if: github.ref == 'refs/heads/develop' @@ -66,7 +77,12 @@ jobs: rm -rf temp/docs/en cd temp mkdocs build - + + - name: Copy benchmark + run: | + cp -R tmp-bench/. temp/site/bench + rm -rf tmp-bench + - name: Public Russian Master if: github.ref == 'refs/heads/master' run: | From 08fee804b9438c071389af626ef37de4c50c585d Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sat, 11 Apr 2020 20:50:11 +0700 Subject: [PATCH 021/444] =?UTF-8?q?=D0=B4=D0=BB=D1=8F=20=D0=BF=D1=80=D0=BE?= =?UTF-8?q?=D0=B2=D0=B5=D1=80=D0=BA=D0=B8=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D1=8B=20gh-pages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/index.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/index.md b/docs/index.md index 2346487ee19..224a4ceb131 100644 --- a/docs/index.md +++ b/docs/index.md @@ -125,3 +125,4 @@ java -jar bsl-language-server.jar --format --srcDir ./src/cf Создатель профессиональных инструментов разработки программного обеспечения, инновационных и мощных, [JetBrains](https://www.jetbrains.com) поддержал наш проект, предоставив лицензии на свои продукты, в том числе на `IntelliJ IDEA Ultimate`. `IntelliJ IDEA Ultimate` один из лучших инструментов в своем классе. + From 45da7fdddc134244cd313ae6d937249a56b8a3d0 Mon Sep 17 00:00:00 2001 From: Oleg Tymko Date: Sat, 11 Apr 2020 21:21:31 +0700 Subject: [PATCH 022/444] =?UTF-8?q?=D0=A3=D0=B2=D0=B5=D0=BB=D0=B8=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BA=D1=80=D1=83=D0=B3=D0=BE=D0=B2?= =?UTF-8?q?=20bench=20=D1=81=201=20=D0=B4=D0=BE=203?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/benchmark.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index fced97e3f2b..5002e68c47e 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -34,7 +34,7 @@ jobs: run: git clone https://github.com/1c-syntax/ssl_3_1.git ssl - name: Analyze ssl - run: pytest .github/scripts/benchmark.py --benchmark-min-rounds=1 --benchmark-timer=time.time --benchmark-json=output.json --benchmark-verbose + run: pytest .github/scripts/benchmark.py --benchmark-min-rounds=3 --benchmark-timer=time.time --benchmark-json=output.json --benchmark-verbose - name: Generation badge benchmark if: github.event_name == 'push' From a96ffc5e9403a211648c232117bcd906a72bfba9 Mon Sep 17 00:00:00 2001 From: Oleg Tymko Date: Sat, 11 Apr 2020 21:56:46 +0700 Subject: [PATCH 023/444] =?UTF-8?q?Total=20=D0=BD=D0=B5=20=D0=BF=D0=BE?= =?UTF-8?q?=D0=B4=D1=85=D0=BE=D0=B4=D0=B8=D1=82=20=D0=BF=D1=80=D0=B8=20?= =?UTF-8?q?=D0=BD=D0=B5=D1=81=D0=BA=D0=BE=D0=BB=D1=8C=D0=BA=D0=B8=D1=85=20?= =?UTF-8?q?=D0=B7=D0=B0=D0=BC=D0=B5=D1=80=D0=B0=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit total -> mean --- .github/scripts/gen-bandge.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/scripts/gen-bandge.py b/.github/scripts/gen-bandge.py index 2195d8385f3..298d9e4f75e 100644 --- a/.github/scripts/gen-bandge.py +++ b/.github/scripts/gen-bandge.py @@ -4,10 +4,10 @@ value = '0' with open("output.json", "r") as file: data = json.load(file) - total = data.get('benchmarks')[0].get('stats').get('total') + total = data.get('benchmarks')[0].get('stats').get('mean') value = '{:.2f}'.format(total) svg = badge(left_text='Benckmark (SSL 1.0)', right_text=value) f = open('benchmark.svg', 'w') f.write(svg) -f.close() \ No newline at end of file +f.close() From 75a4e55e7bb86459f34821b53afb6ec1d7197ef3 Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Sat, 11 Apr 2020 14:32:11 +0300 Subject: [PATCH 024/444] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D1=83=D1=81=D1=82=D0=B0=D1=80=D0=B5=D0=B2=D1=88?= =?UTF-8?q?=D0=B5=D0=B5=20=D0=B8=D0=BC=D1=8F=20=D0=BC=D0=B5=D1=82=D0=BE?= =?UTF-8?q?=D0=B4=D0=B0=20=D0=B2=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/contributing/DiagnostcAddSettings.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/contributing/DiagnostcAddSettings.md b/docs/contributing/DiagnostcAddSettings.md index 1c70b2abfc2..c17b3e255c4 100644 --- a/docs/contributing/DiagnostcAddSettings.md +++ b/docs/contributing/DiagnostcAddSettings.md @@ -43,12 +43,12 @@ Обязательно нужно добавить тест для случая изменения настроек диагностики. Тест добавляется во все тот же класс теста диагностики _(отдельный метод для каждой комбинации вариантов настроек диагностики)_. В начале теста необходимо выполнить установку значения параметра диагностики, последующие действия аналогичны общим правилам написания тестов. -Для установки параметра диагностики из теста необходимо получить конфигурацию диагностики по-умолчанию, используя метод `getDefaultDiagnosticConfiguration()` из метаданных текущей диагностики `diagnosticInstance.getInfo()`. Затем выполнить изменение значения параметра, путем добавления в коллекцию конфигурации, а затем переконфигурировать текущую диагностику, обратившись к методу `configure`. +Для установки параметра диагностики из теста необходимо получить конфигурацию диагностики по-умолчанию, используя метод `getDefaultConfiguration()` из метаданных текущей диагностики `diagnosticInstance.getInfo()`. Затем выполнить изменение значения параметра, путем добавления в коллекцию конфигурации, а затем переконфигурировать текущую диагностику, обратившись к методу `configure`. Пример ```java // получение текущей конфигурации диагностики -Map configuration = diagnosticInstance.getInfo().getDefaultDiagnosticConfiguration(); +Map configuration = diagnosticInstance.getInfo().getDefaultConfiguration(); // установка нового значения configuration.put("commentsAnnotation", "//(с)"); From a48f479c851e9aa34d7bc250b8e5759d8cc3cc35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BD=D1=82=D0=BE=D0=BD=20=D0=A1=D1=82=D0=B5=D0=BF?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Sun, 12 Apr 2020 13:24:15 +0300 Subject: [PATCH 025/444] =?UTF-8?q?Typo:=20=D0=9D=D0=BE=D0=B2=D1=8B=D0=B5?= =?UTF-8?q?=20=D1=81=D0=BB=D0=BE=D0=B2=D0=B0=20=D0=B2=20=D0=B8=D1=81=D0=BA?= =?UTF-8?q?=D0=BB=D1=8E=D1=87=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BF=D0=BE=20?= =?UTF-8?q?=D1=80=D0=B5=D0=B7=D1=83=D0=BB=D1=8C=D1=82=D0=B0=D1=82=D0=B0?= =?UTF-8?q?=D0=BC=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8=20ERP?= =?UTF-8?q?=20=D0=B8=20word?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../languageserver/diagnostics/TypoDiagnostic_ru.properties | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties index 20d23154b99..cc04cc27c96 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties @@ -5,6 +5,10 @@ diagnosticExceptions=Модифицированность,Повт,Исп,Рег Таб,Док,Стр,гггг,дд,Перезаполнить,Версионирование,Автогруппировку,Подредакции,Версионируемого,Сис,Автозаголовок,Неиспользующихся,\ Дозаполнить,Гиперссылкой,Слеш,Гиперссылку,Слеши,Слеша,Гиперссылкой,Перепроведение,Перепроведения,Перепроведением,Автонастройка\ ,Многострочность,Перезаполняется,Неопределен,Модифицированности,Подредакции,Фич,Гиперссылок,Автонастройку,Непройденные,Псевдо,Подпапки\ - ,Декомпозировать,Автообновление,Хэш,Гант,Ганта,Версионируемый,Автоиспользование,Непроведенный,Гипер + ,Декомпозировать,Автообновление,Хэш,Гант,Ганта,Версионируемый,Автоиспользование,Непроведенный,Гипер\ + ,Регл,Госрегулированием,Мульти,Неодобренном,Валидное,Штрихкодам,Коннект,Сконвертировать,Офшоре,Корсчета\ + ,Микропредприятий,Зарплатных,Зацикленности,Журналирования,Сворачиваемости,Студотряде,Перезаполняемая,Резидентство\ + ,Отсканированной,Парсер,Валидные,Несырьевых,Штрихкодом,Подзапросы,Физлица,Штрихкоду,Стикера,Техподдержки,Грейд\ + ,Процессинговых,Однострочное,Офшоров,Токене minWordLength=Минимальная длина проверяемых слов userWordsToIgnore=Пользовательский словарь исключений \ No newline at end of file From 3098751518aaf09e129f0e882f055a4236d13836 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BD=D1=82=D0=BE=D0=BD=20=D0=A1=D1=82=D0=B5=D0=BF?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Sun, 12 Apr 2020 13:29:56 +0300 Subject: [PATCH 026/444] =?UTF-8?q?Typo:=20=D0=A1=D0=BE=D1=80=D1=82=D0=B8?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=D0=BA=D0=B0=20=D1=81=D0=BB=D0=BE=D0=B2=20?= =?UTF-8?q?=D0=B2=20=D0=B8=D1=81=D0=BA=D0=BB=D1=8E=D1=87=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/TypoDiagnostic_ru.properties | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties index cc04cc27c96..f509b23d925 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties @@ -1,14 +1,14 @@ diagnosticMessage=Возможная опечатка в "%s" diagnosticName=Опечатка diagnosticLanguage=ru -diagnosticExceptions=Модифицированность,Повт,Исп,Рег,Знч,Возр,Убыв,Неопределено,Субконто,Дт,Кт,Автотест,Сериализатор,\ - Таб,Док,Стр,гггг,дд,Перезаполнить,Версионирование,Автогруппировку,Подредакции,Версионируемого,Сис,Автозаголовок,Неиспользующихся,\ - Дозаполнить,Гиперссылкой,Слеш,Гиперссылку,Слеши,Слеша,Гиперссылкой,Перепроведение,Перепроведения,Перепроведением,Автонастройка\ - ,Многострочность,Перезаполняется,Неопределен,Модифицированности,Подредакции,Фич,Гиперссылок,Автонастройку,Непройденные,Псевдо,Подпапки\ - ,Декомпозировать,Автообновление,Хэш,Гант,Ганта,Версионируемый,Автоиспользование,Непроведенный,Гипер\ - ,Регл,Госрегулированием,Мульти,Неодобренном,Валидное,Штрихкодам,Коннект,Сконвертировать,Офшоре,Корсчета\ - ,Микропредприятий,Зарплатных,Зацикленности,Журналирования,Сворачиваемости,Студотряде,Перезаполняемая,Резидентство\ - ,Отсканированной,Парсер,Валидные,Несырьевых,Штрихкодом,Подзапросы,Физлица,Штрихкоду,Стикера,Техподдержки,Грейд\ - ,Процессинговых,Однострочное,Офшоров,Токене +diagnosticExceptions=Автогруппировку,Автозаголовок,Автоиспользование,Автонастройка,Автонастройку,Автообновление,Автотест\ + ,Валидное,Валидные,Версионирование,Версионируемого,Версионируемый,Возр,Гант,Ганта,гггг,Гипер,Гиперссылкой,Гиперссылкой\ + ,Гиперссылку,Гиперссылок,Госрегулированием,Грейд,дд,Декомпозировать,Дозаполнить,Док,Дт,Журналирования,Зарплатных\ + ,Зацикленности,Знч,Исп,Коннект,Корсчета,Кт,Микропредприятий,Многострочность,Модифицированности,Модифицированность\ + ,Мульти,Неиспользующихся,Неодобренном,Неопределен,Неопределено,Непроведенный,Непройденные,Несырьевых,Однострочное\ + ,Отсканированной,Офшоре,Офшоров,Парсер,Перезаполнить,Перезаполняемая,Перезаполняется,Перепроведение,Перепроведением\ + ,Перепроведения,Повт,Подзапросы,Подпапки,Подредакции,Подредакции,Процессинговых,Псевдо,Рег,Регл,Резидентство\ + ,Сворачиваемости,Сериализатор,Сис,Сконвертировать,Слеш,Слеша,Слеши,Стикера,Стр,Студотряде,Субконто,Таб,Техподдержки\ + ,Токене,Убыв,Физлица,Фич,Хэш,Штрихкодам,Штрихкодом,Штрихкоду minWordLength=Минимальная длина проверяемых слов userWordsToIgnore=Пользовательский словарь исключений \ No newline at end of file From 7e8d7917623b9872beda4beb3796446f0e022f41 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Sun, 12 Apr 2020 07:06:54 +0300 Subject: [PATCH 027/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D0=B8=D0=BD=D1=84=D0=BE=D1=80=D0=BC=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D1=8F=20=D0=BE=D0=B1=20=D1=81=D0=B8=D1=82=D1=83?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8,=20=D0=BA=D0=BE=D0=B3=D0=B4=D0=B0=20co?= =?UTF-8?q?nfigure=20=D0=BD=D0=B0=D0=B4=D0=BE=20=D1=80=D0=B5=D0=B0=D0=BB?= =?UTF-8?q?=D0=B8=D0=B7=D0=BE=D0=B2=D1=8B=D0=B2=D0=B0=D1=82=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/contributing/DiagnostcAddSettings.md | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/docs/contributing/DiagnostcAddSettings.md b/docs/contributing/DiagnostcAddSettings.md index c17b3e255c4..7f82133e1ae 100644 --- a/docs/contributing/DiagnostcAddSettings.md +++ b/docs/contributing/DiagnostcAddSettings.md @@ -24,17 +24,31 @@ ``` -Следующим шагом, необходимо реализовать метод установки значения `configure`. -Например +Если параметр примитивный или типа String и он устанавливается в соответствующее свойство класса диагностики простым сеттером, то на этом все. +Если же параметр более сложный, например строка-паттерн для регулярного выражения, которое необходимо вычислить перед установкой, то нужно реализовать метод установки значений параметров `configure`. + +Например есть два параметра: + +- `commentAsCode` - считать комментарии как код, типа булево +- `excludeMethods` - методы, которые не надо проверять, типа ArrayList + +Тогда метод установки значений параметров будет выглядеть: ```java @Override public void configure(Map configuration) { + if (configuration == null) { return; } - - this.commentsAnnotation = (String) configuration.getOrDefault("commentsAnnotation", commentsAnnotation); + + // для установки "простых свойств", включая "commentAsCode" + super.configure(configuration); + + // установка "сложного" свойства "excludeMethods" + String excludeMethodsString = + (String) configuration.getOrDefault("excludeMethods", EXCLUDE_METHODS_DEFAULT); + this.excludeMethods = new ArrayList<>(Arrays.asList(excludeMethodsString.split(","))); } ``` From 7ca97f2285803c9c9fcaf86f11490d440c0fe1e1 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Sun, 12 Apr 2020 08:45:58 +0300 Subject: [PATCH 028/444] =?UTF-8?q?=D0=9D=D0=B5=D0=BC=D0=BD=D0=BE=D0=B3?= =?UTF-8?q?=D0=BE=20=D0=BF=D1=80=D0=B0=D0=B2=D0=B8=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/contributing/Rules.md | 43 ++++++++++++++++++++++++++++++++++++++ docs/contributing/index.md | 2 ++ 2 files changed, 45 insertions(+) create mode 100644 docs/contributing/Rules.md diff --git a/docs/contributing/Rules.md b/docs/contributing/Rules.md new file mode 100644 index 00000000000..835abc2b414 --- /dev/null +++ b/docs/contributing/Rules.md @@ -0,0 +1,43 @@ +# Правила или как жить дружно и эффективно + +Проект `BSL Language Server` является свободным, некоммерческим, развивается дружным сообществом, где главенствующими правилами являются взаимоуважение и взаимопомощь. + +В других документах, можно найти правила и инструкции разработки, здесь же больше социальные правила. + +Рассмотрим на примере, что хорошо, и что плохо. + +## Изучение + +Вы увидели наш проект и у вас появились вопросы. Задавать вопросы можно в любом официальном канале, будь то чат или обсуждение в рамках задачи на GitHub. __Но!__ + +Вопросы и замечания типа "что это за фигня", "на****я", "нормальные люди так не делают", "кгам" - оставьте при себе, кому-то все равно, но некоторым может быть обидно, неприятно. + +Переформулируйте вопросы на "а что это вы тут делаете", "а почему, какая цель", "как это работает" и вы получите адекватный, развернутый ответ. За замечания "так не правильно, __ПОТОМУ ЧТО__ *далее ссылки или пояснения*" будут отдельные благодарность и уважение, так как идеальных людей нет и все совершают ошибки, а соринка в чужом глазу всегда виднее. + +## Разработка + +Вы решили помочь проекту, внеся доработки в его кодовую базу, документацию. Сразу спасибо :). __Но!__ +Надо быть готовым к тому, что изменения обязательно будут анализироваться, к ним могут быть высказаны замечания, в том числе: "все неправильно, потому что..." и "нужно переделать...". + +Необходимо адекватно воспринимать замечания, внося соответствующие исправления. Если считаете, что ваше решение верно, то дискуссия с примерами и пояснениями приветствуется, как говорил уже ранее, идеальных людей нет. + +Если у вас что-то не получается, не понимаете как сделать - спрашивайте, но опять же, без "наездов" типа "у вас черт ногу сломит, фиг поймешь как эта х***ня работает". + +Помощь вам в "сделать хорошо" несет пользу проекту, но не стоит злоупотребять вопросами "как это делается", ожидать готовое решение - если вы не можете разобраться в языке программирования, на котором пишете, стоит отложить задачу и поизучать, здесь не бесплатные курсы для студентов. + +## Найдена ошибка, несоответствие, опечатка и т.д. + +Если вы нашли у нас ошибку - сообщите о ней. Хороший вариант - это оформить задачу в проекте на GitHub, идеальный - отправить следом PULL REQUEST с исправлением. +__УЖАСНЫЙ ВАРИАНТ__ - это просто кричать "у вас кругом одни баги", "все сыро и противно" и т.д. Кому вы помогли данным сообщением? Попытка понизить самооценку сообщества и мейнтенеров или самоутверждение за счет других? + +## Общение + +Оскорбления не приемлемы в любом виде! + +## Вам не нравится проект, люди, правила + +Если вам не нравится конкретный человек сообщества по личным причинам - это ваши личные проблемы, помочь мы вам не сможем, разбирайтесь сами. + +Если вам не нравятся правила, можно обсудить, но... **наш проект, наши правила**. + +Если вам не нравится наш проект - ничего страшного, просто пройдите мимо. diff --git a/docs/contributing/index.md b/docs/contributing/index.md index f1ae581b385..00c7da45cac 100644 --- a/docs/contributing/index.md +++ b/docs/contributing/index.md @@ -2,6 +2,8 @@ В данном разделе собраны статьи, содержащие информацию для разработчиков диагностик и функциональности ядра. +[Необходимо прочитать в самом начале](Rules.md). + ## Инструкции - Старт From ebf4a3cd44b5e2cfbe8c6eb9c35766d03928db03 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Sun, 12 Apr 2020 14:09:49 +0300 Subject: [PATCH 029/444] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BE=D0=BF=D0=B5=D1=87=D0=B0=D1=82=D0=BA=D0=B8?= =?UTF-8?q?=20=D0=B8=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B8=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0=D0=BB=20=D1=84=D0=B0=D0=B9=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/contributing/Rules.md => CODE_OF_CONDUCT.md | 2 +- docs/contributing/index.md | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) rename docs/contributing/Rules.md => CODE_OF_CONDUCT.md (97%) diff --git a/docs/contributing/Rules.md b/CODE_OF_CONDUCT.md similarity index 97% rename from docs/contributing/Rules.md rename to CODE_OF_CONDUCT.md index 835abc2b414..1f0b73cdd8f 100644 --- a/docs/contributing/Rules.md +++ b/CODE_OF_CONDUCT.md @@ -28,7 +28,7 @@ ## Найдена ошибка, несоответствие, опечатка и т.д. Если вы нашли у нас ошибку - сообщите о ней. Хороший вариант - это оформить задачу в проекте на GitHub, идеальный - отправить следом PULL REQUEST с исправлением. -__УЖАСНЫЙ ВАРИАНТ__ - это просто кричать "у вас кругом одни баги", "все сыро и противно" и т.д. Кому вы помогли данным сообщением? Попытка понизить самооценку сообщества и мейнтенеров или самоутверждение за счет других? +__УЖАСНЫЙ ВАРИАНТ__ - это просто кричать "у вас кругом одни баги", "все сыро и противно" и т.д. Кому вы помогли данным сообщением? Попытка понизить самооценку сообщества и мейнтейнеров или самоутверждение за счет других? ## Общение diff --git a/docs/contributing/index.md b/docs/contributing/index.md index 00c7da45cac..f1ae581b385 100644 --- a/docs/contributing/index.md +++ b/docs/contributing/index.md @@ -2,8 +2,6 @@ В данном разделе собраны статьи, содержащие информацию для разработчиков диагностик и функциональности ядра. -[Необходимо прочитать в самом начале](Rules.md). - ## Инструкции - Старт From bbded4354da0b0e80b0545b11225141dff0c383c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BD=D1=82=D0=BE=D0=BD=20=D0=A1=D1=82=D0=B5=D0=BF?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Sun, 12 Apr 2020 14:12:46 +0300 Subject: [PATCH 030/444] =?UTF-8?q?Typo:=20=D0=9D=D0=BE=D0=B2=D1=8B=D0=B5?= =?UTF-8?q?=20=D1=81=D0=BB=D0=BE=D0=B2=D0=B0=20=D0=B2=20=D0=B8=D1=81=D0=BA?= =?UTF-8?q?=D0=BB=D1=8E=D1=87=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BF=D0=BE=20?= =?UTF-8?q?=D1=80=D0=B5=D0=B7=D1=83=D0=BB=D1=8C=D1=82=D0=B0=D1=82=D0=B0?= =?UTF-8?q?=D0=BC=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8=20?= =?UTF-8?q?=D0=91=D0=A1=D0=9F=20=D0=B8=20word?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../languageserver/diagnostics/TypoDiagnostic_ru.properties | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties index f509b23d925..ffebbb37879 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties @@ -9,6 +9,9 @@ diagnosticExceptions=Автогруппировку,Автозаголовок, ,Отсканированной,Офшоре,Офшоров,Парсер,Перезаполнить,Перезаполняемая,Перезаполняется,Перепроведение,Перепроведением\ ,Перепроведения,Повт,Подзапросы,Подпапки,Подредакции,Подредакции,Процессинговых,Псевдо,Рег,Регл,Резидентство\ ,Сворачиваемости,Сериализатор,Сис,Сконвертировать,Слеш,Слеша,Слеши,Стикера,Стр,Студотряде,Субконто,Таб,Техподдержки\ - ,Токене,Убыв,Физлица,Фич,Хэш,Штрихкодам,Штрихкодом,Штрихкоду + ,Токене,Убыв,Физлица,Фич,Хэш,Штрихкодам,Штрихкодом,Штрихкоду,Версионирования,Подредакция,Отсканированные\ + ,Финализировать,Стартован,Разыменователь,Сериализованный,Автоподбор,Подпапка,Видеозвонки,Десериализовать,Неполностью\ + ,Автогенерируемых,Несинхронизируемые,Тэгов,Тэги,Версионируемые,Неинтерактивном,Авторегистрация,Сериализованные\ + ,Транслите,Бухфон,Денормализовать,Перезаполнения,Подотчетнику,Непроведенных minWordLength=Минимальная длина проверяемых слов userWordsToIgnore=Пользовательский словарь исключений \ No newline at end of file From 68962726a3803c3a831cc69f4b2385b77578ab7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BD=D1=82=D0=BE=D0=BD=20=D0=A1=D1=82=D0=B5=D0=BF?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Sun, 12 Apr 2020 14:16:11 +0300 Subject: [PATCH 031/444] =?UTF-8?q?=20Typo:=20=D0=A1=D0=BE=D1=80=D1=82?= =?UTF-8?q?=D0=B8=D1=80=D0=BE=D0=B2=D0=BA=D0=B0=20=D1=81=D0=BB=D0=BE=D0=B2?= =?UTF-8?q?=20=D0=B2=20=D0=B8=D1=81=D0=BA=D0=BB=D1=8E=D1=87=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/TypoDiagnostic_ru.properties | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties index ffebbb37879..436fdec1ee9 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties @@ -1,17 +1,17 @@ diagnosticMessage=Возможная опечатка в "%s" diagnosticName=Опечатка diagnosticLanguage=ru -diagnosticExceptions=Автогруппировку,Автозаголовок,Автоиспользование,Автонастройка,Автонастройку,Автообновление,Автотест\ - ,Валидное,Валидные,Версионирование,Версионируемого,Версионируемый,Возр,Гант,Ганта,гггг,Гипер,Гиперссылкой,Гиперссылкой\ - ,Гиперссылку,Гиперссылок,Госрегулированием,Грейд,дд,Декомпозировать,Дозаполнить,Док,Дт,Журналирования,Зарплатных\ - ,Зацикленности,Знч,Исп,Коннект,Корсчета,Кт,Микропредприятий,Многострочность,Модифицированности,Модифицированность\ - ,Мульти,Неиспользующихся,Неодобренном,Неопределен,Неопределено,Непроведенный,Непройденные,Несырьевых,Однострочное\ - ,Отсканированной,Офшоре,Офшоров,Парсер,Перезаполнить,Перезаполняемая,Перезаполняется,Перепроведение,Перепроведением\ - ,Перепроведения,Повт,Подзапросы,Подпапки,Подредакции,Подредакции,Процессинговых,Псевдо,Рег,Регл,Резидентство\ - ,Сворачиваемости,Сериализатор,Сис,Сконвертировать,Слеш,Слеша,Слеши,Стикера,Стр,Студотряде,Субконто,Таб,Техподдержки\ - ,Токене,Убыв,Физлица,Фич,Хэш,Штрихкодам,Штрихкодом,Штрихкоду,Версионирования,Подредакция,Отсканированные\ - ,Финализировать,Стартован,Разыменователь,Сериализованный,Автоподбор,Подпапка,Видеозвонки,Десериализовать,Неполностью\ - ,Автогенерируемых,Несинхронизируемые,Тэгов,Тэги,Версионируемые,Неинтерактивном,Авторегистрация,Сериализованные\ - ,Транслите,Бухфон,Денормализовать,Перезаполнения,Подотчетнику,Непроведенных +diagnosticExceptions=Автогенерируемых,Автогруппировку,Автозаголовок,Автоиспользование,Автонастройка,Автонастройку\ + ,Автообновление,Автоподбор,Авторегистрация,Автотест,Бухфон,Валидное,Валидные,Версионирование,Версионирования\ + ,Версионируемого,Версионируемые,Версионируемый,Видеозвонки,Возр,Гант,Ганта,гггг,Гипер,Гиперссылкой,Гиперссылкой\ + ,Гиперссылку,Гиперссылок,Госрегулированием,Грейд,дд,Декомпозировать,Денормализовать,Десериализовать,Дозаполнить,Док\ + ,Дт,Журналирования,Зарплатных,Зацикленности,Знч,Исп,Коннект,Корсчета,Кт,Микропредприятий,Многострочность\ + ,Модифицированности,Модифицированность,Мульти,Неинтерактивном,Неиспользующихся,Неодобренном,Неопределен,Неопределено\ + ,Неполностью,Непроведенный,Непроведенных,Непройденные,Несинхронизируемые,Несырьевых,Однострочное,Отсканированной\ + ,Отсканированные,Офшоре,Офшоров,Парсер,Перезаполнения,Перезаполнить,Перезаполняемая,Перезаполняется,Перепроведение\ + ,Перепроведением,Перепроведения,Повт,Подзапросы,Подотчетнику,Подпапка,Подпапки,Подредакции,Подредакция\ + ,Процессинговых,Псевдо,Разыменователь,Рег,Регл,Резидентство,Сворачиваемости,Сериализатор,Сериализованные\ + ,Сериализованный,Сис,Сконвертировать,Слеш,Слеша,Слеши,Стартован,Стикера,Стр,Студотряде,Субконто,Таб,Техподдержки\ + ,Токене,Транслите,Тэги,Тэгов,Убыв,Физлица,Финализировать,Фич,Хэш,Штрихкодам,Штрихкодом,Штрихкоду minWordLength=Минимальная длина проверяемых слов userWordsToIgnore=Пользовательский словарь исключений \ No newline at end of file From 1b098633a22d772b5446ac16cfd2213ec1b69d94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BD=D1=82=D0=BE=D0=BD=20=D0=A1=D1=82=D0=B5=D0=BF?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Sun, 12 Apr 2020 14:33:38 +0300 Subject: [PATCH 032/444] =?UTF-8?q?=20Typo:=20fix=20#1024=20=D0=9A=D0=BE?= =?UTF-8?q?=D1=81=D1=82=D1=8B=D0=BB=D1=8C=20=D0=BD=D0=B0=20=D0=BF=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D1=83=20=D1=84=D0=BE=D1=80=D0=BC?= =?UTF-8?q?=D0=B0=D1=82=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D0=BD=D1=8B?= =?UTF-8?q?=D1=85=20=D1=81=D1=82=D1=80=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties index 436fdec1ee9..8643041577d 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties @@ -12,6 +12,6 @@ diagnosticExceptions=Автогенерируемых,Автогруппиров ,Перепроведением,Перепроведения,Повт,Подзапросы,Подотчетнику,Подпапка,Подпапки,Подредакции,Подредакция\ ,Процессинговых,Псевдо,Разыменователь,Рег,Регл,Резидентство,Сворачиваемости,Сериализатор,Сериализованные\ ,Сериализованный,Сис,Сконвертировать,Слеш,Слеша,Слеши,Стартован,Стикера,Стр,Студотряде,Субконто,Таб,Техподдержки\ - ,Токене,Транслите,Тэги,Тэгов,Убыв,Физлица,Финализировать,Фич,Хэш,Штрихкодам,Штрихкодом,Штрихкоду + ,Токене,Транслите,Тэги,Тэгов,Убыв,Физлица,Финализировать,Фич,Хэш,Штрихкодам,Штрихкодом,Штрихкоду,Мдд,Чммсс minWordLength=Минимальная длина проверяемых слов userWordsToIgnore=Пользовательский словарь исключений \ No newline at end of file From 3ee3d29bde7b7af69fbd88998703b46f6e7063cc Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Sun, 12 Apr 2020 18:41:07 +0300 Subject: [PATCH 033/444] =?UTF-8?q?=D1=83=D0=B1=D1=80=D0=B0=D0=BB=20=D0=BD?= =?UTF-8?q?=D0=B5=D0=BD=D1=83=D0=B6=D0=BD=D1=8B=D0=B9=20=D0=B4=D1=83=D0=B1?= =?UTF-8?q?=D0=BB=D1=8C=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8?= =?UTF-8?q?=20=D1=81=D1=82=D1=80=D0=BE=D0=BA=D0=B8=20=D0=BD=D0=B0=20=D1=80?= =?UTF-8?q?=D0=B5=D0=B3=D1=83=D0=BB=D1=8F=D1=80=D0=BA=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/UsingServiceTagDiagnostic.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingServiceTagDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingServiceTagDiagnostic.java index de655733b6d..ce939ebe99e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingServiceTagDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingServiceTagDiagnostic.java @@ -84,10 +84,11 @@ public List getDiagnostics(DocumentContext documentContext) { documentContext.getComments() .parallelStream() - .filter((Token token) -> pattern.matcher(token.getText()).find()) .forEach((Token token) -> { Matcher matcher = pattern.matcher(token.getText()); - matcher.find(); + if (!matcher.find()){ + return; + } diagnosticStorage.addDiagnostic( token, info.getMessage(matcher.group(0)) From 41ab8db11faab8c8abfa6fbbae3141fe7c35098b Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Fri, 10 Apr 2020 13:13:52 +0300 Subject: [PATCH 034/444] Fix qf --- .../codeactions/FixAllCodeActionSupplier.java | 1 - .../codeactions/QuickFixCodeActionSupplier.java | 1 - .../languageserver/codeactions/QuickFixSupplier.java | 2 +- .../bsl/languageserver/context/ServerContext.java | 2 +- .../languageserver/context/symbol/RegionSymbol.java | 2 +- .../diagnostics/CodeBlockBeforeSubDiagnostic.java | 2 +- .../diagnostics/CodeOutOfRegionDiagnostic.java | 2 +- .../diagnostics/DeprecatedCurrentDateDiagnostic.java | 8 -------- .../DeprecatedTypeManagedFormDiagnostic.java | 2 +- .../NestedFunctionInParametersDiagnostic.java | 2 +- .../NonExportMethodsInApiRegionDiagnostic.java | 10 +++++----- .../PublicMethodsDescriptionDiagnostic.java | 8 ++++---- .../_1c_syntax/bsl/languageserver/utils/Trees.java | 2 +- .../bsl/languageserver/context/ServerContextTest.java | 2 +- 14 files changed, 18 insertions(+), 28 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/FixAllCodeActionSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/FixAllCodeActionSupplier.java index fd9ce04373e..0394301a8db 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/FixAllCodeActionSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/FixAllCodeActionSupplier.java @@ -23,7 +23,6 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.diagnostics.QuickFixProvider; -import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCode; import com.github._1c_syntax.bsl.languageserver.providers.DiagnosticProvider; import org.eclipse.lsp4j.CodeAction; import org.eclipse.lsp4j.CodeActionContext; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixCodeActionSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixCodeActionSupplier.java index 6957d90a416..7e7d4b66cef 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixCodeActionSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixCodeActionSupplier.java @@ -23,7 +23,6 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.diagnostics.QuickFixProvider; -import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCode; import com.github._1c_syntax.bsl.languageserver.providers.DiagnosticProvider; import org.eclipse.lsp4j.CodeAction; import org.eclipse.lsp4j.CodeActionParams; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixSupplier.java index ca5965a901c..70baa1ee611 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixSupplier.java @@ -51,7 +51,7 @@ public List> getQuickFixClasses() { } @SuppressWarnings("unchecked") - public > Optional> getQuickFixClass( + public > Optional> getQuickFixClass( T diagnosticCode ) { Optional> diagnosticClass = diagnosticSupplier.getDiagnosticClass(diagnosticCode); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java index a57bf406820..d4b62c01410 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java @@ -21,9 +21,9 @@ */ package com.github._1c_syntax.bsl.languageserver.context; +import com.github._1c_syntax.mdclasses.metadata.Configuration; import com.github._1c_syntax.utils.Absolute; import com.github._1c_syntax.utils.Lazy; -import com.github._1c_syntax.mdclasses.metadata.Configuration; import org.eclipse.lsp4j.TextDocumentItem; import javax.annotation.CheckForNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/RegionSymbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/RegionSymbol.java index 08fadc6d084..0b0ac4847ac 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/RegionSymbol.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/RegionSymbol.java @@ -60,7 +60,7 @@ public class RegionSymbol implements Symbol { @NonFinal @Builder.Default // TODO подумать, как избавиться от этого - List nodes = new ArrayList<>(); + List nodes = new ArrayList<>(); @Override public void clearParseTreeData() { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeBlockBeforeSubDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeBlockBeforeSubDiagnostic.java index b40db6ce401..3bd7d47f249 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeBlockBeforeSubDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeBlockBeforeSubDiagnostic.java @@ -45,7 +45,7 @@ public CodeBlockBeforeSubDiagnostic(DiagnosticInfo info) { @Override public ParseTree visitFileCodeBlockBeforeSub(BSLParser.FileCodeBlockBeforeSubContext ctx) { // todo надо править парсер ибо данный узел есть даже когда его нет. ниже попытка обойти это - if(!ctx.getTokens().isEmpty()) { + if (!ctx.getTokens().isEmpty()) { diagnosticStorage.addDiagnostic(ctx); } return ctx; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnostic.java index b9d5078a4c4..f4446e229f1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnostic.java @@ -71,7 +71,7 @@ public ParseTree visitFile(BSLParser.FileContext ctx) { if (regions.isEmpty() && !ctx.getTokens().isEmpty()) { List relatedInformation = createRelatedInformations(ctx); - if(!relatedInformation.isEmpty()) { + if (!relatedInformation.isEmpty()) { diagnosticStorage.addDiagnostic( relatedInformation.get(0).getLocation().getRange(), relatedInformation); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic.java index 1695355841f..35224ae62e1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic.java @@ -21,22 +21,14 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; -import com.github._1c_syntax.bsl.languageserver.providers.CodeActionProvider; import com.github._1c_syntax.bsl.parser.BSLParser; -import org.eclipse.lsp4j.CodeAction; -import org.eclipse.lsp4j.CodeActionParams; -import org.eclipse.lsp4j.Diagnostic; -import org.eclipse.lsp4j.TextEdit; -import java.util.ArrayList; -import java.util.List; import java.util.regex.Pattern; @DiagnosticMetadata( diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedTypeManagedFormDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedTypeManagedFormDiagnostic.java index 49f763e0697..e7c99c9f14a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedTypeManagedFormDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedTypeManagedFormDiagnostic.java @@ -70,7 +70,7 @@ public DeprecatedTypeManagedFormDiagnostic(DiagnosticInfo info) { } @Override - public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx ) { + public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { Optional.of(ctx) .filter(it -> methodPattern.matcher(it.methodName().getText()).matches()) .map(BSLParser.GlobalMethodCallContext::doCall) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedFunctionInParametersDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedFunctionInParametersDiagnostic.java index 254f980673d..abfacd3a5e1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedFunctionInParametersDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedFunctionInParametersDiagnostic.java @@ -62,7 +62,7 @@ public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { public ParseTree visitNewExpression(BSLParser.NewExpressionContext ctx) { if (findNestedCall(ctx, ctx.doCall())) { - if(ctx.typeName() != null) { + if (ctx.typeName() != null) { diagnosticStorage.addDiagnostic( ctx.typeName(), info.getMessage( diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonExportMethodsInApiRegionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonExportMethodsInApiRegionDiagnostic.java index 44e3d342156..0e7e897d1c8 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonExportMethodsInApiRegionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonExportMethodsInApiRegionDiagnostic.java @@ -61,11 +61,11 @@ public ParseTree visitSub(BSLParser.SubContext ctx) { } methodSymbol.getRootParent().ifPresent((Symbol rootRegion) -> { - if (REGION_NAME.matcher(rootRegion.getName()).matches()) { - String message = info.getMessage(methodSymbol.getName(), rootRegion.getName()); - diagnosticStorage.addDiagnostic(methodSymbol.getSubNameRange(), message); - } - }); + if (REGION_NAME.matcher(rootRegion.getName()).matches()) { + String message = info.getMessage(methodSymbol.getName(), rootRegion.getName()); + diagnosticStorage.addDiagnostic(methodSymbol.getSubNameRange(), message); + } + }); }); return ctx; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PublicMethodsDescriptionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PublicMethodsDescriptionDiagnostic.java index 6f284f0b808..ebdaa24274e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PublicMethodsDescriptionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PublicMethodsDescriptionDiagnostic.java @@ -73,10 +73,10 @@ public ParseTree visitSub(BSLParser.SubContext ctx) { diagnosticStorage.addDiagnostic(methodSymbol.getSubNameRange()); } else { methodSymbol.getRootParent().ifPresent((Symbol rootRegion) -> { - if (isAPIRegion(rootRegion)) { - diagnosticStorage.addDiagnostic(methodSymbol.getSubNameRange()); - } - }); + if (isAPIRegion(rootRegion)) { + diagnosticStorage.addDiagnostic(methodSymbol.getSubNameRange()); + } + }); } } }); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java index aabb6ee8325..2ce462cf19e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java @@ -291,7 +291,7 @@ public static boolean nodeContains(ParseTree t, ParseTree exclude, Integer... in /** * @param tokens - список токенов из DocumentContext - * @param token - токен, на строке которого требуется найти висячий комментарий + * @param token - токен, на строке которого требуется найти висячий комментарий * @return - токен с комментарием, если он найден */ public static Optional getTrailingComment(List tokens, Token token) { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java index 19688e14cd6..515eb9aa948 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java @@ -21,11 +21,11 @@ */ package com.github._1c_syntax.bsl.languageserver.context; -import com.github._1c_syntax.utils.Absolute; import com.github._1c_syntax.mdclasses.metadata.Configuration; import com.github._1c_syntax.mdclasses.metadata.additional.ConfigurationSource; import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; import com.github._1c_syntax.mdclasses.metadata.additional.ScriptVariant; +import com.github._1c_syntax.utils.Absolute; import org.junit.jupiter.api.Test; import java.io.File; From 34f7eba47d4d46ef96c41751cebaacac30c9e868 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Mon, 13 Apr 2020 11:06:30 +0300 Subject: [PATCH 035/444] =?UTF-8?q?Fix=20#1047.=20=D0=98=D1=81=D0=BF=D1=80?= =?UTF-8?q?=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D1=8B=20=D1=81=D1=81=D1=8B=D0=BB?= =?UTF-8?q?=D0=BA=D0=B8=20=D0=B2=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/FunctionNameStartsWithGet.md | 2 +- docs/en/diagnostics/FunctionNameStartsWithGet.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/diagnostics/FunctionNameStartsWithGet.md b/docs/diagnostics/FunctionNameStartsWithGet.md index ac1bc0668d0..4abe3f01a51 100644 --- a/docs/diagnostics/FunctionNameStartsWithGet.md +++ b/docs/diagnostics/FunctionNameStartsWithGet.md @@ -20,7 +20,7 @@ ## Источники -* Источник: [Стандарт: Имена процедур и функций п 6.1](its.1c.ru/db/v8std#content:647:hdoc) +* Источник: [Стандарт: Имена процедур и функций п 6.1](https://its.1c.ru/db/v8std#content:647:hdoc) ## Сниппеты diff --git a/docs/en/diagnostics/FunctionNameStartsWithGet.md b/docs/en/diagnostics/FunctionNameStartsWithGet.md index dc14ff7f1ce..53d9a95356e 100644 --- a/docs/en/diagnostics/FunctionNameStartsWithGet.md +++ b/docs/en/diagnostics/FunctionNameStartsWithGet.md @@ -18,7 +18,7 @@ Function NameByCode() ``` ## Sources -* Source: [Standard: Names of procedures and functions c 6.1](its.1c.ru/db/v8std#content:647:hdoc) +* Source: [Standard: Names of procedures and functions c 6.1](https://its.1c.ru/db/v8std#content:647:hdoc) ## Snippets From f2ce76727ce3431591fe29658eb2294284cf5e41 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Mon, 13 Apr 2020 11:10:02 +0300 Subject: [PATCH 036/444] Fix qf --- .../bsl/languageserver/BSLLSPLauncher.java | 2 +- .../bsl/languageserver/BSLLanguageServer.java | 6 ++-- .../languageserver/BSLWorkspaceService.java | 2 +- .../languageserver/cli/AnalyzeCommand.java | 2 +- .../bsl/languageserver/cli/FormatCommand.java | 4 +-- .../cli/LanguageServerStartCommand.java | 2 +- .../context/DocumentContext.java | 20 +++++------ .../computer/CognitiveComplexityComputer.java | 8 ++--- .../context/computer/ComplexityData.java | 10 +++--- .../computer/ComplexitySecondaryLocation.java | 4 +-- .../CyclomaticComplexityComputer.java | 6 ++-- .../computer/DiagnosticIgnoranceComputer.java | 4 +-- .../computer/MethodSymbolComputer.java | 2 +- .../computer/RegionSymbolComputer.java | 6 ++-- .../context/computer/SymbolTreeComputer.java | 2 +- .../computer/VariableSymbolComputer.java | 2 +- .../languageserver/context/symbol/Symbol.java | 6 ++-- .../diagnostics/AbstractDiagnostic.java | 2 +- .../AbstractListenerDiagnostic.java | 2 +- .../AbstractVisitorDiagnostic.java | 2 +- .../CanonicalSpellingKeywordsDiagnostic.java | 4 +-- .../CodeOutOfRegionDiagnostic.java | 2 +- .../CreateQueryInCycleDiagnostic.java | 8 ++--- .../DeprecatedTypeManagedFormDiagnostic.java | 2 +- .../diagnostics/DiagnosticStorage.java | 4 +-- .../diagnostics/DiagnosticSupplier.java | 2 +- .../IfElseDuplicatedCodeBlockDiagnostic.java | 2 +- .../IfElseDuplicatedConditionDiagnostic.java | 2 +- .../diagnostics/LineLengthDiagnostic.java | 2 +- .../diagnostics/MissingSpaceDiagnostic.java | 2 +- ...issingTemporaryFileDeletionDiagnostic.java | 2 +- .../NestedStatementsDiagnostic.java | 2 +- .../OneStatementPerLineDiagnostic.java | 2 +- .../PairingBrokenTransactionDiagnostic.java | 10 +++--- .../SpaceAtStartCommentDiagnostic.java | 9 +++-- .../UnreachableCodeDiagnostic.java | 4 +-- .../UsingFindElementByStringDiagnostic.java | 2 +- .../UsingModalWindowsDiagnostic.java | 4 +-- .../UsingSynchronousCallsDiagnostic.java | 2 +- .../diagnostics/YoLetterUsageDiagnostic.java | 2 +- .../metadata/DiagnosticCompatibilityMode.java | 2 +- .../diagnostics/metadata/DiagnosticInfo.java | 6 ++-- .../reporter/GenericIssueReport.java | 36 +++++++++---------- .../diagnostics/reporter/JUnitTestSuites.java | 16 ++++----- .../reporter/TSLintReportEntry.java | 2 +- .../diagnostics/typo/JLanguageToolPool.java | 2 +- .../providers/FoldingRangeProvider.java | 10 +++--- .../utils/AbstractObjectPool.java | 4 +-- .../utils/MultilingualStringAnalyser.java | 4 +-- .../MethodSizeDiagnostic_en.properties | 2 +- .../MissingSpaceDiagnostic_en.properties | 2 -- .../MissingSpaceDiagnostic_ru.properties | 2 -- .../NonStandardRegionDiagnostic_ru.properties | 2 +- ...ngSynchronousCallsDiagnostic_en.properties | 2 +- .../BSLTextDocumentServiceTest.java | 2 +- .../reporter/GenericReporterTest.java | 2 +- .../reporter/JUnitReporterTest.java | 2 +- .../reporter/JsonReporterTest.java | 2 +- .../reporter/TSLintReporterTest.java | 2 +- 59 files changed, 130 insertions(+), 135 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java index 6fab3f12b86..ec17fdea384 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java @@ -40,7 +40,7 @@ public class BSLLSPLauncher { public static final String APP_NAME = "BSL language server"; - private static Options options = createOptions(); + private static final Options options = createOptions(); public static void main(String[] args) { CommandLineParser parser = new DefaultParser(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServer.java index b3810b6ebb7..24e77222dc7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServer.java @@ -46,10 +46,10 @@ public class BSLLanguageServer implements LanguageServer, LanguageClientAware { private final LanguageServerConfiguration configuration; - private BSLTextDocumentService textDocumentService; - private BSLWorkspaceService workspaceService; + private final BSLTextDocumentService textDocumentService; + private final BSLWorkspaceService workspaceService; private boolean shutdownWasCalled; - private ServerContext context; + private final ServerContext context; public BSLLanguageServer(LanguageServerConfiguration configuration) { this.configuration = configuration; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLWorkspaceService.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLWorkspaceService.java index 6f46da62742..a977efb5f49 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLWorkspaceService.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLWorkspaceService.java @@ -35,7 +35,7 @@ public class BSLWorkspaceService implements WorkspaceService { - private LanguageServerConfiguration configuration; + private final LanguageServerConfiguration configuration; public BSLWorkspaceService(LanguageServerConfiguration configuration) { this.configuration = configuration; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java index 9629f8a9930..d59471edc28 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java @@ -70,7 +70,7 @@ */ public class AnalyzeCommand implements Command { - private CommandLine cmd; + private final CommandLine cmd; private DiagnosticProvider diagnosticProvider; private ServerContext context; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java index e2b84b52990..a622840df1d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java @@ -56,8 +56,8 @@ */ public class FormatCommand implements Command { - private CommandLine cmd; - private ServerContext serverContext; + private final CommandLine cmd; + private final ServerContext serverContext; public FormatCommand(CommandLine cmd) { this.cmd = cmd; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java index d4fb32ca6d5..d75ada08096 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java @@ -53,7 +53,7 @@ @Slf4j public class LanguageServerStartCommand implements Command { - private CommandLine cmd; + private final CommandLine cmd; public LanguageServerStartCommand(CommandLine cmd) { this.cmd = cmd; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java index 10b5b4a5237..3b9fa8c6823 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java @@ -62,23 +62,23 @@ public class DocumentContext { private final URI uri; private final FileType fileType; private String content; - private ServerContext context; + private final ServerContext context; private Tokenizer tokenizer; - private ReentrantLock computeLock = new ReentrantLock(); + private final ReentrantLock computeLock = new ReentrantLock(); - private Lazy contentList = new Lazy<>(this::computeContentList, computeLock); - private Lazy moduleType = new Lazy<>(this::computeModuleType, computeLock); - private Lazy> supportVariants + private final Lazy contentList = new Lazy<>(this::computeContentList, computeLock); + private final Lazy moduleType = new Lazy<>(this::computeModuleType, computeLock); + private final Lazy> supportVariants = new Lazy<>(this::computeSupportVariants, computeLock); - private Lazy symbolTree = new Lazy<>(this::computeSymbolTree, computeLock); - private Lazy cognitiveComplexityData + private final Lazy symbolTree = new Lazy<>(this::computeSymbolTree, computeLock); + private final Lazy cognitiveComplexityData = new Lazy<>(this::computeCognitiveComplexity, computeLock); - private Lazy cyclomaticComplexityData + private final Lazy cyclomaticComplexityData = new Lazy<>(this::computeCyclomaticComplexity, computeLock); - private Lazy diagnosticIgnoranceData + private final Lazy diagnosticIgnoranceData = new Lazy<>(this::computeDiagnosticIgnorance, computeLock); - private Lazy metrics = new Lazy<>(this::computeMetrics, computeLock); + private final Lazy metrics = new Lazy<>(this::computeMetrics, computeLock); public DocumentContext(URI uri, String content, ServerContext context) { this.uri = Absolute.uri(uri); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CognitiveComplexityComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CognitiveComplexityComputer.java index a3db366cf42..66b0bd94d9f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CognitiveComplexityComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CognitiveComplexityComputer.java @@ -52,15 +52,15 @@ public class CognitiveComplexityComputer private int fileComplexity; private int fileCodeBlockComplexity; - private List fileBlockComplexitySecondaryLocations; + private final List fileBlockComplexitySecondaryLocations; - private Map methodsComplexity; - private Map> methodsComplexitySecondaryLocations; + private final Map methodsComplexity; + private final Map> methodsComplexitySecondaryLocations; private MethodSymbol currentMethod; private int complexity; private int nestedLevel; - private Set ignoredContexts; + private final Set ignoredContexts; public CognitiveComplexityComputer(DocumentContext documentContext) { this.documentContext = documentContext; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ComplexityData.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ComplexityData.java index 463b1c323b5..e3641c087f0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ComplexityData.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ComplexityData.java @@ -31,10 +31,10 @@ @Value @AllArgsConstructor public class ComplexityData { - private final int fileComplexity; - private final int fileCodeBlockComplexity; - private List fileBlockComplexitySecondaryLocations; + int fileComplexity; + int fileCodeBlockComplexity; + List fileBlockComplexitySecondaryLocations; - private final Map methodsComplexity; - private Map> methodsComplexitySecondaryLocations; + Map methodsComplexity; + Map> methodsComplexitySecondaryLocations; } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ComplexitySecondaryLocation.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ComplexitySecondaryLocation.java index 31fbfb1aa78..1d25863ffb2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ComplexitySecondaryLocation.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ComplexitySecondaryLocation.java @@ -28,6 +28,6 @@ @Value @AllArgsConstructor public class ComplexitySecondaryLocation { - private final Range range; - private final String message; + Range range; + String message; } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CyclomaticComplexityComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CyclomaticComplexityComputer.java index eb607701023..beb91400c64 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CyclomaticComplexityComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CyclomaticComplexityComputer.java @@ -49,10 +49,10 @@ public class CyclomaticComplexityComputer private int fileComplexity; private int fileCodeBlockComplexity; - private List fileBlockComplexitySecondaryLocations; + private final List fileBlockComplexitySecondaryLocations; - private Map methodsComplexity; - private Map> methodsComplexitySecondaryLocations; + private final Map methodsComplexity; + private final Map> methodsComplexitySecondaryLocations; private MethodSymbol currentMethod; private int complexity; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/DiagnosticIgnoranceComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/DiagnosticIgnoranceComputer.java index 39c66af9160..e04f9527a64 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/DiagnosticIgnoranceComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/DiagnosticIgnoranceComputer.java @@ -64,8 +64,8 @@ public class DiagnosticIgnoranceComputer implements Computer>> diagnosticIgnorance = new HashMap<>(); - private Map> ignoranceStack = new HashMap<>(); + private final Map>> diagnosticIgnorance = new HashMap<>(); + private final Map> ignoranceStack = new HashMap<>(); public DiagnosticIgnoranceComputer(DocumentContext documentContext) { this.documentContext = documentContext; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java index 73f5ccab7a1..b90fd7c323f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java @@ -46,7 +46,7 @@ public final class MethodSymbolComputer implements Computer> { private final DocumentContext documentContext; - private List methods = new ArrayList<>(); + private final List methods = new ArrayList<>(); public MethodSymbolComputer(DocumentContext documentContext) { this.documentContext = documentContext; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/RegionSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/RegionSymbolComputer.java index 2416a190586..b0179f21738 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/RegionSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/RegionSymbolComputer.java @@ -43,9 +43,9 @@ public final class RegionSymbolComputer implements Computer> { private final DocumentContext documentContext; - private Deque> regionStack = new ArrayDeque<>(); - private List regions = new ArrayList<>(); - private List allNodes = new ArrayList<>(); + private final Deque> regionStack = new ArrayDeque<>(); + private final List regions = new ArrayList<>(); + private final List allNodes = new ArrayList<>(); public RegionSymbolComputer(DocumentContext documentContext) { this.documentContext = documentContext; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/SymbolTreeComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/SymbolTreeComputer.java index 87aa63e994b..78d5008ddd9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/SymbolTreeComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/SymbolTreeComputer.java @@ -36,7 +36,7 @@ public class SymbolTreeComputer implements Computer { - private DocumentContext documentContext; + private final DocumentContext documentContext; public SymbolTreeComputer(DocumentContext documentContext) { this.documentContext = documentContext; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java index d17795f8005..31d46a950ad 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java @@ -40,7 +40,7 @@ public class VariableSymbolComputer extends BSLParserBaseVisitor implements Computer> { private final DocumentContext documentContext; - private List variables = new ArrayList<>(); + private final List variables = new ArrayList<>(); public VariableSymbolComputer(DocumentContext documentContext) { this.documentContext = documentContext; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Symbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Symbol.java index 07d04287b65..87638ac472e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Symbol.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Symbol.java @@ -50,10 +50,10 @@ default Optional getRootParent() { static Symbol emptySymbol() { return new Symbol() { - @Getter private String name = "empty"; - @Getter private Range range = Ranges.create(-1, 0, -1, 0); + @Getter private final String name = "empty"; + @Getter private final Range range = Ranges.create(-1, 0, -1, 0); @Getter @Setter private Optional parent = Optional.empty(); - @Getter private List children = Collections.emptyList(); + @Getter private final List children = Collections.emptyList(); }; } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractDiagnostic.java index 8a64b2ba232..f175f8a24ad 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractDiagnostic.java @@ -30,7 +30,7 @@ public abstract class AbstractDiagnostic implements BSLDiagnostic { protected final DiagnosticInfo info; - protected DiagnosticStorage diagnosticStorage = new DiagnosticStorage(this); + protected final DiagnosticStorage diagnosticStorage = new DiagnosticStorage(this); public AbstractDiagnostic(DiagnosticInfo info) { this.info = info; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractListenerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractListenerDiagnostic.java index 1c1cb8a45f4..ba2b33da4d4 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractListenerDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractListenerDiagnostic.java @@ -32,7 +32,7 @@ public abstract class AbstractListenerDiagnostic extends BSLParserBaseListener implements BSLDiagnostic { protected final DiagnosticInfo info; - protected DiagnosticStorage diagnosticStorage = new DiagnosticStorage(this); + protected final DiagnosticStorage diagnosticStorage = new DiagnosticStorage(this); protected DocumentContext documentContext; public AbstractListenerDiagnostic(DiagnosticInfo info) { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java index af11457eee2..4965869e53b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java @@ -32,7 +32,7 @@ public abstract class AbstractVisitorDiagnostic extends BSLParserBaseVisitor implements BSLDiagnostic { protected final DiagnosticInfo info; - protected DiagnosticStorage diagnosticStorage = new DiagnosticStorage(this); + protected final DiagnosticStorage diagnosticStorage = new DiagnosticStorage(this); protected DocumentContext documentContext; public AbstractVisitorDiagnostic(DiagnosticInfo info) { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CanonicalSpellingKeywordsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CanonicalSpellingKeywordsDiagnostic.java index bf452db42f7..42f63ed8678 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CanonicalSpellingKeywordsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CanonicalSpellingKeywordsDiagnostic.java @@ -53,8 +53,8 @@ ) public class CanonicalSpellingKeywordsDiagnostic extends AbstractDiagnostic implements QuickFixProvider { - private static Map> canonicalKeywords = getPreset(); - private static Map canonicalStrings = getCanonical(); + private static final Map> canonicalKeywords = getPreset(); + private static final Map canonicalStrings = getCanonical(); public CanonicalSpellingKeywordsDiagnostic(DiagnosticInfo info) { super(info); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnostic.java index f4446e229f1..f0f4fe73874 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnostic.java @@ -56,7 +56,7 @@ compatibilityMode = DiagnosticCompatibilityMode.COMPATIBILITY_MODE_8_3_1 ) public class CodeOutOfRegionDiagnostic extends AbstractVisitorDiagnostic { - private List regionsRanges = new ArrayList<>(); + private final List regionsRanges = new ArrayList<>(); public CodeOutOfRegionDiagnostic(DiagnosticInfo info) { super(info); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java index 7b0a2a1c53f..8c8ad3da753 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java @@ -302,8 +302,8 @@ public enum CodeFlowType { @ToString public static class VariableDefinition { - private String variableName; - private Set types = new HashSet<>(); + private final String variableName; + private final Set types = new HashSet<>(); private ParseTree firstDeclaration; VariableDefinition(String variableName) { @@ -324,7 +324,7 @@ public void addDeclaration(ParseTree firstDeclaration) { private static class Scope { private final String name; - private HashMap variables = new HashMap<>(); + private final HashMap variables = new HashMap<>(); public Scope(String name) { this.name = name; @@ -350,7 +350,7 @@ public String getName() { } private static class VariableScope extends ArrayDeque { - private Deque flowMode = new ArrayDeque<>(); + private final Deque flowMode = new ArrayDeque<>(); public boolean codeFlowInCycle() { final CodeFlowType flowType = flowMode.peek(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedTypeManagedFormDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedTypeManagedFormDiagnostic.java index e7c99c9f14a..d02c3690f45 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedTypeManagedFormDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedTypeManagedFormDiagnostic.java @@ -76,7 +76,7 @@ public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { .map(BSLParser.GlobalMethodCallContext::doCall) .map(BSLParser.DoCallContext::callParamList) .filter(callParamList -> paramPattern.matcher(callParamList.getText()).matches()) - .ifPresent(callParamList -> diagnosticStorage.addDiagnostic(callParamList)); + .ifPresent(diagnosticStorage::addDiagnostic); return super.visitGlobalMethodCall(ctx); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java index bf5fd1f7442..945505942b0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java @@ -39,8 +39,8 @@ public class DiagnosticStorage { - private BSLDiagnostic diagnostic; - private Queue diagnosticList = new ConcurrentLinkedQueue<>(); + private final BSLDiagnostic diagnostic; + private final Queue diagnosticList = new ConcurrentLinkedQueue<>(); DiagnosticStorage(BSLDiagnostic diagnostic) { this.diagnostic = diagnostic; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java index 3e5f62f57ee..31eb9c99ea3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java @@ -52,7 +52,7 @@ public class DiagnosticSupplier { private final LanguageServerConfiguration configuration; - private static List> diagnosticClasses = createDiagnosticClasses(); + private static final List> diagnosticClasses = createDiagnosticClasses(); public DiagnosticSupplier(LanguageServerConfiguration configuration) { this.configuration = configuration; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedCodeBlockDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedCodeBlockDiagnostic.java index dc99d4503dc..9f887ab6d03 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedCodeBlockDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedCodeBlockDiagnostic.java @@ -53,7 +53,7 @@ public class IfElseDuplicatedCodeBlockDiagnostic extends AbstractVisitorDiagnostic { private final String relatedMessage; - private Set checkedBlocks = new HashSet<>(); + private final Set checkedBlocks = new HashSet<>(); public IfElseDuplicatedCodeBlockDiagnostic(DiagnosticInfo info) { super(info); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedConditionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedConditionDiagnostic.java index e9f4be9ced6..a76524e8c4e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedConditionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedConditionDiagnostic.java @@ -53,7 +53,7 @@ public class IfElseDuplicatedConditionDiagnostic extends AbstractVisitorDiagnostic { private final String relatedMessage; - private Set checkedConditions = new HashSet<>(); + private final Set checkedConditions = new HashSet<>(); public IfElseDuplicatedConditionDiagnostic(DiagnosticInfo info) { super(info); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LineLengthDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LineLengthDiagnostic.java index 15dc31dcafc..b4c4b1a6f11 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LineLengthDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LineLengthDiagnostic.java @@ -56,7 +56,7 @@ public class LineLengthDiagnostic extends AbstractDiagnostic { defaultValue = "" + MAX_LINE_LENGTH ) private int maxLineLength = MAX_LINE_LENGTH; - private Map> tokensInOneLine = new HashMap<>(); + private final Map> tokensInOneLine = new HashMap<>(); public LineLengthDiagnostic(DiagnosticInfo info) { super(info); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnostic.java index 7338e64b072..68f49db782b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnostic.java @@ -107,7 +107,7 @@ public class MissingSpaceDiagnostic extends AbstractVisitorDiagnostic implements private Pattern patternL = compilePattern(listForCheckLeft); private Pattern patternR = compilePattern(listForCheckRight); private Pattern patternLr = compilePattern(listForCheckLeftAndRight); - private Pattern patternNotSpace = compilePattern("\\S+"); + private final Pattern patternNotSpace = compilePattern("\\S+"); public MissingSpaceDiagnostic(DiagnosticInfo info) { super(info); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTemporaryFileDeletionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTemporaryFileDeletionDiagnostic.java index 86de04d471c..28df878d75c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTemporaryFileDeletionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTemporaryFileDeletionDiagnostic.java @@ -133,7 +133,7 @@ private boolean foundDeleteFile(BSLParser.CodeBlockContext codeBlockContext, Str BSLParser.GlobalMethodCallContext localGlobalMethodCall = localCallStatementContext.globalMethodCall(); // получаем full call method и полное имя вызова - String fullCallMethod = ""; + String fullCallMethod; BSLParser.DoCallContext doCallContext; if (localGlobalMethodCall == null) { fullCallMethod = getFullCallMethod(localCallStatementContext); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedStatementsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedStatementsDiagnostic.java index 6c7bbc015d7..40d63921c47 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedStatementsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedStatementsDiagnostic.java @@ -64,7 +64,7 @@ public class NestedStatementsDiagnostic extends AbstractListenerDiagnostic { private int maxAllowedLevel = MAX_ALLOWED_LEVEL; private ParseTree lastCtx; - private Deque nestedParents = new ArrayDeque<>(); + private final Deque nestedParents = new ArrayDeque<>(); public NestedStatementsDiagnostic(DiagnosticInfo info) { super(info); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OneStatementPerLineDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OneStatementPerLineDiagnostic.java index 7a8400c30c0..9117679f4cc 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OneStatementPerLineDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OneStatementPerLineDiagnostic.java @@ -59,7 +59,7 @@ public class OneStatementPerLineDiagnostic extends AbstractVisitorDiagnostic imp "^(\\s+?)[^\\s]", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private int previousLineNumber; - private List statementsPerLine = new ArrayList<>(); + private final List statementsPerLine = new ArrayList<>(); public OneStatementPerLineDiagnostic(DiagnosticInfo info) { super(info); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PairingBrokenTransactionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PairingBrokenTransactionDiagnostic.java index d24a798bec3..abff7294f17 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PairingBrokenTransactionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PairingBrokenTransactionDiagnostic.java @@ -47,19 +47,19 @@ ) public class PairingBrokenTransactionDiagnostic extends AbstractVisitorDiagnostic { - private Pattern beginTransaction = Pattern.compile("НачатьТранзакцию|BeginTransaction", + private final Pattern beginTransaction = Pattern.compile("НачатьТранзакцию|BeginTransaction", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); - private Pattern beginEndTransaction = Pattern.compile( + private final Pattern beginEndTransaction = Pattern.compile( "ЗафиксироватьТранзакцию|CommitTransaction|НачатьТранзакцию|BeginTransaction", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); - private Pattern beginCancelTransaction = Pattern.compile( + private final Pattern beginCancelTransaction = Pattern.compile( "ОтменитьТранзакцию|RollbackTransaction|НачатьТранзакцию|BeginTransaction", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); - private HashMap pairMethodsBeginEnd = new HashMap<>(); - private HashMap pairMethodsBeginCancel = new HashMap<>(); + private final HashMap pairMethodsBeginEnd = new HashMap<>(); + private final HashMap pairMethodsBeginCancel = new HashMap<>(); public PairingBrokenTransactionDiagnostic(DiagnosticInfo info) { super(info); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SpaceAtStartCommentDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SpaceAtStartCommentDiagnostic.java index d68082a5247..4151a662d2b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SpaceAtStartCommentDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SpaceAtStartCommentDiagnostic.java @@ -63,9 +63,9 @@ public class SpaceAtStartCommentDiagnostic implements QuickFixProvider, BSLDiagn private static final int COMMENT_LENGTH = 2; private static final float COMMENTED_CODE_THRESHOLD = 0.9F; - protected DiagnosticStorage diagnosticStorage = new DiagnosticStorage(this); - private CodeRecognizer codeRecognizer; - private DiagnosticInfo info; + protected final DiagnosticStorage diagnosticStorage = new DiagnosticStorage(this); + private final CodeRecognizer codeRecognizer; + private final DiagnosticInfo info; @DiagnosticParameter( type = String.class, @@ -113,8 +113,7 @@ public List getDiagnostics(DocumentContext documentContext) { && !commentsAnnotation.matcher(t.getText()).matches() && !codeRecognizer.meetsCondition(t.getText())) .sequential() - .forEach((Token t) -> - diagnosticStorage.addDiagnostic(t)); + .forEach(diagnosticStorage::addDiagnostic); return diagnosticStorage.getDiagnostics(); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnostic.java index f4e9e2b1291..4d245a1a155 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnostic.java @@ -54,10 +54,10 @@ public class UnreachableCodeDiagnostic extends AbstractVisitorDiagnostic { // кэш диапазонов зарегистрированных ошибок - private List errorRanges = new ArrayList<>(); + private final List errorRanges = new ArrayList<>(); // диапазоны препроцессорных скобок - private List preprocessorRanges = new ArrayList<>(); + private final List preprocessorRanges = new ArrayList<>(); public UnreachableCodeDiagnostic(DiagnosticInfo info) { super(info); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnostic.java index 001cbdaef98..f071145c91d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnostic.java @@ -47,7 +47,7 @@ public class UsingFindElementByStringDiagnostic extends AbstractVisitorDiagnostic { - private Pattern pattern = Pattern.compile( + private final Pattern pattern = Pattern.compile( "(НайтиПоНаименованию|FindByDescription|НайтиПоКоду|FindByCode)", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnostic.java index 4d2ead6fa4b..ebc25f7e5e2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnostic.java @@ -46,7 +46,7 @@ ) public class UsingModalWindowsDiagnostic extends AbstractVisitorDiagnostic { - private Pattern modalityMethods = Pattern.compile( + private final Pattern modalityMethods = Pattern.compile( "(ВОПРОС|DOQUERYBOX|ОТКРЫТЬФОРМУМОДАЛЬНО|OPENFORMMODAL|ОТКРЫТЬЗНАЧЕНИЕ|OPENVALUE|" + "ПРЕДУПРЕЖДЕНИЕ|DOMESSAGEBOX|ВВЕСТИДАТУ|INPUTDATE|ВВЕСТИЗНАЧЕНИЕ|INPUTVALUE|" + "ВВЕСТИСТРОКУ|INPUTSTRING|ВВЕСТИЧИСЛО|INPUTNUMBER|УСТАНОВИТЬВНЕШНЮЮКОМПОНЕНТУ|INSTALLADDIN|" + @@ -54,7 +54,7 @@ public class UsingModalWindowsDiagnostic extends AbstractVisitorDiagnostic { "УСТАНОВИТЬРАСШИРЕНИЕРАБОТЫСКРИПТОГРАФИЕЙ|INSTALLCRYPTOEXTENSION|ПОМЕСТИТЬФАЙЛ|PUTFILE)", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); - private HashMap pairMethods = new HashMap<>(); + private final HashMap pairMethods = new HashMap<>(); public UsingModalWindowsDiagnostic(DiagnosticInfo info) { super(info); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnostic.java index 50ac4b07077..76dd40a94f0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnostic.java @@ -64,7 +64,7 @@ public class UsingSynchronousCallsDiagnostic extends AbstractVisitorDiagnostic { "(НаСервере|НаСервереБезКонтекста|AtServer|AtServerNoContext)", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); - private HashMap pairMethods = new HashMap<>(); + private final HashMap pairMethods = new HashMap<>(); public UsingSynchronousCallsDiagnostic(DiagnosticInfo info) { super(info); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/YoLetterUsageDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/YoLetterUsageDiagnostic.java index 54db0f430f2..df6c59f223d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/YoLetterUsageDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/YoLetterUsageDiagnostic.java @@ -53,7 +53,7 @@ protected void check(DocumentContext documentContext) { .filter((Token t) -> t.getType() == BSLParser.IDENTIFIER && t.getText().toUpperCase(Locale.ENGLISH).contains("Ё")) - .forEach(token -> diagnosticStorage.addDiagnostic(token)); + .forEach(diagnosticStorage::addDiagnostic); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticCompatibilityMode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticCompatibilityMode.java index ca770df5509..f3189bcec57 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticCompatibilityMode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticCompatibilityMode.java @@ -45,7 +45,7 @@ public enum DiagnosticCompatibilityMode { COMPATIBILITY_MODE_8_3_15(3, 15), COMPATIBILITY_MODE_8_3_16(3, 16); - private CompatibilityMode compatibilityMode; + private final CompatibilityMode compatibilityMode; DiagnosticCompatibilityMode(int minor, int version) { this.compatibilityMode = new CompatibilityMode(minor, version); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java index 39213d610b0..aeafee2ec08 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java @@ -45,15 +45,15 @@ @Slf4j public class DiagnosticInfo { - private static Map severityToLSPSeverityMap + private static final Map severityToLSPSeverityMap = createSeverityToLSPSeverityMap(); private final Class diagnosticClass; private final DiagnosticLanguage diagnosticLanguage; private final DiagnosticCode diagnosticCode; - private DiagnosticMetadata diagnosticMetadata; - private List diagnosticParameters; + private final DiagnosticMetadata diagnosticMetadata; + private final List diagnosticParameters; public DiagnosticInfo(Class diagnosticClass, DiagnosticLanguage diagnosticLanguage) { this.diagnosticClass = diagnosticClass; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericIssueReport.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericIssueReport.java index ec808c1a73c..8ddb97aca14 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericIssueReport.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericIssueReport.java @@ -55,10 +55,10 @@ public class GenericIssueReport { private static final String SEVERITY_MINOR = "MINOR"; // TODO: пробросить из analyze? - private static LanguageServerConfiguration configuration = LanguageServerConfiguration.create(); - private static DiagnosticSupplier diagnosticSupplier = new DiagnosticSupplier(configuration); - private static Map severityMap = new EnumMap<>(DiagnosticSeverity.class); - private static Map typeMap = new EnumMap<>(DiagnosticSeverity.class); + private static final LanguageServerConfiguration configuration = LanguageServerConfiguration.create(); + private static final DiagnosticSupplier diagnosticSupplier = new DiagnosticSupplier(configuration); + private static final Map severityMap = new EnumMap<>(DiagnosticSeverity.class); + private static final Map typeMap = new EnumMap<>(DiagnosticSeverity.class); static { severityMap.put(DiagnosticSeverity.Error, SEVERITY_CRITICAL); @@ -101,13 +101,13 @@ public GenericIssueReport(AnalysisInfo analysisInfo) { @Value static class GenericIssueEntry { - private final String engineId; - private final String ruleId; - private final String severity; - private final String type; - private final Location primaryLocation; - private final int effortMinutes; - private final List secondaryLocations; + String engineId; + String ruleId; + String severity; + String type; + Location primaryLocation; + int effortMinutes; + List secondaryLocations; public GenericIssueEntry( @JsonProperty("engineId") String engineId, @@ -161,9 +161,9 @@ public GenericIssueEntry(String fileName, Diagnostic diagnostic) { @Value static class Location { - private final String message; - private final String filePath; - private final TextRange textRange; + String message; + String filePath; + TextRange textRange; public Location( @JsonProperty("message") String message, @@ -191,10 +191,10 @@ public Location(DiagnosticRelatedInformation relatedInformation) { @Value static class TextRange { - private final int startLine; - private final int endLine; - private final int startColumn; - private final int endColumn; + int startLine; + int endLine; + int startColumn; + int endColumn; public TextRange( @JsonProperty("startLine") int startLine, diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/JUnitTestSuites.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/JUnitTestSuites.java index 82e236bda25..bb59dddb194 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/JUnitTestSuites.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/JUnitTestSuites.java @@ -80,10 +80,10 @@ public JUnitTestSuites( static class JUnitTestSuite { @JacksonXmlProperty(isAttribute = true) - private final String name; + String name; @JacksonXmlElementWrapper(useWrapping = false) - private final List testcase; + List testcase; public JUnitTestSuite(FileInfo fileInfo) { this.name = fileInfo.getPath().toString(); @@ -114,13 +114,13 @@ public JUnitTestSuite( static class JUnitTestCase { @JacksonXmlProperty(isAttribute = true) - private final String name; + String name; @JacksonXmlProperty(isAttribute = true) - private final String classname; + String classname; @JacksonXmlElementWrapper(useWrapping = false) - private final JUnitFailure failure; + JUnitFailure failure; public JUnitTestCase(List diagnostics, String name, String classname) { this.name = name; @@ -161,14 +161,14 @@ public JUnitTestCase( static class JUnitFailure { @JacksonXmlProperty(isAttribute = true) - private final String type; + String type; @JacksonXmlProperty(isAttribute = true) - private final String message; + String message; @JacksonXmlText @JacksonXmlCData - private final String value; + String value; } static class JUnitFailureDeserializer extends JsonDeserializer { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/TSLintReportEntry.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/TSLintReportEntry.java index 820ad99a0b2..47aef14cb7f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/TSLintReportEntry.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/TSLintReportEntry.java @@ -44,7 +44,7 @@ class TSLintReportEntry { @Getter private final String ruleSeverity; - private static Map severityMap = new EnumMap<>(DiagnosticSeverity.class); + private static final Map severityMap = new EnumMap<>(DiagnosticSeverity.class); static { severityMap.put(DiagnosticSeverity.Error, "error"); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/typo/JLanguageToolPool.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/typo/JLanguageToolPool.java index 0e20a4b643c..578050f42ec 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/typo/JLanguageToolPool.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/typo/JLanguageToolPool.java @@ -28,7 +28,7 @@ @AllArgsConstructor public class JLanguageToolPool extends AbstractObjectPool { - private Language language; + private final Language language; @Override protected JLanguageToolPoolEntry create() { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/FoldingRangeProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/FoldingRangeProvider.java index 3e35282d67c..48c0a89ac07 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/FoldingRangeProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/FoldingRangeProvider.java @@ -106,7 +106,7 @@ private static List getCommentRanges(DocumentContext documentConte private static class UseRangeFinder extends BSLParserBaseVisitor { - private List regionRanges = new ArrayList<>(); + private final List regionRanges = new ArrayList<>(); public List getRegionRanges() { return new ArrayList<>(regionRanges); @@ -135,7 +135,7 @@ public ParseTree visitFile(BSLParser.FileContext ctx) { private static class CodeBlockRangeFinder extends BSLParserBaseVisitor { - private List regionRanges = new ArrayList<>(); + private final List regionRanges = new ArrayList<>(); public List getRegionRanges() { return new ArrayList<>(regionRanges); @@ -202,7 +202,7 @@ private void addRegionRange(TerminalNode start, TerminalNode stop) { private static class RegionRangeFinder { - private List regionRanges; + private final List regionRanges; RegionRangeFinder(DocumentContext documentContext) { regionRanges = documentContext.getSymbolTree().getRegionsFlat().stream() @@ -229,8 +229,8 @@ private static FoldingRange toFoldingRange(RegionSymbol regionSymbol) { private static class PreprocIfRegionRangeFinder extends BSLParserBaseVisitor { - private Deque preprocIfRegionStack = new ArrayDeque<>(); - private List regionRanges = new ArrayList<>(); + private final Deque preprocIfRegionStack = new ArrayDeque<>(); + private final List regionRanges = new ArrayList<>(); public List getRegionRanges() { return new ArrayList<>(regionRanges); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/AbstractObjectPool.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/AbstractObjectPool.java index 798aa3780f8..d8a8d11ec0d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/AbstractObjectPool.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/AbstractObjectPool.java @@ -55,8 +55,8 @@ */ public abstract class AbstractObjectPool { - private Set available = new HashSet<>(); - private Set inUse = new HashSet<>(); + private final Set available = new HashSet<>(); + private final Set inUse = new HashSet<>(); protected abstract T create(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MultilingualStringAnalyser.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MultilingualStringAnalyser.java index 16fa3eb94a0..b0a7c618227 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MultilingualStringAnalyser.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MultilingualStringAnalyser.java @@ -63,8 +63,8 @@ public final class MultilingualStringAnalyser { private BSLParser.GlobalMethodCallContext globalMethodCallContext; private boolean isParentTemplate; private String variableName; - private ArrayList expectedLanguages; - private Set expandedMultilingualString = new HashSet<>(); + private final ArrayList expectedLanguages; + private final Set expandedMultilingualString = new HashSet<>(); private ArrayList missingLanguages = new ArrayList<>(); public MultilingualStringAnalyser(String declaredLanguages) { diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MethodSizeDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MethodSizeDiagnostic_en.properties index df050240fcd..7299e50ed17 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MethodSizeDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MethodSizeDiagnostic_en.properties @@ -1,4 +1,4 @@ diagnosticMessage=Method "%s" has %d lines, which is greater than the %d lines authorized -diagnosticName=Method size +diagnosticName=Method size maxMethodSize=Max method line count. \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnostic_en.properties index bec90ae9005..bc529e8370b 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnostic_en.properties @@ -4,8 +4,6 @@ quickFixMessage=Add space wordLeft=To the left wordRight=To the right wordLeftAndRight=Left and right -wordLeftOrRight=Left or right - listForCheckLeft=List of symbols to check for the space to the left of (separated by space) listForCheckRight=List of symbols to check for the space to the right of (separated by space) listForCheckLeftAndRight=List of symbols to check for the space from both sides of (separated by space) diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnostic_ru.properties index 4b5593bae29..254b9b3ce9e 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnostic_ru.properties @@ -4,8 +4,6 @@ quickFixMessage=Добавить пробел wordLeft=Слева wordRight=Справа wordLeftAndRight=Слева и справа -wordLeftOrRight=Слева или справа - listForCheckLeft=Список символов для проверки слева (разделенные пробелом). Например: ) = listForCheckRight=Список символов для проверки справа (разделенные пробелом). Например: ( = listForCheckLeftAndRight=Список символов для проверки с обоих сторон (разделенные пробелом). Например: + - * / = % < > diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnostic_ru.properties index 3aca60ece0d..47c5b302b45 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnostic_ru.properties @@ -1,2 +1,2 @@ -diagnosticMessage=Нужно удалить нестандартный раздел "%s" +diagnosticMessage=Нужно удалить нестандартный раздел "%s" diagnosticName=Нестандартные разделы модуля \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnostic_en.properties index 3e096606d23..0d083276ae1 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnostic_en.properties @@ -1,4 +1,4 @@ diagnosticMessage=Instead of the synchronous method `%s`, use `%s` diagnosticName=Using synchronous calls -searchWords= Keywords for search hardcoded security information \ No newline at end of file +searchWords= Keywords for search hardcoded security information \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentServiceTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentServiceTest.java index c1921dba71c..90b4bd0006f 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentServiceTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentServiceTest.java @@ -54,7 +54,7 @@ class BSLTextDocumentServiceTest { - private BSLTextDocumentService textDocumentService = new BSLTextDocumentService( + private final BSLTextDocumentService textDocumentService = new BSLTextDocumentService( LanguageServerConfiguration.create(), new ServerContext()); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericReporterTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericReporterTest.java index ff6f6ffa875..b7a4baab231 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericReporterTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericReporterTest.java @@ -46,7 +46,7 @@ class GenericReporterTest { - private File file = new File("./bsl-generic-json.json"); + private final File file = new File("./bsl-generic-json.json"); @BeforeEach void setUp() { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/JUnitReporterTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/JUnitReporterTest.java index 76f64d4c6c1..799e23c26f0 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/JUnitReporterTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/JUnitReporterTest.java @@ -46,7 +46,7 @@ class JUnitReporterTest { - private File file = new File("./bsl-junit.xml"); + private final File file = new File("./bsl-junit.xml"); @BeforeEach void setUp() { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/JsonReporterTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/JsonReporterTest.java index 02da59a9163..c3535aa15e5 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/JsonReporterTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/JsonReporterTest.java @@ -42,7 +42,7 @@ class JsonReporterTest { - private File file = new File("./bsl-json.json"); + private final File file = new File("./bsl-json.json"); @BeforeEach void setUp() { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/TSLintReporterTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/TSLintReporterTest.java index f366d94a722..3e0f849e0be 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/TSLintReporterTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/TSLintReporterTest.java @@ -45,7 +45,7 @@ class TSLintReporterTest { - private File file = new File("./bsl-tslint.json"); + private final File file = new File("./bsl-tslint.json"); @BeforeEach void setUp() { From 6d046c7ff672041e9d7fe7808720ca4aa5ecf607 Mon Sep 17 00:00:00 2001 From: Aleksandr Ponkratov Date: Mon, 13 Apr 2020 12:28:49 +0300 Subject: [PATCH 037/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=20=D1=82=D0=B5=D1=81=D1=82=20VariableSymbol?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../context/computer/VariableSymbolTest.java | 60 +++++++++++++++++++ .../resources/providers/variableSymbol.bsl | 11 ++++ 2 files changed, 71 insertions(+) create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolTest.java create mode 100644 src/test/resources/providers/variableSymbol.bsl diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolTest.java new file mode 100644 index 00000000000..7d175562698 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolTest.java @@ -0,0 +1,60 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.context.computer; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.symbol.VariableSymbol; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class VariableSymbolTest { + + @Test + void testVariableDescription() { + + DocumentContext documentContext = TestUtils.getDocumentContextFromFile("./src/test/resources/providers/variableSymbol.bsl"); + List variableSymbols = documentContext.getSymbolTree().getVariables(); + + assertThat(variableSymbols).hasSize(4); + + assertThat(variableSymbols) + .filteredOn(variableSymbol -> variableSymbol.getDescription().isEmpty()) + .hasSize(2) + .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(1, 6, 1, 27))) + .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(10, 6, 10, 34))) + ; + + assertThat(variableSymbols) + .filteredOn(variableSymbol -> variableSymbol.getDescription().isPresent()) + .hasSize(2) + .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(4, 6, 4, 32))) + .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(6, 6, 6, 33))) + ; + + } + +} diff --git a/src/test/resources/providers/variableSymbol.bsl b/src/test/resources/providers/variableSymbol.bsl new file mode 100644 index 00000000000..134fe908fcf --- /dev/null +++ b/src/test/resources/providers/variableSymbol.bsl @@ -0,0 +1,11 @@ + +Перем ПеременнаяБезОписания; + +// Описание сверху +Перем ПеременнаяСОписаниемСверху; + +Перем ПеременнаяСОписаниемВСтроке; // Описание в строке + +// Неверное описание + +Перем ПеременнаяСНевернымОписанием; From 99a36a4dd971646616014532ca3f1ca82a181ec2 Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Mon, 13 Apr 2020 12:52:59 +0300 Subject: [PATCH 038/444] =?UTF-8?q?=D0=92=20=D0=A0=D1=83=D0=BA=D0=BE=D0=B2?= =?UTF-8?q?=D0=BE=D0=B4=D1=81=D1=82=D0=B2=D0=BE=20=D0=BA=D0=BE=D0=BD=D1=82?= =?UTF-8?q?=D1=80=D0=B8=D0=B1=D1=8C=D1=8E=D1=82=D0=BE=D1=80=D0=B0=20=D0=BD?= =?UTF-8?q?=D0=B5=D1=82=20=D1=81=D1=81=D1=8B=D0=BB=D0=BA=D0=B8=20=D0=BD?= =?UTF-8?q?=D0=B0=20=D0=BF=D0=BE=D0=BB=D0=B5=D0=B7=D0=BD=D1=83=D1=8E=20?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D1=82=D1=8C=D1=8E=20"=D0=A1=D1=82=D1=80?= =?UTF-8?q?=D1=83=D0=BA=D1=82=D1=83=D1=80=D0=B0=20=D0=B4=D0=B8=D0=B0=D0=B3?= =?UTF-8?q?=D0=BD=D0=BE=D1=81=D1=82=D0=B8=D0=BA=D0=B8,=20=D0=BD=D0=B0?= =?UTF-8?q?=D0=B7=D0=BD=D0=B0=D1=87=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B8=20?= =?UTF-8?q?=D1=81=D0=BE=D0=B4=D0=B5=D1=80=D0=B6=D0=B8=D0=BC=D0=BE=D0=B5=20?= =?UTF-8?q?=D1=84=D0=B0=D0=B9=D0=BB=D0=BE=D0=B2"=20#1048?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/contributing/index.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/contributing/index.md b/docs/contributing/index.md index f1ae581b385..460c600d682 100644 --- a/docs/contributing/index.md +++ b/docs/contributing/index.md @@ -8,8 +8,9 @@ - [Настройка окружения](EnvironmentSetting.md) - [Быстрый старт](FastStart.md) - Разработка диагностик - - [Пример разработки диагностики](DiagnosticExample.md) - [Процесс (workflow) разработки диагностики](DiagnosticDevWorkFlow.md) + - [Пример разработки диагностики](DiagnosticExample.md) + - [Структура диагностики, назначение и содержимое файлов](DiagnosticStructure.md) - [Описание типов и важности диагностик](DiagnosticTypeAndSeverity.md) - [Тэги диагностик](DiagnosticTag.md) - [Добавление параметров диагностике](DiagnostcAddSettings.md) From eba28e7b88d4055bdab40281197d14882736679e Mon Sep 17 00:00:00 2001 From: evgeniy Date: Mon, 13 Apr 2020 15:27:28 +0300 Subject: [PATCH 039/444] =?UTF-8?q?Another=20fix=20fp=20=D0=B7=D0=B0=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D1=81=20=D0=B2=20=D1=86=D0=B8=D0=BA=D0=BB=D0=B5=20?= =?UTF-8?q?#1046?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CreateQueryInCycleDiagnostic.java | 28 ++++++++++++++++--- .../CreateQueryInCycleDiagnosticTest.java | 6 ++-- .../CreateQueryInCycleDiagnostic.bsl | 20 +++++++++++++ 3 files changed, 48 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java index 7b0a2a1c53f..a187494e908 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java @@ -35,6 +35,7 @@ import org.antlr.v4.runtime.tree.ParseTree; import java.util.ArrayDeque; +import java.util.Collection; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; @@ -274,10 +275,20 @@ public ParseTree visitAccessCall(BSLParser.AccessCallContext ctx) { @Override public ParseTree visitForEachStatement(BSLParser.ForEachStatementContext ctx) { + boolean alreadyInCycle = currentScope.codeFlowInCycle(); + ParseTree result; currentScope.flowMode.push(CodeFlowType.CYCLE); - ParseTree result = super.visitForEachStatement(ctx); + if(alreadyInCycle) { + Optional.ofNullable(ctx.expression()) + .ifPresent( e -> e.accept(this)); + } + Optional.ofNullable(ctx.codeBlock()) + .map(e -> e.children) + .stream(). + flatMap(Collection::stream) + .forEach( t -> t.accept(this)); currentScope.flowMode.pop(); - return result; + return null; } @Override @@ -290,10 +301,19 @@ public ParseTree visitWhileStatement(BSLParser.WhileStatementContext ctx) { @Override public ParseTree visitForStatement(BSLParser.ForStatementContext ctx) { + boolean alreadyInCycle = currentScope.codeFlowInCycle(); currentScope.flowMode.push(CodeFlowType.CYCLE); - ParseTree result = super.visitForStatement(ctx); + if(alreadyInCycle) { + ctx.expression() + .forEach( e-> e.accept(this)); + } + Optional.ofNullable(ctx.codeBlock()) + .map(e -> e.children) + .stream() + .flatMap(Collection::stream) + .forEach( t -> t.accept(this)); currentScope.flowMode.pop(); - return result; + return null; } public enum CodeFlowType { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnosticTest.java index 9bc96f39dfa..81e82a4be88 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnosticTest.java @@ -39,7 +39,7 @@ class CreateQueryInCycleDiagnosticTest extends AbstractDiagnosticTest diagnostics = getDiagnostics(); - assertThat(diagnostics).hasSize(8); + assertThat(diagnostics).hasSize(10); assertThat(diagnostics, true) .hasRange(4, 8, 4, 36) .hasRange(27, 23, 27, 47) @@ -48,6 +48,8 @@ void test() { .hasRange(59, 4, 59, 18) .hasRange(60, 4, 60, 24) .hasRange(66, 4, 66, 22) - .hasRange(73, 2, 73, 30); + .hasRange(73, 2, 73, 30) + .hasRange(79, 4, 79, 34) + .hasRange(90, 41, 90, 71); } } diff --git a/src/test/resources/diagnostics/CreateQueryInCycleDiagnostic.bsl b/src/test/resources/diagnostics/CreateQueryInCycleDiagnostic.bsl index e2024cdfea7..fd524b44328 100644 --- a/src/test/resources/diagnostics/CreateQueryInCycleDiagnostic.bsl +++ b/src/test/resources/diagnostics/CreateQueryInCycleDiagnostic.bsl @@ -74,3 +74,23 @@ Запрос.Выполнить().Выбрать(); КонецЦикла; + +Для Каждого СтрокаПредопределенного Из Коллекция Цикл + + Запрос.Выполнить().Выгрузить(); + +КонецЦикла; + +Для Каждого СтрокаПредопределенного Из Запрос.Выполнить().Выгрузить() Цикл + + +КонецЦикла; + +Для ит = 1 По 10 Цикл + + Для Каждого СтрокаПредопределенного Из Запрос.Выполнить().Выгрузить() Цикл // Тут + + + КонецЦикла; + +КонецЦикла; \ No newline at end of file From 14af3296365e052c1ebb9cab054e37c814cad5d1 Mon Sep 17 00:00:00 2001 From: Aleksandr Ponkratov Date: Mon, 13 Apr 2020 17:18:05 +0300 Subject: [PATCH 040/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D1=8B=20=D1=82=D0=B5=D1=81=D1=82=D1=8B=20=D0=B4?= =?UTF-8?q?=D0=BB=D1=8F=20VariableSymbol?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../computer/VariableSymbolComputer.java | 17 ++++- .../context/computer/VariableSymbolTest.java | 72 ++++++++++++++++--- .../symbol/variableSymbolTest.bsl} | 9 ++- 3 files changed, 86 insertions(+), 12 deletions(-) rename src/test/resources/{providers/variableSymbol.bsl => context/symbol/variableSymbolTest.bsl} (64%) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java index b668f25d21f..31cf93690c2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java @@ -32,6 +32,7 @@ import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.ParseTree; +import org.eclipse.lsp4j.Range; import java.util.ArrayList; import java.util.List; @@ -103,8 +104,10 @@ private Optional createDescription(Token token) { .build() ); - var description = VariableDescription.builder() + var description = + VariableDescription.builder() .description(commentsText) + .range(getRangeForDescription(comments)) .trailingDescription(trailingDescription) .build(); @@ -119,4 +122,16 @@ private static Token getTokenToSearchComments(BSLParserRuleContext declaration) return parent.getStart(); } + private static Range getRangeForDescription(List tokens) { + + if (tokens.isEmpty()) { + return null; + } + + Token firstElement = tokens.get(0); + Token lastElement = tokens.get(tokens.size() - 1); + + return Ranges.create(firstElement, lastElement); + } + } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolTest.java index 7d175562698..b2b3c662251 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolTest.java @@ -23,38 +23,90 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; 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.util.TestUtils; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import org.eclipse.lsp4j.Range; import org.junit.jupiter.api.Test; import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; public class VariableSymbolTest { - @Test - void testVariableDescription() { + static DocumentContext documentContext; + static List variableSymbols; + + static { + documentContext = TestUtils.getDocumentContextFromFile("./src/test/resources/context/symbol/variableSymbolTest.bsl"); + variableSymbols = documentContext.getSymbolTree().getVariables(); + } - DocumentContext documentContext = TestUtils.getDocumentContextFromFile("./src/test/resources/providers/variableSymbol.bsl"); - List variableSymbols = documentContext.getSymbolTree().getVariables(); + @Test + void testVariableSymbolDescription() { - assertThat(variableSymbols).hasSize(4); + assertThat(variableSymbols).hasSize(7); assertThat(variableSymbols) .filteredOn(variableSymbol -> variableSymbol.getDescription().isEmpty()) - .hasSize(2) - .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(1, 6, 1, 27))) - .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(10, 6, 10, 34))) + .hasSize(4) + .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(12, 6, 12, 34))) + .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(14, 6, 14, 27))) + .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(16, 6, 16, 17))) + .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(16, 19, 16, 30))) ; assertThat(variableSymbols) .filteredOn(variableSymbol -> variableSymbol.getDescription().isPresent()) + .hasSize(3) + .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(2, 6, 2, 32))) + .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(6, 6, 6, 32))) + .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(8, 6, 8, 33))) + ; + + } + + @Test + void testVariableDescriptionRange() { + + List variableDescriptions = variableSymbols.stream() + .map(VariableSymbol::getDescription) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.toList()); + + assertThat(variableDescriptions).hasSize(3); + + assertThat(variableDescriptions) + .filteredOn(variableDescription -> !variableDescription.getDescription().equals("")) .hasSize(2) - .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(4, 6, 4, 32))) - .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(6, 6, 6, 33))) + .anyMatch(variableDescription -> variableDescription.getRange().equals(Ranges.create(1, 0, 1, 18))) + .anyMatch(variableDescription -> variableDescription.getRange().equals(Ranges.create(4, 0, 5, 23))) + ; + + assertThat(variableDescriptions) + .extracting(VariableDescription::getTrailingDescription) + .filteredOn(Optional::isPresent) + .hasSize(1) + .extracting(Optional::get) + .anyMatch(trailingDescription -> trailingDescription.getRange().equals(Ranges.create(8, 35, 8, 55))) ; } + @Test + void testVariableNameRange() { + + assertThat(variableSymbols) + .filteredOn(variableSymbol -> variableSymbol.getDescription().isEmpty()) + .hasSize(4) + .anyMatch(variableName -> variableName.getVariableNameRange().equals(Ranges.create(12, 6, 12, 34))) + .anyMatch(variableName -> variableName.getVariableNameRange().equals(Ranges.create(14, 6, 14, 27))) + .anyMatch(variableName -> variableName.getVariableNameRange().equals(Ranges.create(16, 6, 16, 17))) + .anyMatch(variableName -> variableName.getVariableNameRange().equals(Ranges.create(16, 19, 16, 30))) + ; + } } diff --git a/src/test/resources/providers/variableSymbol.bsl b/src/test/resources/context/symbol/variableSymbolTest.bsl similarity index 64% rename from src/test/resources/providers/variableSymbol.bsl rename to src/test/resources/context/symbol/variableSymbolTest.bsl index 134fe908fcf..5930a0769ad 100644 --- a/src/test/resources/providers/variableSymbol.bsl +++ b/src/test/resources/context/symbol/variableSymbolTest.bsl @@ -1,7 +1,9 @@ -Перем ПеременнаяБезОписания; +// Описание сверху +Перем ПеременнаяСОписаниемСверху; // Описание сверху +// Еще немного описания Перем ПеременнаяСОписаниемСверху; Перем ПеременнаяСОписаниемВСтроке; // Описание в строке @@ -9,3 +11,8 @@ // Неверное описание Перем ПеременнаяСНевернымОписанием; + +Перем ПеременнаяБезОписания; + +Перем ПеременнаяА, ПеременнаяБ; + From e3b0a0ca78811540e9991f9a82574f033436dfe1 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Mon, 13 Apr 2020 19:18:01 +0300 Subject: [PATCH 041/444] =?UTF-8?q?MethodeSymbolComputer=20subName=20?= =?UTF-8?q?=D0=B8=D0=B7=20=D0=A1=D1=82=D0=B0=D1=80=D1=82=D0=A2=D0=BE=D0=BA?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../computer/MethodSymbolComputer.java | 6 +- .../computer/MethodSymbolComputerTest.java | 71 +++++++++++++++++++ .../computer/MethodSymbolComputerTest.bsl | 19 +++++ .../MethodSymbolComputerTestParseError.bsl | 3 + 4 files changed, 96 insertions(+), 3 deletions(-) create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java create mode 100644 src/test/resources/context/computer/MethodSymbolComputerTest.bsl create mode 100644 src/test/resources/context/computer/MethodSymbolComputerTestParseError.bsl diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java index b90fd7c323f..9561f672a90 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java @@ -77,7 +77,7 @@ public ParseTree visitFunction(BSLParser.FunctionContext ctx) { MethodSymbol methodSymbol = createMethodSymbol( startNode, stopNode, - declaration.subName(), + declaration.subName().getStart(), declaration.paramList(), true, declaration.EXPORT_KEYWORD() != null @@ -106,7 +106,7 @@ public ParseTree visitProcedure(BSLParser.ProcedureContext ctx) { MethodSymbol methodSymbol = createMethodSymbol( startNode, stopNode, - declaration.subName(), + declaration.subName().getStart(), declaration.paramList(), false, declaration.EXPORT_KEYWORD() != null @@ -120,7 +120,7 @@ public ParseTree visitProcedure(BSLParser.ProcedureContext ctx) { private MethodSymbol createMethodSymbol( TerminalNode startNode, TerminalNode stopNode, - BSLParser.SubNameContext subName, + Token subName, BSLParser.ParamListContext paramList, boolean function, boolean export diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java new file mode 100644 index 00000000000..9ef91b6c3d0 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java @@ -0,0 +1,71 @@ +package com.github._1c_syntax.bsl.languageserver.context.computer; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.ParameterDefinition; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class MethodSymbolComputerTest { + + @Test + void testMethodSymbolComputer() { + + DocumentContext documentContext = TestUtils.getDocumentContextFromFile("./src/test/resources/context/computer/MethodSymbolComputerTest.bsl"); + List methods = documentContext.getSymbolTree().getMethods(); + + assertThat(methods.size()).isEqualTo(3); + + assertThat(methods.get(0).getName()).isEqualTo("Один"); + assertThat(methods.get(0).getDescription().orElse(null)).isNull(); + assertThat(methods.get(0).getRange()).isEqualTo(Ranges.create(1, 0, 3, 14)); + assertThat(methods.get(0).getSubNameRange()).isEqualTo(Ranges.create(1, 10, 1, 14)); + + assertThat(methods.get(1).getDescription()).isNotEmpty(); + assertThat(methods.get(1).getRegion().orElse(null).getName()).isEqualTo("ИмяОбласти"); + assertThat(methods.get(1).getDescription().orElse(null).getDescription()).isNotEmpty(); + + } + + @Test + void testParameters() { + + DocumentContext documentContext = TestUtils.getDocumentContextFromFile("./src/test/resources/context/computer/MethodSymbolComputerTest.bsl"); + List methods = documentContext.getSymbolTree().getMethods(); + + List parameters = methods.get(2).getParameters(); + assertThat(parameters.size()).isEqualTo(4); + assertThat(parameters.get(0).getName()).isEqualTo("Парам"); + assertThat(parameters.get(0).isByValue()).isFalse(); + assertThat(parameters.get(0).isOptional()).isFalse(); + + assertThat(parameters.get(1).getName()).isEqualTo("Парам2"); + assertThat(parameters.get(1).isByValue()).isTrue(); + assertThat(parameters.get(1).isOptional()).isFalse(); + + assertThat(parameters.get(2).getName()).isEqualTo("Парам3"); + assertThat(parameters.get(2).isByValue()).isFalse(); + assertThat(parameters.get(2).isOptional()).isTrue(); + + assertThat(parameters.get(3).getName()).isEqualTo("Парам4"); + assertThat(parameters.get(3).isByValue()).isTrue(); + assertThat(parameters.get(3).isOptional()).isTrue(); + + } + + @Test + void testParseError() { + + DocumentContext documentContext = TestUtils.getDocumentContextFromFile("./src/test/resources/context/computer/MethodSymbolComputerTestParseError.bsl"); + List methods = documentContext.getSymbolTree().getMethods(); + + assertThat(methods.get(0).getName()).isEqualTo("Выполнить"); + assertThat(methods.get(0).getSubNameRange()).isEqualTo(Ranges.create(0, 10, 0, 19)); + + } +} \ No newline at end of file diff --git a/src/test/resources/context/computer/MethodSymbolComputerTest.bsl b/src/test/resources/context/computer/MethodSymbolComputerTest.bsl new file mode 100644 index 00000000000..373be805b44 --- /dev/null +++ b/src/test/resources/context/computer/MethodSymbolComputerTest.bsl @@ -0,0 +1,19 @@ + +Процедура Один() + А = 0; +КонецПроцедуры + +#Область ИмяОбласти + +// Описание +// Возвращаемое значение: +// Строка - описание строки +Функция Два() + Возврат Неопределено; +КонецФункции + +Функция Три(Парам, Знач Парам2, Парам3 = 0, Знач Парам4 = 0) + Возврат Неопределено; +КонецФункции + +#КонецОбласти diff --git a/src/test/resources/context/computer/MethodSymbolComputerTestParseError.bsl b/src/test/resources/context/computer/MethodSymbolComputerTestParseError.bsl new file mode 100644 index 00000000000..e055cf6852d --- /dev/null +++ b/src/test/resources/context/computer/MethodSymbolComputerTestParseError.bsl @@ -0,0 +1,3 @@ +Процедура Выполнить() + +КонецПроцедуры From 81d047c93272caa9fa399cffb0065a660b3803f9 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Mon, 13 Apr 2020 19:19:12 +0300 Subject: [PATCH 042/444] CodeOutOfRegion test --- .../diagnostics/CodeOutOfRegionDiagnosticTest.java | 11 +++++++++++ .../diagnostics/CodeOutOfRegionDiagnosticExecute.bsl | 4 ++++ 2 files changed, 15 insertions(+) create mode 100644 src/test/resources/diagnostics/CodeOutOfRegionDiagnosticExecute.bsl diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnosticTest.java index 70b8f0168a1..4e09de3708a 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnosticTest.java @@ -96,4 +96,15 @@ void testEmptyFile() { } + @Test + void testExecute() { + + List diagnostics = getDiagnostics("CodeOutOfRegionDiagnosticExecute"); + + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(1, 10, 1, 19); + + } + } diff --git a/src/test/resources/diagnostics/CodeOutOfRegionDiagnosticExecute.bsl b/src/test/resources/diagnostics/CodeOutOfRegionDiagnosticExecute.bsl new file mode 100644 index 00000000000..76871b83e20 --- /dev/null +++ b/src/test/resources/diagnostics/CodeOutOfRegionDiagnosticExecute.bsl @@ -0,0 +1,4 @@ + +Процедура Выполнить() + +КонецПроцедуры From 539368fc50d887bd371bc8879c2639ec7cf9d391 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Mon, 13 Apr 2020 20:02:57 +0300 Subject: [PATCH 043/444] liicense add --- .../computer/MethodSymbolComputerTest.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java index 9ef91b6c3d0..b4e10b4674d 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java @@ -1,3 +1,24 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.context.computer; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; From ec2f280aa355a6a6ebb89f02a11d7aff774b94b8 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Mon, 13 Apr 2020 20:25:06 +0300 Subject: [PATCH 044/444] Update src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java --- .../context/computer/MethodSymbolComputerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java index b4e10b4674d..1c4a6d36fa4 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java @@ -89,4 +89,4 @@ void testParseError() { assertThat(methods.get(0).getSubNameRange()).isEqualTo(Ranges.create(0, 10, 0, 19)); } -} \ No newline at end of file +} From c66dd4b5d9b898f49a02b1ce3cced159803b9572 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Mon, 13 Apr 2020 21:56:39 +0300 Subject: [PATCH 045/444] ContentList with last whiteSpaces --- .../bsl/languageserver/context/DocumentContext.java | 2 +- .../languageserver/context/DocumentContextTest.java | 11 +++++++++++ src/test/resources/context/DocumentContextTest.bsl | 3 +++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java index 3b9fa8c6823..9a985ae7912 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java @@ -234,7 +234,7 @@ private static FileType computeFileType(URI uri) { } private String[] computeContentList() { - return getContent().split("\n"); + return getContent().split("\n", -1); } private SymbolTree computeSymbolTree() { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java index bae3d5373f8..c3703e5de9c 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java @@ -208,5 +208,16 @@ void testComputeMetricsComments() { } + @Test + void testContentList() { + // given + DocumentContext documentContext = getDocumentContext(); + + // when + String[] conten = documentContext.getContentList(); + + // then + assertThat(conten.length).isEqualTo(40); + } } \ No newline at end of file diff --git a/src/test/resources/context/DocumentContextTest.bsl b/src/test/resources/context/DocumentContextTest.bsl index f6c9e8f83e5..ff49137ad7d 100644 --- a/src/test/resources/context/DocumentContextTest.bsl +++ b/src/test/resources/context/DocumentContextTest.bsl @@ -34,3 +34,6 @@ Функция ФункцияСПараметрами(Парам1, Знач Парам2, Парам3 = 0, Знач Парам4 = 0) КонецФункции + + + From 27f87f62021a508b57f1799b2e5a058118fe22ad Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Mon, 13 Apr 2020 22:11:40 +0300 Subject: [PATCH 046/444] test fix --- .../bsl/languageserver/context/DocumentContextTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java index c3703e5de9c..648a11eb1b7 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java @@ -214,10 +214,10 @@ void testContentList() { DocumentContext documentContext = getDocumentContext(); // when - String[] conten = documentContext.getContentList(); + String[] contentList = documentContext.getContentList(); // then - assertThat(conten.length).isEqualTo(40); + assertThat(contentList).hasSize(40); } } \ No newline at end of file From fcc5df8b3b47be2ba4f2a4d5ec0dc14572e66ca5 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Mon, 13 Apr 2020 22:54:27 +0300 Subject: [PATCH 047/444] CodeActionAssert fix --- .../bsl/languageserver/util/assertions/CodeActionAssert.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/CodeActionAssert.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/CodeActionAssert.java index d3878d679fd..5f17c89fba4 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/CodeActionAssert.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/CodeActionAssert.java @@ -35,6 +35,8 @@ import java.util.List; import java.util.Objects; +import static java.lang.Integer.max; + public class CodeActionAssert extends AbstractAssert { private DocumentContext documentContext; @@ -88,7 +90,7 @@ public CodeActionAssert fixes(Diagnostic diagnostic) { startLine = end.getLine(); startChar = end.getCharacter(); endLine = contentList.length - 1; - endChar = contentList[endLine].length() - 1; + endChar = max(contentList[endLine].length() - 1, 0); Range endRange = Ranges.create(startLine, startChar, endLine, endChar); final String endText = documentContext.getText(endRange); From 346fe69bd5075af0b99a2c32e257fe7a1c16b5b9 Mon Sep 17 00:00:00 2001 From: evgeniy Date: Tue, 14 Apr 2020 06:48:01 +0300 Subject: [PATCH 048/444] Cleanup code, remove doubles. --- .../CreateQueryInCycleDiagnostic.java | 21 +++++++++---------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java index a187494e908..06ff11b434a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java @@ -236,6 +236,14 @@ private Set getTypesFromComplexIdentifier(BSLParser.ComplexIdentifierCon } } + private void visitDescendantCodeBlock(BSLParser.CodeBlockContext ctx){ + Optional.ofNullable(ctx) + .map(e -> e.children) + .stream() + .flatMap(Collection::stream) + .forEach( t -> t.accept(this)); + } + @Override public ParseTree visitAccessCall(BSLParser.AccessCallContext ctx) { if (!EXECUTE_CALL_PATTERN.matcher(ctx.methodCall().methodName().getText()).matches()) { @@ -276,17 +284,12 @@ public ParseTree visitAccessCall(BSLParser.AccessCallContext ctx) { @Override public ParseTree visitForEachStatement(BSLParser.ForEachStatementContext ctx) { boolean alreadyInCycle = currentScope.codeFlowInCycle(); - ParseTree result; currentScope.flowMode.push(CodeFlowType.CYCLE); if(alreadyInCycle) { Optional.ofNullable(ctx.expression()) .ifPresent( e -> e.accept(this)); } - Optional.ofNullable(ctx.codeBlock()) - .map(e -> e.children) - .stream(). - flatMap(Collection::stream) - .forEach( t -> t.accept(this)); + visitDescendantCodeBlock(ctx.codeBlock()); currentScope.flowMode.pop(); return null; } @@ -307,11 +310,7 @@ public ParseTree visitForStatement(BSLParser.ForStatementContext ctx) { ctx.expression() .forEach( e-> e.accept(this)); } - Optional.ofNullable(ctx.codeBlock()) - .map(e -> e.children) - .stream() - .flatMap(Collection::stream) - .forEach( t -> t.accept(this)); + visitDescendantCodeBlock(ctx.codeBlock()); currentScope.flowMode.pop(); return null; } From 6a9edd24f5b13066a26c2eafc12b9d9b6e2d4260 Mon Sep 17 00:00:00 2001 From: evgeniy Date: Tue, 14 Apr 2020 06:52:53 +0300 Subject: [PATCH 049/444] return context --- .../diagnostics/CreateQueryInCycleDiagnostic.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java index 06ff11b434a..7aa5f8f96a1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java @@ -291,7 +291,7 @@ public ParseTree visitForEachStatement(BSLParser.ForEachStatementContext ctx) { } visitDescendantCodeBlock(ctx.codeBlock()); currentScope.flowMode.pop(); - return null; + return ctx; } @Override @@ -312,7 +312,7 @@ public ParseTree visitForStatement(BSLParser.ForStatementContext ctx) { } visitDescendantCodeBlock(ctx.codeBlock()); currentScope.flowMode.pop(); - return null; + return ctx; } public enum CodeFlowType { From 02b3f0a4c6aea7f7b0b434b576274303177c38a9 Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Tue, 14 Apr 2020 11:02:41 +0300 Subject: [PATCH 050/444] =?UTF-8?q?=D0=BA=D1=82=D0=BE-=D1=82=D0=BE=20?= =?UTF-8?q?=D0=BD=D0=B5=20=D1=81=D0=B4=D0=B5=D0=BB=D0=B0=D0=BB=20precommit?= =?UTF-8?q?=20-=20=D1=82.=D0=BA.=20=D0=BF=D1=80=D0=B8=20=D0=B5=D0=B3=D0=BE?= =?UTF-8?q?=20=D0=B2=D1=8B=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5=D0=BD=D0=B8=D0=B8?= =?UTF-8?q?=20=D0=BF=D1=80=D0=B0=D0=B2=D0=B8=D0=BB=D1=8C=D0=BD=D0=BE=20?= =?UTF-8?q?=D0=B2=D1=83=D0=B4=D0=B0=D0=BB=D1=8F=D0=B5=D1=82=D1=81=D1=8F=20?= =?UTF-8?q?=D0=BB=D0=B8=D1=88=D0=BD=D0=B8=D0=B9=20=D0=BF=D1=80=D0=BE=D0=B1?= =?UTF-8?q?=D0=B5=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/diagnostics/MethodSize.md | 2 +- docs/en/diagnostics/index.md | 2 +- .../bsl/languageserver/configuration/diagnostics-schema.json | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/en/diagnostics/MethodSize.md b/docs/en/diagnostics/MethodSize.md index e3f6095d305..33027e71da9 100644 --- a/docs/en/diagnostics/MethodSize.md +++ b/docs/en/diagnostics/MethodSize.md @@ -1,4 +1,4 @@ -# Method size (MethodSize) +# Method size (MethodSize) | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 246b94d7e89..541b675e17d 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -50,7 +50,7 @@ Total: **87** | [InvalidCharacterInFile](InvalidCharacterInFile.md) | Invalid character | Yes | Major | Error | `error`
`standard`
`unpredictable` | | [LineLength](LineLength.md) | Line Length limit | Yes | Minor | Code smell | `standard`
`badpractice` | | [MagicNumber](MagicNumber.md) | Magic numbers | Yes | Minor | Code smell | `badpractice` | -| [MethodSize](MethodSize.md) | Method size | Yes | Major | Code smell | `badpractice` | +| [MethodSize](MethodSize.md) | Method size | Yes | Major | Code smell | `badpractice` | | [MissingCodeTryCatchEx](MissingCodeTryCatchEx.md) | Missing code in Raise block in "Try ... Raise ... EndTry" | Yes | Major | Error | `standard`
`badpractice` | | [MissingSpace](MissingSpace.md) | Missing spaces to the left or right of operators + - * / = % < > <> <= >=, and also to the right of , and ; | Yes | Info | Code smell | `badpractice` | | [MissingTemporaryFileDeletion](MissingTemporaryFileDeletion.md) | Missing temporary file deletion after using | Yes | Major | Error | `badpractice`
`standard` | diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json index e50e2182208..2fce47dae7d 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json @@ -409,13 +409,13 @@ "$id": "#/definitions/MagicNumber" }, "MethodSize": { - "description": "Method size ", + "description": "Method size", "default": null, "type": [ "boolean", "object" ], - "title": "Method size ", + "title": "Method size", "properties": { "maxMethodSize": { "description": "Max method line count.", From bf03f7d9fe23c488fd63eb49fae44e2e6924b8f5 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Tue, 14 Apr 2020 15:14:36 +0300 Subject: [PATCH 051/444] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D1=81=D1=81=D1=8B=D0=BB=D0=BA=D1=83=20=D0=BD?= =?UTF-8?q?=D0=B0=20=D1=80=D0=B5=D0=B7=D1=83=D0=BB=D1=8C=D1=82=D0=B0=D1=82?= =?UTF-8?q?=D1=8B=20=D0=B1=D0=B5=D0=BD=D1=87=D0=BC=D0=B0=D1=80=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f63eb6fdc0c..ed3f50246d0 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Сайт проекта - https://1c-syntax.github.io/bsl-language-server -Замеры производительности - [SSL 3.1](https://1c-syntax.github.io/bsl-language-serve/bench/index.html) +Замеры производительности - [SSL 3.1](https://1c-syntax.github.io/bsl-language-server/dev/bench/index.html) [English version](docs/en/index.md) From 6de0173294d9f212160881706c84abcfe1bdd4c6 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Tue, 14 Apr 2020 21:29:47 +0300 Subject: [PATCH 052/444] =?UTF-8?q?=D0=9F=D0=B0=D1=80=D1=81=D0=B5=D1=80=20?= =?UTF-8?q?=D0=BE=D1=82=D0=B4=D0=B0=D0=B5=D1=82=20EOF=20=D0=B2=20Hidden=20?= =?UTF-8?q?Channel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle.kts | 2 +- .../bsl/languageserver/context/DocumentContextTest.java | 4 ++-- src/test/resources/providers/format_formatted.bsl | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index ebceff53a86..80f686f8f9e 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -77,7 +77,7 @@ dependencies { implementation("org.reflections", "reflections", "0.9.10") - implementation("com.github.1c-syntax", "bsl-parser", "0.13.0") { + implementation("com.github.1c-syntax", "bsl-parser", "01cc1512e10b667a0ec3fdd2307ca0221bf52684") { exclude("com.tunnelvisionlabs", "antlr4-annotations") exclude("com.ibm.icu", "*") exclude("org.antlr", "ST4") diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java index 648a11eb1b7..5ce1568ea86 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java @@ -43,12 +43,12 @@ class DocumentContextTest { void testRebuild() throws IOException { DocumentContext documentContext = getDocumentContext("./src/test/resources/context/DocumentContextRebuildFirstTest.bsl"); - assertThat(documentContext.getTokens()).hasSize(38); + assertThat(documentContext.getTokens()).hasSize(39); File file = new File("./src/test/resources/context/DocumentContextRebuildSecondTest.bsl"); String fileContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8); documentContext.rebuild(fileContent); - assertThat(documentContext.getTokens()).hasSize(15); + assertThat(documentContext.getTokens()).hasSize(16); } @Test diff --git a/src/test/resources/providers/format_formatted.bsl b/src/test/resources/providers/format_formatted.bsl index eadca82d3ea..27cb8a69477 100644 --- a/src/test/resources/providers/format_formatted.bsl +++ b/src/test/resources/providers/format_formatted.bsl @@ -30,4 +30,4 @@ Процедура Третья() // Комментарий с пробелами слева // Другой комментарий с пробелами -КонецПроцедуры +КонецПроцедуры \ No newline at end of file From 197f05077953508b963d16b30e92785400c7c39f Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Tue, 14 Apr 2020 21:51:27 +0300 Subject: [PATCH 053/444] EOF test --- .../context/DocumentContextTest.java | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java index 5ce1568ea86..30973fbd1f7 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java @@ -25,6 +25,8 @@ import com.github._1c_syntax.bsl.languageserver.context.symbol.RegionSymbol; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import lombok.SneakyThrows; +import org.antlr.v4.runtime.Lexer; +import org.antlr.v4.runtime.Token; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.reflect.FieldUtils; import org.junit.jupiter.api.Test; @@ -82,8 +84,8 @@ void testMethodParametersComputesCorrectly() { .hasSize(4) .anyMatch(parameterDefinition -> parameterDefinition.getName().equals("Парам1") - && !parameterDefinition.isByValue() - && !parameterDefinition.isOptional() + && !parameterDefinition.isByValue() + && !parameterDefinition.isOptional() ) .anyMatch(parameterDefinition -> parameterDefinition.getName().equals("Парам2") @@ -220,4 +222,15 @@ void testContentList() { assertThat(contentList).hasSize(40); } -} \ No newline at end of file + @Test + void testEOF() { + // given + DocumentContext documentContext = getDocumentContext(); + // when + List tokens = documentContext.getTokens(); + Token lastToken = tokens.get(tokens.size() - 1); + // then + assertThat(lastToken.getType()).isEqualTo(Lexer.EOF); + assertThat(lastToken.getChannel()).isEqualTo(Lexer.HIDDEN); + } +} From e93883c94bac1affb541e89a15176d1645a9ad7c Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Wed, 15 Apr 2020 10:30:43 +0300 Subject: [PATCH 054/444] parser version bump --- build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle.kts b/build.gradle.kts index 80f686f8f9e..6b44f06a1ca 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -77,7 +77,7 @@ dependencies { implementation("org.reflections", "reflections", "0.9.10") - implementation("com.github.1c-syntax", "bsl-parser", "01cc1512e10b667a0ec3fdd2307ca0221bf52684") { + implementation("com.github.1c-syntax", "bsl-parser", "0.14.0") { exclude("com.tunnelvisionlabs", "antlr4-annotations") exclude("com.ibm.icu", "*") exclude("org.antlr", "ST4") From 027f82941995df3fa75af3b0a7f76c4c5f143237 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Wed, 15 Apr 2020 15:12:40 +0300 Subject: [PATCH 055/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BC=D0=BE=D0=BB=D1=87=D0=B0=D0=BB=D0=B8=D0=B2=D1=8B?= =?UTF-8?q?=D0=B9=20=D1=80=D0=B5=D0=B6=D0=B8=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../bsl/languageserver/BSLLSPLauncher.java | 8 ++++ .../languageserver/cli/AnalyzeCommand.java | 19 +++++++--- .../bsl/languageserver/cli/FormatCommand.java | 20 ++++++---- .../languageserver/BSLLSPLauncherTest.java | 38 +++++++++++++++++++ 4 files changed, 71 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java index ec17fdea384..9b53f8192f7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java @@ -132,11 +132,19 @@ public static Options createOptions() { "Show version." ); + Option silentMode = new Option( + "S", + "silent", + false, + "Silent mode" + ); + createdOptions.addOption(analyze); createdOptions.addOption(format); createdOptions.addOption(srcDir); createdOptions.addOption(outputDir); createdOptions.addOption(reporter); + createdOptions.addOption(silentMode); createdOptions.addOption(configurationOption); createdOptions.addOption(help); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java index d59471edc28..675837c73cf 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java @@ -61,7 +61,7 @@ * -c, (--configuration) <arg> - Путь к конфигурационному файлу BSL Language Server (.bsl-language-server.json). * Возможно указывать как в абсолютном, так и относительном виде. Если параметр опущен, * то будут использованы настройки по умолчанию. - * -r, (--reporter) <arg> - Ключи "Репортеров", т.е. форматов отчетов, котрые необходимо сгенерировать после + * -r, (--reporter) <arg> - Ключи "Репортеров", т.е. форматов отчетов, котрые необходимо сгенерировать после * выполнения анализа. Может быть указано более одного ключа. Если параметр опущен, * то вывод результата будет призведен в консоль. * Выводимая информация: @@ -83,6 +83,7 @@ public int execute() { String srcDirOption = cmd.getOptionValue("srcDir", ""); String outputDirOption = cmd.getOptionValue("outputDir", ""); String configurationOption = cmd.getOptionValue("configuration", ""); + boolean silentMode = cmd.hasOption("silent"); Path srcDir = Absolute.path(srcDirOption); File configurationFile = new File(configurationOption); @@ -97,13 +98,19 @@ public int execute() { Collection files = FileUtils.listFiles(srcDir.toFile(), new String[]{"bsl", "os"}, true); List fileInfos; - try (ProgressBar pb = new ProgressBar("Analyzing files...", files.size(), ProgressBarStyle.ASCII)) { + if (silentMode) { fileInfos = files.parallelStream() - .map((File file) -> { - pb.step(); - return getFileInfoFromFile(srcDir, file); - }) + .map((File file) -> getFileInfoFromFile(srcDir, file)) .collect(Collectors.toList()); + } else { + try (ProgressBar pb = new ProgressBar("Analyzing files...", files.size(), ProgressBarStyle.ASCII)) { + fileInfos = files.parallelStream() + .map((File file) -> { + pb.step(); + return getFileInfoFromFile(srcDir, file); + }) + .collect(Collectors.toList()); + } } AnalysisInfo analysisInfo = new AnalysisInfo(LocalDateTime.now(), fileInfos, srcDirOption); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java index a622840df1d..841882699c5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java @@ -46,13 +46,12 @@ * Ключ команды: * -f, (--format) * Параметры: - * -s, (--srcDir) <arg> - Путь к каталогу исходных файлов. + * -s, (--srcDir) <arg> - Путь к каталогу исходных файлов. * Возможно указывать как в абсолютном, так и относительном виде. Если параметр опущен, * то анализ выполняется в текущем каталоге запуска. * Выводимая информация: * Выполняет форматирование исходного кода в файлах каталога. Для форматирования используются правила и настройки * "форматтера" FormatProvider, т.е. пользователь никак не может овлиять на результат. - * */ public class FormatCommand implements Command { @@ -69,17 +68,22 @@ public int execute() { serverContext.clear(); String srcDirOption = cmd.getOptionValue("srcDir", ""); + boolean silentMode = cmd.hasOption("silent"); Path srcDir = Absolute.path(srcDirOption); Collection files = FileUtils.listFiles(srcDir.toFile(), new String[]{"bsl", "os"}, true); - try (ProgressBar pb = new ProgressBar("Formatting files...", files.size(), ProgressBarStyle.ASCII)) { - files.parallelStream() - .forEach((File file) -> { - pb.step(); - formatFile(file); - }); + if (silentMode) { + files.parallelStream().forEach(this::formatFile); + } else { + try (ProgressBar pb = new ProgressBar("Formatting files...", files.size(), ProgressBarStyle.ASCII)) { + files.parallelStream() + .forEach((File file) -> { + pb.step(); + formatFile(file); + }); + } } return 0; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java index 7d0a3208d61..7c4c26930b0 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java @@ -105,6 +105,25 @@ void testAnalyze() { // assertThat(errContent.toString()).contains("100%"); } + @Test + @ExpectSystemExitWithStatus(0) + void testAnalyzeSilent() { + // given + String[] args = new String[]{"--analyze", "--srcDir", "./src/test/resources/cli", "-S"}; + + // when + try { + BSLLSPLauncher.main(args); + } catch (RuntimeException ignored) { + // catch prevented system.exit call + } + + // then + // main-method should runs without exceptions + assertThat(outContent.toString()).isEmpty(); + assertThat(errContent.toString()).isEmpty(); + } + @Test @ExpectSystemExitWithStatus(0) void testFormat() { @@ -125,6 +144,25 @@ void testFormat() { // assertThat(errContent.toString()).contains("100%"); } + @Test + @ExpectSystemExitWithStatus(0) + void testFormatSilent() { + // given + String[] args = new String[]{"--format", "--srcDir", "./src/test/resources/cli", "-S"}; + + // when + try { + BSLLSPLauncher.main(args); + } catch (RuntimeException ignored) { + // catch prevented system.exit call + } + + // then + // main-method should runs without exceptions + assertThat(outContent.toString()).isEmpty(); + assertThat(errContent.toString()).isEmpty(); + } + @Test void testWithoutParameters() { // given From dca59ba0fb7971c8ad6da41cf05797903f89ea9c Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Wed, 15 Apr 2020 16:20:24 +0300 Subject: [PATCH 056/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BF=D0=BE=D1=82=D0=B5=D1=80=D1=8F=D0=BD=D0=BD=D1=83?= =?UTF-8?q?=D1=8E=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC=D0=B5=D0=BD=D1=82=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + docs/en/index.md | 1 + docs/index.md | 1 + .../github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java | 1 + .../github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java | 1 + 5 files changed, 5 insertions(+) diff --git a/README.md b/README.md index ed3f50246d0..e605babc234 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,7 @@ usage: BSL language server [-a] [-c ] [-f] [-h] [-o ] [-r ] [-s < -r,--reporter Reporter key -s,--srcDir Source directory -v,--version Version + -S,--silent Silent mode ``` При запуске BSL Language Server в обычном режиме будет запущен сам Language Server, взаимодействующий по протоколу [LSP](https://microsoft.github.io/language-server-protocol/). Для взаимодействия используются stdin и stdout. diff --git a/docs/en/index.md b/docs/en/index.md index e1bdd5980f4..ea813b5468c 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -58,6 +58,7 @@ usage: BSL language server [-a] [-c ] [-f] [-h] [-o ] [-r ] [-s < -r,--reporter Reporter key -s,--srcDir Source directory -v,--version Version + -S,--silent Silent mode ``` Starting BSL Language Server in standard mode will run the Language Server communicating via [LSP]([language server protocol](https://microsoft.github.io/language-server-protocol/)). stdin and stdout are used for communication. diff --git a/docs/index.md b/docs/index.md index 224a4ceb131..cd6be8638e3 100644 --- a/docs/index.md +++ b/docs/index.md @@ -58,6 +58,7 @@ usage: BSL language server [-a] [-c ] [-f] [-h] [-o ] [-r ] [-s < -r,--reporter Reporter key -s,--srcDir Source directory -v,--version Version + -S,--silent Silent mode ``` При запуске BSL Language Server в обычном режиме будет запущен сам Language Server, взаимодействующий по протоколу [LSP]([language server protocol](https://microsoft.github.io/language-server-protocol/)). Для взаимодействия используются stdin и stdout. diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java index 675837c73cf..5de9afbb83d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java @@ -64,6 +64,7 @@ * -r, (--reporter) <arg> - Ключи "Репортеров", т.е. форматов отчетов, котрые необходимо сгенерировать после * выполнения анализа. Может быть указано более одного ключа. Если параметр опущен, * то вывод результата будет призведен в консоль. + * -S, (--silent) - Флаг для отключения вывода прогресс-бара и дополнительных сообщений в консоль * Выводимая информация: * Выполняет анализ каталога исходных файлов и генерацию файлов отчета. Для каждого указанного ключа "Репортера" * создается отдельный файл (каталог файлов). Реализованные "репортеры" находятся в пакете "reporter". diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java index 841882699c5..74cf9df03b1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java @@ -49,6 +49,7 @@ * -s, (--srcDir) <arg> - Путь к каталогу исходных файлов. * Возможно указывать как в абсолютном, так и относительном виде. Если параметр опущен, * то анализ выполняется в текущем каталоге запуска. + * -S, (--silent) - Флаг для отключения вывода прогресс-бара и дополнительных сообщений в консоль * Выводимая информация: * Выполняет форматирование исходного кода в файлах каталога. Для форматирования используются правила и настройки * "форматтера" FormatProvider, т.е. пользователь никак не может овлиять на результат. From 457a0eeb84b10d078df92a20035702474ec89034 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Wed, 15 Apr 2020 16:23:54 +0300 Subject: [PATCH 057/444] thisObjectAssignDiagnostic --- docs/diagnostics/ThisObjectAssign.md | 40 ++++++ docs/diagnostics/index.md | 5 +- docs/en/diagnostics/ThisObjectAssign.md | 36 ++++++ docs/en/diagnostics/index.md | 5 +- .../ThisObjectAssignDiagnostic.java | 82 +++++++++++++ .../configuration/diagnostics-schema.json | 10 ++ .../languageserver/configuration/schema.json | 3 + .../ThisObjectAssignDiagnostic_en.properties | 2 + .../ThisObjectAssignDiagnostic_ru.properties | 2 + .../ThisObjectAssignDiagnosticTest.java | 114 ++++++++++++++++++ .../ThisObjectAssignDiagnostic.bsl | 5 + 11 files changed, 300 insertions(+), 4 deletions(-) create mode 100644 docs/diagnostics/ThisObjectAssign.md create mode 100644 docs/en/diagnostics/ThisObjectAssign.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/ThisObjectAssignDiagnostic.bsl diff --git a/docs/diagnostics/ThisObjectAssign.md b/docs/diagnostics/ThisObjectAssign.md new file mode 100644 index 00000000000..98812324feb --- /dev/null +++ b/docs/diagnostics/ThisObjectAssign.md @@ -0,0 +1,40 @@ +# Присвоение заначения свойству ЭтотОбъект (ThisObjectAssign) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Ошибка` | `BSL` | `Блокирующий` | `Да` | `1` | `error` | + + +## Описание диагностики +В модулях управляемых форм и общих модулях не должно быть переменной с именем "ЭтотОбъект". + +Часто ошибка появляется при поднятии версии режима совместимости конфигурации т.к. в версиях до 8.3.3 +свойство "ЭтотОбъект" у управляемых форм и общих модулей отсутствовало. И могло быть +использовано как переменная. + +## Примеры + +Неправильно: +```bsl + +ЭтотОбъект = РеквизитФормыВЗначение("Объект"); + +``` + +## Источники + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:ThisObjectAssign-off +// BSLLS:ThisObjectAssign-on +``` + +### Параметр конфигурационного файла + +```json +"ThisObjectAssign": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 53ae4ea5032..d1eccfc2ac0 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,11 +8,11 @@ ## Список реализованных диагностик -Общее количество: **87** +Общее количество: **88** * Дефект кода: **55** * Уязвимость: **2** -* Ошибка: **28** +* Ошибка: **29** * Потенциальная уязвимость: **2** | Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги | @@ -80,6 +80,7 @@ | [SpaceAtStartComment](SpaceAtStartComment.md) | Пробел в начале комментария | Да | Информационный | Дефект кода | `standard` | | [TempFilesDir](TempFilesDir.md) | Вызов функции КаталогВременныхФайлов() | Да | Важный | Дефект кода | `standard`
`badpractice` | | [TernaryOperatorUsage](TernaryOperatorUsage.md) | Использование тернарного оператора | Нет | Незначительный | Дефект кода | `brainoverload` | +| [ThisObjectAssign](ThisObjectAssign.md) | Присвоение заначения свойству ЭтотОбъект | Да | Блокирующий | Ошибка | `error` | | [TimeoutsInExternalResources](TimeoutsInExternalResources.md) | Таймауты при работе с внешними ресурсами | Да | Критичный | Ошибка | `unpredictable`
`standard` | | [TooManyReturns](TooManyReturns.md) | Метод не должен содержать много возвратов | Нет | Незначительный | Дефект кода | `brainoverload` | | [TryNumber](TryNumber.md) | Приведение к числу в попытке | Да | Важный | Дефект кода | `standard` | diff --git a/docs/en/diagnostics/ThisObjectAssign.md b/docs/en/diagnostics/ThisObjectAssign.md new file mode 100644 index 00000000000..fc8f4d6a83a --- /dev/null +++ b/docs/en/diagnostics/ThisObjectAssign.md @@ -0,0 +1,36 @@ +# ThisObject assign (ThisObjectAssign) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Error` | `BSL` | `Blocker` | `Yes` | `1` | `error` | + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:ThisObjectAssign-off +// BSLLS:ThisObjectAssign-on +``` + +### Parameter for config + +```json +"ThisObjectAssign": false +``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 541b675e17d..92ef4e4c507 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,9 +8,9 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **87** +Total: **88** -* Error: **28** +* Error: **29** * Code smell: **55** * Vulnerability: **2** * Security Hotspot: **2** @@ -80,6 +80,7 @@ Total: **87** | [SpaceAtStartComment](SpaceAtStartComment.md) | Space at the beginning of the comment | Yes | Info | Code smell | `standard` | | [TempFilesDir](TempFilesDir.md) | TempFilesDir() method call | Yes | Major | Code smell | `standard`
`badpractice` | | [TernaryOperatorUsage](TernaryOperatorUsage.md) | Ternary operator usage | No | Minor | Code smell | `brainoverload` | +| [ThisObjectAssign](ThisObjectAssign.md) | ThisObject assign | Yes | Blocker | Error | `error` | | [TimeoutsInExternalResources](TimeoutsInExternalResources.md) | Timeouts working with external resources | Yes | Critical | Error | `unpredictable`
`standard` | | [TooManyReturns](TooManyReturns.md) | Methods should not have too many return statements | No | Minor | Code smell | `brainoverload` | | [TryNumber](TryNumber.md) | Cast to number of try catch block | Yes | Major | Code smell | `standard` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnostic.java new file mode 100644 index 00000000000..83c03974bdd --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnostic.java @@ -0,0 +1,82 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCompatibilityMode; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.TerminalNode; + +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.ERROR, + severity = DiagnosticSeverity.BLOCKER, + scope = DiagnosticScope.BSL, + modules = { + ModuleType.CommonModule, + ModuleType.FormModule + }, + minutesToFix = 1, + compatibilityMode = DiagnosticCompatibilityMode.COMPATIBILITY_MODE_8_3_3, + tags = { + DiagnosticTag.ERROR + } + +) +public class ThisObjectAssignDiagnostic extends AbstractVisitorDiagnostic { + + private static final Pattern thisObjectPattern = Pattern.compile( + "(этотобъект|thisobject)", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE + ); + + public ThisObjectAssignDiagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + public ParseTree visitLValue(BSLParser.LValueContext ctx) { + + TerminalNode identifier = ctx.IDENTIFIER(); + + if (identifier == null + || ctx.acceptor() != null) { + return ctx; + } + + if (!thisObjectPattern.matcher(identifier.getText()).matches()) { + return ctx; + } + + diagnosticStorage.addDiagnostic(identifier); + + return ctx; + } +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json index 2fce47dae7d..3369ec036ca 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json @@ -828,6 +828,16 @@ "title": "Ternary operator usage", "$id": "#/definitions/TernaryOperatorUsage" }, + "ThisObjectAssign": { + "description": "ThisObject assign", + "default": null, + "type": [ + "boolean", + "object" + ], + "title": "ThisObject assign", + "$id": "#/definitions/ThisObjectAssign" + }, "TimeoutsInExternalResources": { "description": "Timeouts working with external resources", "default": null, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index f31df27a92d..c34797acb3e 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -290,6 +290,9 @@ "TernaryOperatorUsage": { "$ref": "diagnostics-schema.json#/definitions/TernaryOperatorUsage" }, + "ThisObjectAssign": { + "$ref": "diagnostics-schema.json#/definitions/ThisObjectAssign" + }, "TimeoutsInExternalResources": { "$ref": "diagnostics-schema.json#/definitions/TimeoutsInExternalResources" }, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnostic_en.properties new file mode 100644 index 00000000000..bb0dd82ab88 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=The ThisObject property is read only +diagnosticName=ThisObject assign diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnostic_ru.properties new file mode 100644 index 00000000000..efac1ae6719 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Свойство ЭтотОбъект доступно только для чтения +diagnosticName=Присвоение заначения свойству ЭтотОбъект diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnosticTest.java new file mode 100644 index 00000000000..3c988ea61d0 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnosticTest.java @@ -0,0 +1,114 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.mdclasses.metadata.additional.CompatibilityMode; +import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; +import org.eclipse.lsp4j.Diagnostic; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +class ThisObjectAssignDiagnosticTest extends AbstractDiagnosticTest { + ThisObjectAssignDiagnosticTest() { + super(ThisObjectAssignDiagnostic.class); + } + + @Test + void test832() { + + DocumentContext documentContext = setCompatibilityMode(new CompatibilityMode(3, 2)); + + List diagnostics = getDiagnosticsFiltered(documentContext); + + assertThat(diagnostics).hasSize(0); + + } + + + @Test + void test833() { + + DocumentContext documentContext = setCompatibilityMode(new CompatibilityMode(3, 4)); + + List diagnostics = getDiagnosticsFiltered(documentContext); + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(1, 4, 14); + + } + + @Test + void test836() { + + DocumentContext documentContext = setCompatibilityMode(new CompatibilityMode(3, 14)); + + List diagnostics = getDiagnosticsFiltered(documentContext); + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(1, 4, 14); + + } + + + @NotNull + private DocumentContext setCompatibilityMode(CompatibilityMode version) { + + var documentContext = spy(getDocumentContext()); + var serverContext = spy(documentContext.getServerContext()); + var configuration = spy(serverContext.getConfiguration()); + + when(documentContext.getServerContext()).thenReturn(serverContext); + when(documentContext.getModuleType()).thenReturn(ModuleType.CommonModule); + + when(serverContext.getConfiguration()).thenReturn(configuration); + when(configuration.getCompatibilityMode()).thenReturn(version); + + return documentContext; + } + + private List getDiagnosticsFiltered(DocumentContext documentContext) { + DiagnosticSupplier diagnosticSupplier = new DiagnosticSupplier(LanguageServerConfiguration.create()); + + Optional first = diagnosticSupplier + .getDiagnosticInstances(documentContext) + .stream() + .filter(di -> di instanceof ThisObjectAssignDiagnostic) + .findFirst(); + + List diagnostics = new ArrayList<>(); + if (first.isPresent()) { + diagnostics = first.get().getDiagnostics(documentContext); + } + return diagnostics; + } + +} diff --git a/src/test/resources/diagnostics/ThisObjectAssignDiagnostic.bsl b/src/test/resources/diagnostics/ThisObjectAssignDiagnostic.bsl new file mode 100644 index 00000000000..73c0ba0ca41 --- /dev/null +++ b/src/test/resources/diagnostics/ThisObjectAssignDiagnostic.bsl @@ -0,0 +1,5 @@ +Процедура ПриСозданииНаСервере() + ЭтотОбъект = РеквизитФормыВЗначение("Объект"); +КонецПроцедуры + +ЭтотОбъект.Реквизит1 = А; From 76ddeef323459739b0ec4c040d7d6817dbd821ea Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Wed, 15 Apr 2020 16:40:37 +0300 Subject: [PATCH 058/444] stream magic --- .../ThisObjectAssignDiagnosticTest.java | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnosticTest.java index 3c988ea61d0..3288aa4e8d0 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnosticTest.java @@ -29,9 +29,8 @@ import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Test; -import java.util.ArrayList; +import java.util.Collections; import java.util.List; -import java.util.Optional; import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; import static org.mockito.Mockito.spy; @@ -98,17 +97,14 @@ private DocumentContext setCompatibilityMode(CompatibilityMode version) { private List getDiagnosticsFiltered(DocumentContext documentContext) { DiagnosticSupplier diagnosticSupplier = new DiagnosticSupplier(LanguageServerConfiguration.create()); - Optional first = diagnosticSupplier + return diagnosticSupplier .getDiagnosticInstances(documentContext) .stream() - .filter(di -> di instanceof ThisObjectAssignDiagnostic) - .findFirst(); - - List diagnostics = new ArrayList<>(); - if (first.isPresent()) { - diagnostics = first.get().getDiagnostics(documentContext); - } - return diagnostics; + .filter(ThisObjectAssignDiagnostic.class::isInstance) + .findFirst() + .map(bslDiagnostic -> bslDiagnostic.getDiagnostics(documentContext)) + .orElseGet(Collections::emptyList); + } } From 343551fba97f736439166e7b1ff1e708b9273785 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Wed, 15 Apr 2020 16:44:07 +0300 Subject: [PATCH 059/444] notNul rm --- .../diagnostics/ThisObjectAssignDiagnosticTest.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnosticTest.java index 3288aa4e8d0..9644fca0c60 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnosticTest.java @@ -26,7 +26,6 @@ import com.github._1c_syntax.mdclasses.metadata.additional.CompatibilityMode; import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; import org.eclipse.lsp4j.Diagnostic; -import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Test; import java.util.Collections; @@ -77,8 +76,6 @@ void test836() { } - - @NotNull private DocumentContext setCompatibilityMode(CompatibilityMode version) { var documentContext = spy(getDocumentContext()); From da012e029de56bcdd3fc4d710b5bc3fee5a2fd06 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Wed, 15 Apr 2020 17:10:59 +0300 Subject: [PATCH 060/444] =?UTF-8?q?=D0=98=D0=B7=D0=BC=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BA=D0=BB=D1=8E=D1=87=20=D0=BD=D0=B0=20-q?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/en/index.md | 2 +- docs/index.md | 2 +- .../github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java | 2 +- .../_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java | 2 +- .../_1c_syntax/bsl/languageserver/cli/FormatCommand.java | 2 +- .../_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java | 4 ++-- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index e605babc234..aea179d9510 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ usage: BSL language server [-a] [-c ] [-f] [-h] [-o ] [-r ] [-s < -r,--reporter Reporter key -s,--srcDir Source directory -v,--version Version - -S,--silent Silent mode + -q,--silent Silent mode ``` При запуске BSL Language Server в обычном режиме будет запущен сам Language Server, взаимодействующий по протоколу [LSP](https://microsoft.github.io/language-server-protocol/). Для взаимодействия используются stdin и stdout. diff --git a/docs/en/index.md b/docs/en/index.md index ea813b5468c..6d46285df71 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -58,7 +58,7 @@ usage: BSL language server [-a] [-c ] [-f] [-h] [-o ] [-r ] [-s < -r,--reporter Reporter key -s,--srcDir Source directory -v,--version Version - -S,--silent Silent mode + -q,--silent Silent mode ``` Starting BSL Language Server in standard mode will run the Language Server communicating via [LSP]([language server protocol](https://microsoft.github.io/language-server-protocol/)). stdin and stdout are used for communication. diff --git a/docs/index.md b/docs/index.md index cd6be8638e3..20e94187313 100644 --- a/docs/index.md +++ b/docs/index.md @@ -58,7 +58,7 @@ usage: BSL language server [-a] [-c ] [-f] [-h] [-o ] [-r ] [-s < -r,--reporter Reporter key -s,--srcDir Source directory -v,--version Version - -S,--silent Silent mode + -q,--silent Silent mode ``` При запуске BSL Language Server в обычном режиме будет запущен сам Language Server, взаимодействующий по протоколу [LSP]([language server protocol](https://microsoft.github.io/language-server-protocol/)). Для взаимодействия используются stdin и stdout. diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java index 9b53f8192f7..e8b394b2e04 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java @@ -133,7 +133,7 @@ public static Options createOptions() { ); Option silentMode = new Option( - "S", + "q", "silent", false, "Silent mode" diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java index 5de9afbb83d..638ef5c6334 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java @@ -64,7 +64,7 @@ * -r, (--reporter) <arg> - Ключи "Репортеров", т.е. форматов отчетов, котрые необходимо сгенерировать после * выполнения анализа. Может быть указано более одного ключа. Если параметр опущен, * то вывод результата будет призведен в консоль. - * -S, (--silent) - Флаг для отключения вывода прогресс-бара и дополнительных сообщений в консоль + * -q, (--silent) - Флаг для отключения вывода прогресс-бара и дополнительных сообщений в консоль * Выводимая информация: * Выполняет анализ каталога исходных файлов и генерацию файлов отчета. Для каждого указанного ключа "Репортера" * создается отдельный файл (каталог файлов). Реализованные "репортеры" находятся в пакете "reporter". diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java index 74cf9df03b1..99d6cc4e31d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java @@ -49,7 +49,7 @@ * -s, (--srcDir) <arg> - Путь к каталогу исходных файлов. * Возможно указывать как в абсолютном, так и относительном виде. Если параметр опущен, * то анализ выполняется в текущем каталоге запуска. - * -S, (--silent) - Флаг для отключения вывода прогресс-бара и дополнительных сообщений в консоль + * -q, (--silent) - Флаг для отключения вывода прогресс-бара и дополнительных сообщений в консоль * Выводимая информация: * Выполняет форматирование исходного кода в файлах каталога. Для форматирования используются правила и настройки * "форматтера" FormatProvider, т.е. пользователь никак не может овлиять на результат. diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java index 7c4c26930b0..317d30ce095 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java @@ -109,7 +109,7 @@ void testAnalyze() { @ExpectSystemExitWithStatus(0) void testAnalyzeSilent() { // given - String[] args = new String[]{"--analyze", "--srcDir", "./src/test/resources/cli", "-S"}; + String[] args = new String[]{"--analyze", "--srcDir", "./src/test/resources/cli", "-q"}; // when try { @@ -148,7 +148,7 @@ void testFormat() { @ExpectSystemExitWithStatus(0) void testFormatSilent() { // given - String[] args = new String[]{"--format", "--srcDir", "./src/test/resources/cli", "-S"}; + String[] args = new String[]{"--format", "--srcDir", "./src/test/resources/cli", "-q"}; // when try { From b76eca860a3a9b85afed549bb0d141ff6427ac63 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Wed, 15 Apr 2020 22:05:36 +0300 Subject: [PATCH 061/444] EOF parse error fix --- .../diagnostics/ParseErrorDiagnostic.java | 10 +++++++++- .../diagnostics/ParseErrorDiagnosticTest.java | 12 ++++++++++++ .../diagnostics/ParseErrorDiagnosticEOF.bsl | 4 ++++ 3 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 src/test/resources/diagnostics/ParseErrorDiagnosticEOF.bsl diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnostic.java index a625e1420e7..0fd6c0676ae 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnostic.java @@ -31,6 +31,7 @@ import com.github._1c_syntax.bsl.parser.BSLLexer; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; +import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.misc.IntervalSet; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.ErrorNodeImpl; @@ -50,6 +51,8 @@ ) public class ParseErrorDiagnostic extends AbstractListenerDiagnostic { + public static final int EOF = -1; + public ParseErrorDiagnostic(DiagnosticInfo info) { super(info); } @@ -82,8 +85,13 @@ public void enterFile(BSLParser.FileContext ctx) { .mapToObj(ParseErrorDiagnostic::getTokenName) .forEachOrdered(sj::add); + Token errorToken = node.exception.getOffendingToken(); + if (errorToken.getType() == EOF) { + errorToken = node.getStart(); + } + diagnosticStorage.addDiagnostic( - node.exception.getOffendingToken(), + errorToken, info.getMessage(initialExpectedString + sj.toString()) ); }); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnosticTest.java index 39a2aee3c87..4e45802fa4b 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnosticTest.java @@ -49,4 +49,16 @@ void runTest() { assertThat(diagnostics, true).satisfiesAnyOf(onLineFive, onLineEight); } + + @Test + void runTestError() { + // when + List diagnostics = getDiagnostics("ParseErrorDiagnosticEOF"); + + // then + assertThat(diagnostics.size()).isEqualTo(2); // why 2? + assertThat(diagnostics.get(0)).hasRange(3, 0, 3, 3); + + } + } diff --git a/src/test/resources/diagnostics/ParseErrorDiagnosticEOF.bsl b/src/test/resources/diagnostics/ParseErrorDiagnosticEOF.bsl new file mode 100644 index 00000000000..caab5171f61 --- /dev/null +++ b/src/test/resources/diagnostics/ParseErrorDiagnosticEOF.bsl @@ -0,0 +1,4 @@ +Процедура ОтключитьСканерШтрихкодов() Экспорт + +КонецПроцедуры +HHH \ No newline at end of file From 2cc66f4148545b5b90628ef0e4ca7d7786b669d7 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Thu, 16 Apr 2020 14:44:37 +0300 Subject: [PATCH 062/444] Update src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnosticTest.java --- .../languageserver/diagnostics/ParseErrorDiagnosticTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnosticTest.java index 4e45802fa4b..0661688398b 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnosticTest.java @@ -57,7 +57,7 @@ void runTestError() { // then assertThat(diagnostics.size()).isEqualTo(2); // why 2? - assertThat(diagnostics.get(0)).hasRange(3, 0, 3, 3); + assertThat(diagnostics, true).hasRange(3, 0, 3, 3); } From 0c89be00a236f42da718fb5fe12cf399e290b1fe Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Thu, 16 Apr 2020 14:31:19 +0300 Subject: [PATCH 063/444] useLessForeach field FP fix --- .../diagnostics/UseLessForEachDiagnostic.java | 9 +++++++++ .../diagnostics/UseLessForEachDiagnosticTest.java | 2 +- .../resources/diagnostics/UseLessForEachDiagnostic.bsl | 6 ++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnostic.java index 2d28040ca9f..dcd207fca7a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnostic.java @@ -59,6 +59,15 @@ public ParseTree visitForEachStatement(BSLParser.ForEachStatementContext ctx) { TerminalNode iterator = ctx.IDENTIFIER(); String iteratorIdName = iterator.getText(); + + boolean isVariable = documentContext.getSymbolTree().getVariables() + .stream() + .anyMatch(variableSymbol -> variableSymbol.getName().equalsIgnoreCase(iteratorIdName)); + + if (isVariable) { + return super.visitForEachStatement(ctx); + } + boolean hasUsage = Trees.findAllTokenNodes(ctx.codeBlock(), BSLParser.IDENTIFIER) .stream() .filter(node -> iteratorIdName.equalsIgnoreCase(node.getText())) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnosticTest.java index 1e2efcdbba6..5d9146e37fc 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnosticTest.java @@ -41,7 +41,7 @@ void test() { assertThat(diagnostics).hasSize(1); assertThat(diagnostics, true) - .hasRange(0, 12, 0, 20); + .hasRange(2, 12, 2, 20); } } diff --git a/src/test/resources/diagnostics/UseLessForEachDiagnostic.bsl b/src/test/resources/diagnostics/UseLessForEachDiagnostic.bsl index 738acd3eb65..38f93d3aa9c 100644 --- a/src/test/resources/diagnostics/UseLessForEachDiagnostic.bsl +++ b/src/test/resources/diagnostics/UseLessForEachDiagnostic.bsl @@ -1,3 +1,5 @@ +Перем Поле; + Для Каждого Итератор Из Коллекция Цикл // Сработать Итератор неиспользуется в теле цикла Итератор(); КонецЦикла; @@ -30,3 +32,7 @@ Для Каждого АСтруктура Из Б Цикл АСтруктура.Ключ.Метод(); КонецЦикла; + +Для Каждого Поле Из Б Цикл + КакойтоМетод(); +КонецЦикла; From eaf2d68e8474d374a69e21af5e1a2f9a9d7c38c1 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Thu, 16 Apr 2020 15:20:47 +0300 Subject: [PATCH 064/444] only GlobalVarible --- .../diagnostics/UseLessForEachDiagnostic.java | 2 ++ .../UseLessForEachDiagnosticTest.java | 6 ++++-- .../diagnostics/UseLessForEachDiagnostic.bsl | 18 ++++++++++++++---- 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnostic.java index dcd207fca7a..60ddd6e738d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnostic.java @@ -21,6 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.languageserver.context.symbol.variable.VariableKind; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; @@ -62,6 +63,7 @@ public ParseTree visitForEachStatement(BSLParser.ForEachStatementContext ctx) { boolean isVariable = documentContext.getSymbolTree().getVariables() .stream() + .filter(variableSymbol -> variableSymbol.getKind() == VariableKind.GLOBAL) .anyMatch(variableSymbol -> variableSymbol.getName().equalsIgnoreCase(iteratorIdName)); if (isVariable) { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnosticTest.java index 5d9146e37fc..550639762e7 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnosticTest.java @@ -39,9 +39,11 @@ class UseLessForEachDiagnosticTest extends AbstractDiagnosticTest diagnostics = getDiagnostics(); - assertThat(diagnostics).hasSize(1); + assertThat(diagnostics).hasSize(2); assertThat(diagnostics, true) - .hasRange(2, 12, 2, 20); + .hasRange(2, 12, 2, 20) + .hasRange(39, 16, 26) + ; } } diff --git a/src/test/resources/diagnostics/UseLessForEachDiagnostic.bsl b/src/test/resources/diagnostics/UseLessForEachDiagnostic.bsl index 38f93d3aa9c..17c0f06bf95 100644 --- a/src/test/resources/diagnostics/UseLessForEachDiagnostic.bsl +++ b/src/test/resources/diagnostics/UseLessForEachDiagnostic.bsl @@ -1,4 +1,4 @@ -Перем Поле; +Перем ПолеМодуля; Для Каждого Итератор Из Коллекция Цикл // Сработать Итератор неиспользуется в теле цикла Итератор(); @@ -33,6 +33,16 @@ АСтруктура.Ключ.Метод(); КонецЦикла; -Для Каждого Поле Из Б Цикл - КакойтоМетод(); -КонецЦикла; +Процедура А() + + Перем ПолеМетода; + + Для Каждого ПолеМетода Из Б Цикл // Тут ловить + КакойтоМетод(); + КонецЦикла; + + Для Каждого ПолеМодуля Из Б Цикл // Тут не ловить + КакойтоМетод(); + КонецЦикла; + +КонецПроцедуры From b4092ef08a5fe40efb79c72d7f794f238f1b05ac Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Thu, 16 Apr 2020 16:14:12 +0300 Subject: [PATCH 065/444] or ModuleVarible --- .../languageserver/diagnostics/UseLessForEachDiagnostic.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnostic.java index 60ddd6e738d..ff30c314a2f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnostic.java @@ -63,7 +63,8 @@ public ParseTree visitForEachStatement(BSLParser.ForEachStatementContext ctx) { boolean isVariable = documentContext.getSymbolTree().getVariables() .stream() - .filter(variableSymbol -> variableSymbol.getKind() == VariableKind.GLOBAL) + .filter(variableSymbol -> variableSymbol.getKind() == VariableKind.GLOBAL + || variableSymbol.getKind() == VariableKind.MODULE) .anyMatch(variableSymbol -> variableSymbol.getName().equalsIgnoreCase(iteratorIdName)); if (isVariable) { From 50cfc71b8f03f3341de316e0343cdc1f15acd044 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Thu, 16 Apr 2020 16:39:35 +0300 Subject: [PATCH 066/444] change variableKind to Module --- .../computer/VariableSymbolComputer.java | 2 +- .../context/computer/VariableSymbolTest.java | 19 ++++++++++++++++--- .../context/symbol/variableSymbolTest.bsl | 4 ++++ 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java index 5c5a93215fc..b24204ab837 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java @@ -56,7 +56,7 @@ public List compute() { @Override public ParseTree visitModuleVarDeclaration(BSLParser.ModuleVarDeclarationContext ctx) { - var symbol = createVariableSymbol(ctx, ctx.var_name(), ctx.EXPORT_KEYWORD() != null, VariableKind.GLOBAL); + var symbol = createVariableSymbol(ctx, ctx.var_name(), ctx.EXPORT_KEYWORD() != null, VariableKind.MODULE); variables.add(symbol); return ctx; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolTest.java index b2b3c662251..5b4c4b8f92e 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolTest.java @@ -24,6 +24,7 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; 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.context.symbol.variable.VariableKind; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import org.eclipse.lsp4j.Range; @@ -48,15 +49,16 @@ public class VariableSymbolTest { @Test void testVariableSymbolDescription() { - assertThat(variableSymbols).hasSize(7); + assertThat(variableSymbols).hasSize(8); assertThat(variableSymbols) .filteredOn(variableSymbol -> variableSymbol.getDescription().isEmpty()) - .hasSize(4) + .hasSize(5) .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(12, 6, 12, 34))) .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(14, 6, 14, 27))) .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(16, 6, 16, 17))) .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(16, 19, 16, 30))) + .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(19, 10, 19, 19))) ; assertThat(variableSymbols) @@ -102,11 +104,22 @@ void testVariableNameRange() { assertThat(variableSymbols) .filteredOn(variableSymbol -> variableSymbol.getDescription().isEmpty()) - .hasSize(4) + .hasSize(5) .anyMatch(variableName -> variableName.getVariableNameRange().equals(Ranges.create(12, 6, 12, 34))) .anyMatch(variableName -> variableName.getVariableNameRange().equals(Ranges.create(14, 6, 14, 27))) .anyMatch(variableName -> variableName.getVariableNameRange().equals(Ranges.create(16, 6, 16, 17))) .anyMatch(variableName -> variableName.getVariableNameRange().equals(Ranges.create(16, 19, 16, 30))) + .anyMatch(variableName -> variableName.getVariableNameRange().equals(Ranges.create(19, 10, 19, 19))) + ; } + + @Test + void testVariableKind() { + + assertThat(variableSymbols.get(0).getKind()).isEqualTo(VariableKind.MODULE); + assertThat(variableSymbols.get(7).getKind()).isEqualTo(VariableKind.LOCAL); + + } + } diff --git a/src/test/resources/context/symbol/variableSymbolTest.bsl b/src/test/resources/context/symbol/variableSymbolTest.bsl index 5930a0769ad..e337ee31dcd 100644 --- a/src/test/resources/context/symbol/variableSymbolTest.bsl +++ b/src/test/resources/context/symbol/variableSymbolTest.bsl @@ -16,3 +16,7 @@ Перем ПеременнаяА, ПеременнаяБ; +Процедура А() + Перем Локальная; + +КонецПроцедуры \ No newline at end of file From 7b8c05c195743570c2619bea1e1ec0b84920e843 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Thu, 16 Apr 2020 22:48:06 +0700 Subject: [PATCH 067/444] =?UTF-8?q?=D0=BE=D0=BF=D0=B5=D1=87=D0=B0=D1=82?= =?UTF-8?q?=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/gen-bandge.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/scripts/gen-bandge.py b/.github/scripts/gen-bandge.py index 298d9e4f75e..8921ca039b2 100644 --- a/.github/scripts/gen-bandge.py +++ b/.github/scripts/gen-bandge.py @@ -7,7 +7,7 @@ total = data.get('benchmarks')[0].get('stats').get('mean') value = '{:.2f}'.format(total) -svg = badge(left_text='Benckmark (SSL 1.0)', right_text=value) +svg = badge(left_text='Benchmark (SSL 1.0)', right_text=value) f = open('benchmark.svg', 'w') f.write(svg) f.close() From 765195f806cc1b2392dbc2abd4a09609dd303e6f Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Thu, 16 Apr 2020 22:48:23 +0700 Subject: [PATCH 068/444] =?UTF-8?q?=D0=A2=D0=B5=D1=81=D1=82=20=D0=BF=D1=80?= =?UTF-8?q?=D0=BE=D0=B8=D0=B7=D0=B2=D0=BE=D0=B4=D0=B8=D1=82=D0=B5=D0=BB?= =?UTF-8?q?=D1=8C=D0=BD=D0=BE=D1=81=D1=82=D0=B8=20=D0=B1=D0=B5=D0=B7=20Typ?= =?UTF-8?q?o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/benchmark.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/.github/scripts/benchmark.py b/.github/scripts/benchmark.py index e515afdce7b..4f299a0761d 100644 --- a/.github/scripts/benchmark.py +++ b/.github/scripts/benchmark.py @@ -2,14 +2,17 @@ import os import re import ntpath +import json pattern = r"bsl.+\.jar" -dirName = os.getcwd() + "/build/libs" +thisPath = os.getcwd() +dirName = thisPath + "/build/libs" def test_analyze_ssl31(benchmark): benchmark(some_func, None) def some_func(arg): + pathToConfig = createBSLLSConfiguration() fullname = get_bslls_jar(dirName) cmdArgs = ['java'] cmdArgs.append('-jar') @@ -17,6 +20,8 @@ def some_func(arg): cmdArgs.append('-a') cmdArgs.append('-s') cmdArgs.append('ssl') + cmdArgs.append('-c') + cmdArgs.append(pathToConfig) cmd = ' '.join(cmdArgs) os.system(cmd) @@ -27,3 +32,14 @@ def get_bslls_jar(dir): if os.path.isfile(fullname) and re.search(pattern, fullname) and fullname.find('sources.jar') == -1 and fullname.find('javadoc.jar') == -1: return ntpath.basename(fullname) return None + +def createBSLLSConfiguration(): + newPath = thisPath + "/ssl/.bsl-language-server.json" + data = {} + data['configurationRoot'] = './src' + data['diagnostics'] = {'Typo': False} + + with open(newPath, 'w') as outfile: + json.dump(data, outfile) + + return newPath \ No newline at end of file From 0dc1f3a85b9b8f9611318c381c617633b254faf7 Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Thu, 16 Apr 2020 22:35:39 +0300 Subject: [PATCH 069/444] =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=B8=D0=BB?= =?UTF-8?q?=D0=BE=20=D1=83=D1=81=D0=BA=D0=BE=D1=80=D0=B5=D0=BD=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ресурсы вынесены в поля класса убран двойной прогон по списку токенов условия фильтра оптимизированы --- .../InvalidCharacterInFileDiagnostic.java | 39 +++++++++++-------- .../InvalidCharacterInFileDiagnosticTest.java | 13 +++++-- .../InvalidCharacterInFileDiagnostic.bsl | 15 +++++++ 3 files changed, 47 insertions(+), 20 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java index 2c3b19877e2..a0e68601c66 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java @@ -28,7 +28,9 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.providers.CodeActionProvider; +import com.github._1c_syntax.bsl.parser.BSLLexer; import com.github._1c_syntax.bsl.parser.BSLParser; +import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.ParseTree; import org.eclipse.lsp4j.CodeAction; @@ -69,31 +71,36 @@ public class InvalidCharacterInFileDiagnostic extends AbstractVisitorDiagnostic "])", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + private final String diagnosticMessageDash; + private final String diagnosticMessageSpace; + public InvalidCharacterInFileDiagnostic(DiagnosticInfo info) { super(info); + diagnosticMessageDash = info.getResourceString("diagnosticMessageDash"); + diagnosticMessageSpace = info.getResourceString("diagnosticMessageSpace"); } @Override public ParseTree visitFile(BSLParser.FileContext ctx) { - documentContext - .getTokens() - .stream() - .filter((Token token) -> ILLEGAL_DASH_PATTERN.matcher(token.getText()).find()) - .forEach(token -> - diagnosticStorage.addDiagnostic( - token, - info.getResourceString("diagnosticMessageDash")) - ); documentContext .getTokens() .stream() - .filter((Token token) -> ILLEGAL_SPACE_PATTERN.matcher(token.getText()).find()) + .filter((Token token) -> token.getChannel() == Lexer.HIDDEN || token.getType() == BSLLexer.STRING + || token.getType() == BSLLexer.LINE_COMMENT) .forEach(token -> - diagnosticStorage.addDiagnostic( - token, - info.getResourceString("diagnosticMessageSpace") - ) + { + var text = token.getText(); + if (ILLEGAL_SPACE_PATTERN.matcher(text).find()) { + + diagnosticStorage.addDiagnostic(token, diagnosticMessageSpace); + + } else if (ILLEGAL_DASH_PATTERN.matcher(text).find()) { + + diagnosticStorage.addDiagnostic(token, diagnosticMessageDash); + + } + } ); return ctx; @@ -109,7 +116,7 @@ public List getQuickFixes( List textEdits = new ArrayList<>(); diagnostics.stream() - .filter(diagnostic -> diagnostic.getMessage().equals(info.getResourceString("diagnosticMessageSpace"))) + .filter(diagnostic -> diagnostic.getMessage().equals(diagnosticMessageSpace)) .forEach((Diagnostic diagnostic) -> { Range range = diagnostic.getRange(); TextEdit textEdit = new TextEdit(range, @@ -119,7 +126,7 @@ public List getQuickFixes( }); diagnostics.stream() - .filter(diagnostic -> diagnostic.getMessage().equals(info.getResourceString("diagnosticMessageDash"))) + .filter(diagnostic -> diagnostic.getMessage().equals(diagnosticMessageDash)) .forEach((Diagnostic diagnostic) -> { Range range = diagnostic.getRange(); TextEdit textEdit = new TextEdit(range, diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnosticTest.java index 385dcd97dc1..92017bd4d5d 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnosticTest.java @@ -42,7 +42,6 @@ void test() { List diagnostics = getDiagnostics(); - assertThat(diagnostics).hasSize(8); assertThat(diagnostics, true) .hasRange(1, 14, 1, 17) .hasRange(2, 15, 2, 18) @@ -52,7 +51,13 @@ void test() { .hasRange(6, 0, 6, 33) .hasRange(12, 0, 12, 32) .hasRange(14, 15, 14, 18) - ; + .hasRange(17, 0, 17, 1) + .hasRange(20, 0, 20, 1) + .hasRange(22, 0, 22, 1) + .hasRange(24, 0, 24, 1) + .hasRange(26, 0, 26, 1) + .hasRange(28, 0, 28, 1) + .hasSize(14); } @@ -69,7 +74,7 @@ void testQuickFix() { .first() .matches(codeAction -> codeAction.getKind().equals(CodeActionKind.QuickFix)) - .matches(codeAction -> codeAction.getDiagnostics().size() == 8) + .matches(codeAction -> codeAction.getDiagnostics().size() == 14) .matches(codeAction -> codeAction.getDiagnostics().get(3).equals(diagnostics.get(3))) .matches(codeAction -> codeAction.getEdit().getChanges().size() == 1) @@ -87,7 +92,7 @@ void testQuickFix() { .first() .matches(codeAction -> codeAction.getKind().equals(CodeActionKind.QuickFix)) - .matches(codeAction -> codeAction.getDiagnostics().size() == 8) + .matches(codeAction -> codeAction.getDiagnostics().size() == 14) .matches(codeAction -> codeAction.getDiagnostics().get(7).equals(diagnostics.get(7))) .matches(codeAction -> codeAction.getEdit().getChanges().size() == 1) diff --git a/src/test/resources/diagnostics/InvalidCharacterInFileDiagnostic.bsl b/src/test/resources/diagnostics/InvalidCharacterInFileDiagnostic.bsl index 6531270387a..3a703dac5d0 100644 --- a/src/test/resources/diagnostics/InvalidCharacterInFileDiagnostic.bsl +++ b/src/test/resources/diagnostics/InvalidCharacterInFileDiagnostic.bsl @@ -13,3 +13,18 @@ // В этом комментарии только НПП Строка = "А" + " " + "И"; + +//в строке ниже неразрывный пробел +  +// минусы с ошибками +//СреднееТире = " +–; +//ЦифровоеТире = " +‒; +//ДлинноеТире = " +—; +//ГоризонтальнаяЛиния = " +―; +//НеправильныйМинус = " +−; +//конец файла From 05d0d9872ca11749ede8e3c7c964573bcf6d8c68 Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Fri, 17 Apr 2020 12:16:57 +0300 Subject: [PATCH 070/444] =?UTF-8?q?=D1=83=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D0=B0=20=D0=BD=D0=B5=D0=BD=D1=83=D0=B6=D0=BD=D0=B0=D1=8F=20?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B0=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=BC=D0=BC=D0=B5=D0=BD=D1=82=D0=B0=D1=80=D0=B8=D0=B5=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/InvalidCharacterInFileDiagnostic.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java index a0e68601c66..e6f4b64e58a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java @@ -86,8 +86,7 @@ public ParseTree visitFile(BSLParser.FileContext ctx) { documentContext .getTokens() .stream() - .filter((Token token) -> token.getChannel() == Lexer.HIDDEN || token.getType() == BSLLexer.STRING - || token.getType() == BSLLexer.LINE_COMMENT) + .filter((Token token) -> token.getChannel() == Lexer.HIDDEN || token.getType() == BSLLexer.STRING) .forEach(token -> { var text = token.getText(); From 29fc0d2e5b926b5e6229350d96ad480cfceec77c Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Fri, 17 Apr 2020 22:22:27 +0700 Subject: [PATCH 071/444] =?UTF-8?q?=D0=91=D0=B0=D0=B7=D0=BE=D0=B2=D0=B0?= =?UTF-8?q?=D1=8F=20=D1=80=D0=B5=D0=B0=D0=BB=D0=B8=D0=B0=D1=86=D0=B8=D1=8F?= =?UTF-8?q?=20=D0=B4=D0=B8=D0=B0=D0=B3=D0=BD=D0=BE=D1=81=D1=82=D0=B8=D0=BA?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DataExchangeLoadingDiagnostic.java | 109 ++++++++++++++++++ ...ataExchangeLoadingDiagnostic_en.properties | 2 + ...ataExchangeLoadingDiagnostic_ru.properties | 2 + 3 files changed, 113 insertions(+) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_ru.properties diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java new file mode 100644 index 00000000000..385f284b074 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java @@ -0,0 +1,109 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; +import org.antlr.v4.runtime.tree.ParseTree; + +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.ERROR, + severity = DiagnosticSeverity.CRITICAL, + scope = DiagnosticScope.BSL, + modules = { + ModuleType.ObjectModule + }, + minutesToFix = 10, + tags = { + DiagnosticTag.STANDARD, + DiagnosticTag.BADPRACTICE, + DiagnosticTag.UNPREDICTABLE + } + +) +public class DataExchangeLoadingDiagnostic extends AbstractVisitorDiagnostic { + + private static final String SUB_NAMES = "^(ПередЗаписью|ПриЗаписи|ПередУдалением|BeforeWrite|BeforeDelete|OnWrite)$"; + private static final String CONDITION = + "ОбменДанными.Загрузка=Истина|ОбменДанными.Загрузка|DataExchange.Load=True|DataExchange.Load"; + + private static final Pattern searchSubNames = Pattern.compile( + SUB_NAMES, + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + private static final Pattern searchCondition = Pattern.compile( + CONDITION, + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + + public DataExchangeLoadingDiagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + public ParseTree visitProcDeclaration(BSLParser.ProcDeclarationContext ctx) { + var subName = ctx.subName(); + if (subName != null) { + if (searchSubNames.matcher(subName.getText()).matches() && needCreateIssue(ctx)) { + diagnosticStorage.addDiagnostic(ctx); + } + } + return ctx; + } + + private boolean needCreateIssue(BSLParser.ProcDeclarationContext ctx) { + BSLParser.ProcedureContext procedureContext = (BSLParser.ProcedureContext) ctx.getParent(); + var statements = procedureContext.subCodeBlock().codeBlock().statement(); + if (statements != null) { + if (!statements.isEmpty()) { + return !foundLoadConditionWithReturn(statements.get(0)); + } + } + return true; + } + + private boolean foundLoadConditionWithReturn(BSLParser.StatementContext ctx) { + var ifStatement = ctx.compoundStatement().ifStatement(); + if (ifStatement != null) { + var ifBranch = ifStatement.ifBranch(); + var text = ifBranch.expression().getText(); + return searchCondition.matcher(text).find() && foundReturnStatement(ifBranch); + } + return false; + } + + private boolean foundReturnStatement(BSLParser.IfBranchContext ctx) { + var ifStatements = ctx.codeBlock().statement(); + if (ifStatements != null) { + var itemStatement = ifStatements.get(0); + return itemStatement.compoundStatement().returnStatement() != null; + } + return false; + } + +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_en.properties new file mode 100644 index 00000000000..7ecbe607958 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=There is no check for the attribute DataExchange.Load in the object's event handler +diagnosticName=Add a check for the attribute ExchangeData.Load at the very beginning of the procedure diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_ru.properties new file mode 100644 index 00000000000..d13a2b3e7bb --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Отсутствует проверка признака ОбменДанными.Загрузка в обработчике событий объекта +diagnosticName=Добавьте проверку признака ОбменДанными.Загрузка в самом начале процедуры From d85c2fff267e1b76da5d3c83d7b1a74757b848bf Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Fri, 17 Apr 2020 22:22:51 +0700 Subject: [PATCH 072/444] =?UTF-8?q?=D0=A2=D0=B5=D1=81=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DataExchangeLoadingDiagnosticTest.java | 52 +++++++++++++++++++ .../DataExchangeLoadingDiagnostic.bsl | 38 ++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java new file mode 100644 index 00000000000..6d91b558a71 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java @@ -0,0 +1,52 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class DataExchangeLoadingDiagnosticTest extends AbstractDiagnosticTest { + DataExchangeLoadingDiagnosticTest() { + super(DataExchangeLoadingDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics) + .hasSize(3) + .anyMatch(diagnostic -> diagnostic.getRange().equals( + Ranges.create(7, 0, 7, 29))) + .anyMatch(diagnostic -> diagnostic.getRange().equals( + Ranges.create(19, 0, 19, 25))) + .anyMatch(diagnostic -> diagnostic.getRange().equals( + Ranges.create(33, 0, 33, 30))); + + } +} diff --git a/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl b/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl new file mode 100644 index 00000000000..c943ac42539 --- /dev/null +++ b/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl @@ -0,0 +1,38 @@ +Процедура ПередУдалением(Отказ) + Если ОбменДанными.Загрузка = Истина Тогда + Возврат; + КонецЕсли; + Отказ = ОбщийМодуль.ЕстьОтказ(ОбменДанными.Загрузка); +КонецПроцедуры + +Процедура ПередЗаписью(Отказ) // Ошибка + Если Отказ Тогда + Сообщить("Это отказ"); + КонецЕсли; +КонецПроцедуры + +Процедура ПриЗаписи(Отказ) + Если ОбменДанными.Загрузка Тогда + Возврат; + КонецЕсли; +КонецПроцедуры + +Procedure OnWrite(Cancel) + Var Value; + If DataExchange.Recipients Then + Return; + EndIf; +EndProcedure + +Procedure BeforeWrite(Cancel) + Var Value; + If DataExchange.Load Then + Return; + EndIf; +EndProcedure + +Procedure BeforeDelete(Cancel) + For Each Item in new Array Do + Return; + EndDo; +EndProcedure \ No newline at end of file From 2974178b66ce481b442f425739ef76edf4432f47 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Fri, 17 Apr 2020 22:23:32 +0700 Subject: [PATCH 073/444] =?UTF-8?q?=D0=94=D0=BE=D0=BA=D1=83=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D1=8F=20+=20=D0=BF=D1=80=D0=B5?= =?UTF-8?q?=D0=BA=D0=BE=D0=BC=D0=BC=D0=B8=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/DataExchangeLoading.md | 69 +++++++++++++++++++ docs/diagnostics/index.md | 5 +- docs/en/diagnostics/DataExchangeLoading.md | 68 ++++++++++++++++++ docs/en/diagnostics/index.md | 5 +- .../configuration/diagnostics-schema.json | 10 +++ .../languageserver/configuration/schema.json | 3 + 6 files changed, 156 insertions(+), 4 deletions(-) create mode 100644 docs/diagnostics/DataExchangeLoading.md create mode 100644 docs/en/diagnostics/DataExchangeLoading.md diff --git a/docs/diagnostics/DataExchangeLoading.md b/docs/diagnostics/DataExchangeLoading.md new file mode 100644 index 00000000000..b792db68d54 --- /dev/null +++ b/docs/diagnostics/DataExchangeLoading.md @@ -0,0 +1,69 @@ +# Добавьте проверку признака ОбменДанными.Загрузка в самом начале процедуры (DataExchangeLoading) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Ошибка` | `BSL` | `Критичный` | `Да` | `10` | `standard`
`badpractice`
`unpredictable` | + + +## Описание диагностики + +Все действия в процедурах-обработчиков событий ПередЗаписью, ПриЗаписи, ПередУдалением должны выполняться +после проверки на ОбменДанными.Загрузка. + +Это необходимо для того, чтобы никакая бизнес-логика объекта не выполнялась при записи объекта через механизм обмена +данными, поскольку она уже была выполнена для объекта в том узле, где он был создан. В этом случае все данные +загружаются в ИБ "как есть", без искажений (изменений), проверок или каких-либо других дополнительных действий, +препятствующих загрузке данных. + +## Примеры + + +Неправильно: +```bsl +Процедура ПередЗаписью(Отказ) + + Если Не Отказ Тогда + ЗапутитьКакойТоАлгоритм(); + КонецЕсли; + + // код обработчика + // + // ... + +КонецПроцедуры +``` +Правильно: +```bsl +Процедура ПередЗаписью(Отказ) + Если ОбменДанными.Загрузка Тогда + Возврат; + КонецЕсли; + + // код обработчика + // ... +КонецПроцедуры +``` + +## Источники + + +* [Стандарт: Использование признака ОбменДанными.Загрузка в обработчиках событий объекта](https://its.1c.ru/db/v8std#content:773) +* [Обработчик события ПриЗаписи](https://its.1c.ru/db/v8std#content:465) +* [Обработчик события ПередЗаписью](https://its.1c.ru/db/v8std#content:464) +* [Обработчик события ПередУдалением](https://its.1c.ru/db/v8std#content:752) + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:DataExchangeLoading-off +// BSLLS:DataExchangeLoading-on +``` + +### Параметр конфигурационного файла + +```json +"DataExchangeLoading": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index d1eccfc2ac0..7037e7ad77c 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,11 +8,11 @@ ## Список реализованных диагностик -Общее количество: **88** +Общее количество: **89** * Дефект кода: **55** * Уязвимость: **2** -* Ошибка: **29** +* Ошибка: **30** * Потенциальная уязвимость: **2** | Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги | @@ -28,6 +28,7 @@ | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Лишняя директива компиляции | Да | Важный | Дефект кода | `clumsy`
`standard`
`unpredictable` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Выполнение запроса в цикле | Да | Критичный | Ошибка | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Цикломатическая сложность | Да | Критичный | Дефект кода | `brainoverload` | +| [DataExchangeLoading](DataExchangeLoading.md) | Добавьте проверку признака ОбменДанными.Загрузка в самом начале процедуры | Да | Критичный | Ошибка | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Удаление элемента при обходе коллекции посредством оператора "Для каждого ... Из ... Цикл" | Да | Важный | Ошибка | `standard`
`error` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Использование устаревшего метода "ТекущаяДата" | Да | Важный | Ошибка | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Использование устаревшего метода "Найти" | Да | Незначительный | Дефект кода | `deprecated` | diff --git a/docs/en/diagnostics/DataExchangeLoading.md b/docs/en/diagnostics/DataExchangeLoading.md new file mode 100644 index 00000000000..afbeffb325a --- /dev/null +++ b/docs/en/diagnostics/DataExchangeLoading.md @@ -0,0 +1,68 @@ +# Add a check for the attribute ExchangeData.Load at the very beginning of the procedure (DataExchangeLoading) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Error` | `BSL` | `Critical` | `Yes` | `10` | `standard`
`badpractice`
`unpredictable` | + + +## Description + + +## Examples + + +Bad: +```bsl +Procedure BeforeWrite(Cancel) + + If Not Cancel Then + RandomAlgorithm(); + EndIf; + + // code handler + // + // ... + +EndProcedure +``` + +Good: +```bsl +Procedure BeforeWrite(Cancel) + If DataExchange.Load Then + Return; + EndIf; + + // code handler + // ... +EndProcedure +``` + +## Sources + + + +* [Стандарт: Использование признака ОбменДанными.Загрузка в обработчиках событий объекта](https://its.1c.ru/db/v8std#content:773) +* [Обработчик события ПриЗаписи](https://its.1c.ru/db/v8std#content:465) +* [Обработчик события ПередЗаписью](https://its.1c.ru/db/v8std#content:464) +* [Обработчик события ПередУдалением](https://its.1c.ru/db/v8std#content:752) + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:DataExchangeLoading-off +// BSLLS:DataExchangeLoading-on +``` + +### Parameter for config + +```json +"DataExchangeLoading": false +``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 92ef4e4c507..1e53873c90c 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,9 +8,9 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **88** +Total: **89** -* Error: **29** +* Error: **30** * Code smell: **55** * Vulnerability: **2** * Security Hotspot: **2** @@ -28,6 +28,7 @@ Total: **88** | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Needless compilation directive | Yes | Major | Code smell | `clumsy`
`standard`
`unpredictable` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Execution query on cycle | Yes | Critical | Error | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Cyclomatic complexity | Yes | Critical | Code smell | `brainoverload` | +| [DataExchangeLoading](DataExchangeLoading.md) | Add a check for the attribute ExchangeData.Load at the very beginning of the procedure | Yes | Critical | Error | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Deleting an item when iterating through collection using the operator "For each ... In ... Do" | Yes | Major | Error | `standard`
`error` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Using of the deprecated method "CurrentDate" | Yes | Major | Error | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Using of the deprecated method "Find" | Yes | Minor | Code smell | `deprecated` | diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json index 3369ec036ca..660be6ebd5f 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json @@ -150,6 +150,16 @@ }, "$id": "#/definitions/CyclomaticComplexity" }, + "DataExchangeLoading": { + "description": "Add a check for the attribute ExchangeData.Load at the very beginning of the procedure", + "default": null, + "type": [ + "boolean", + "object" + ], + "title": "Add a check for the attribute ExchangeData.Load at the very beginning of the procedure", + "$id": "#/definitions/DataExchangeLoading" + }, "DeletingCollectionItem": { "description": "Deleting an item when iterating through collection using the operator \"For each ... In ... Do\"", "default": null, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index c34797acb3e..befc3db93e5 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -134,6 +134,9 @@ "CyclomaticComplexity": { "$ref": "diagnostics-schema.json#/definitions/CyclomaticComplexity" }, + "DataExchangeLoading": { + "$ref": "diagnostics-schema.json#/definitions/DataExchangeLoading" + }, "DeletingCollectionItem": { "$ref": "diagnostics-schema.json#/definitions/DeletingCollectionItem" }, From bd648c9e958115c709e7590815ff99ea72dfe24a Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sat, 18 Apr 2020 23:06:39 +0700 Subject: [PATCH 074/444] =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B5=D1=85=D0=BE?= =?UTF-8?q?=D0=B4=20=D0=BD=D0=B0=20=D1=81=D1=82=D1=80=D0=B8=D0=BC=D1=8B,?= =?UTF-8?q?=20=D1=83=D0=BC=D0=B5=D0=BD=D1=8C=D1=88=D0=B5=D0=BD=D0=B8=D0=B5?= =?UTF-8?q?=20=D0=BA=D0=BE=D0=B4=D0=B0,=20=D0=B2=D1=80=D0=B5=D0=BC=D1=8F?= =?UTF-8?q?=20=D1=83=D0=BC=D0=B5=D0=BD=D1=8C=D1=88=D0=B5=D0=BD=D0=BE=20?= =?UTF-8?q?=D0=B4=D0=BE=205=20=D0=BC=D0=B8=D0=BD,=20=D0=B4=D0=BE=D0=B1?= =?UTF-8?q?=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D1=8B=20=D0=B5=D1=89=D0=B5=20?= =?UTF-8?q?=D1=82=D0=B8=D0=BF=D1=8B=20=D0=BC=D0=BE=D0=B4=D1=83=D0=BB=D0=B5?= =?UTF-8?q?=D0=B9=20=D0=B2=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA?= =?UTF-8?q?=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DataExchangeLoadingDiagnostic.java | 81 ++++++++++--------- .../DataExchangeLoadingDiagnosticTest.java | 6 +- 2 files changed, 48 insertions(+), 39 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java index 385f284b074..83edfa2c8b1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java @@ -27,10 +27,13 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.Trees; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; +import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; +import java.util.Optional; import java.util.regex.Pattern; @DiagnosticMetadata( @@ -38,9 +41,11 @@ severity = DiagnosticSeverity.CRITICAL, scope = DiagnosticScope.BSL, modules = { - ModuleType.ObjectModule + ModuleType.ObjectModule, + ModuleType.RecordSetModule, + ModuleType.ValueManagerModule }, - minutesToFix = 10, + minutesToFix = 5, tags = { DiagnosticTag.STANDARD, DiagnosticTag.BADPRACTICE, @@ -50,15 +55,11 @@ ) public class DataExchangeLoadingDiagnostic extends AbstractVisitorDiagnostic { - private static final String SUB_NAMES = "^(ПередЗаписью|ПриЗаписи|ПередУдалением|BeforeWrite|BeforeDelete|OnWrite)$"; - private static final String CONDITION = - "ОбменДанными.Загрузка=Истина|ОбменДанными.Загрузка|DataExchange.Load=True|DataExchange.Load"; - private static final Pattern searchSubNames = Pattern.compile( - SUB_NAMES, + "^(ПередЗаписью|ПриЗаписи|ПередУдалением|BeforeWrite|BeforeDelete|OnWrite)$", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final Pattern searchCondition = Pattern.compile( - CONDITION, + "(ОбменДанными.Загрузка=Истина|ОбменДанными.Загрузка|DataExchange.Load=True|DataExchange.Load)$", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); public DataExchangeLoadingDiagnostic(DiagnosticInfo info) { @@ -67,43 +68,51 @@ public DataExchangeLoadingDiagnostic(DiagnosticInfo info) { @Override public ParseTree visitProcDeclaration(BSLParser.ProcDeclarationContext ctx) { - var subName = ctx.subName(); - if (subName != null) { - if (searchSubNames.matcher(subName.getText()).matches() && needCreateIssue(ctx)) { - diagnosticStorage.addDiagnostic(ctx); - } - } + Optional.of(ctx) + .map(BSLParser.ProcDeclarationContext::subName) + .filter(subName -> searchSubNames.matcher(subName.getText()).find() && needCreateIssue(ctx)) + .flatMap(context -> + Optional.of(documentContext.getSymbolTree()) + .map(symbolTree -> symbolTree.getMethodSymbol((BSLParser.SubContext) getSubContext(ctx))) + .get()) + .ifPresent(methodSymbol -> diagnosticStorage.addDiagnostic(methodSymbol.getSubNameRange())); return ctx; } private boolean needCreateIssue(BSLParser.ProcDeclarationContext ctx) { - BSLParser.ProcedureContext procedureContext = (BSLParser.ProcedureContext) ctx.getParent(); - var statements = procedureContext.subCodeBlock().codeBlock().statement(); - if (statements != null) { - if (!statements.isEmpty()) { - return !foundLoadConditionWithReturn(statements.get(0)); - } - } - return true; + return Optional.of(ctx) + .map(BSLParser.ProcDeclarationContext::getParent) + .map(BSLParser.ProcedureContext.class::cast) + .map(BSLParser.ProcedureContext::subCodeBlock) + .map(BSLParser.SubCodeBlockContext::codeBlock) + .map(BSLParser.CodeBlockContext::statement) + .flatMap(context -> context.stream().findFirst()) + .filter(context -> !foundLoadConditionWithReturn(context)) + .isPresent(); } private boolean foundLoadConditionWithReturn(BSLParser.StatementContext ctx) { - var ifStatement = ctx.compoundStatement().ifStatement(); - if (ifStatement != null) { - var ifBranch = ifStatement.ifBranch(); - var text = ifBranch.expression().getText(); - return searchCondition.matcher(text).find() && foundReturnStatement(ifBranch); - } - return false; + return Optional.of(ctx) + .map(BSLParser.StatementContext::compoundStatement) + .map(BSLParser.CompoundStatementContext::ifStatement) + .map(BSLParser.IfStatementContext::ifBranch) + .filter(context -> + searchCondition.matcher(context.expression().getText()).find() + && foundReturnStatement(context)) + .isPresent(); } - private boolean foundReturnStatement(BSLParser.IfBranchContext ctx) { - var ifStatements = ctx.codeBlock().statement(); - if (ifStatements != null) { - var itemStatement = ifStatements.get(0); - return itemStatement.compoundStatement().returnStatement() != null; - } - return false; + private boolean foundReturnStatement(BSLParser.IfBranchContext ifBranch) { + return Optional.of(ifBranch) + .map(BSLParser.IfBranchContext::codeBlock) + .map(BSLParser.CodeBlockContext::statement) + .flatMap(context -> context.stream().findFirst()) + .map(BSLParser.StatementContext::compoundStatement) + .map(BSLParser.CompoundStatementContext::returnStatement) + .isPresent(); } + private ParserRuleContext getSubContext(BSLParser.ProcDeclarationContext ctx) { + return Trees.getAncestorByRuleIndex((ParserRuleContext) ctx.getRuleContext(), BSLParser.RULE_sub); + } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java index 6d91b558a71..41653ea5653 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java @@ -42,11 +42,11 @@ void test() { assertThat(diagnostics) .hasSize(3) .anyMatch(diagnostic -> diagnostic.getRange().equals( - Ranges.create(7, 0, 7, 29))) + Ranges.create(7, 10, 7, 22))) .anyMatch(diagnostic -> diagnostic.getRange().equals( - Ranges.create(19, 0, 19, 25))) + Ranges.create(19, 10, 19, 17))) .anyMatch(diagnostic -> diagnostic.getRange().equals( - Ranges.create(33, 0, 33, 30))); + Ranges.create(33, 10, 33, 22))); } } From c5e66d4df31d18afc734d16091d4da63f6e74d6b Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sat, 18 Apr 2020 23:07:00 +0700 Subject: [PATCH 075/444] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=B2=20=D1=80=D0=B5=D1=81=D1=83=D1=80=D1=81=D0=B0?= =?UTF-8?q?=D1=85=20(=D0=BF=D0=B5=D1=80=D0=B5=D0=BF=D1=83=D1=82=D0=B0?= =?UTF-8?q?=D0=BD=D1=8B=20=D0=B7=D0=BD=D0=B0=D1=87=D0=B5=D0=BD=D0=B8=D1=8F?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/DataExchangeLoadingDiagnostic_en.properties | 4 ++-- .../diagnostics/DataExchangeLoadingDiagnostic_ru.properties | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_en.properties index 7ecbe607958..f905e642ceb 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_en.properties @@ -1,2 +1,2 @@ -diagnosticMessage=There is no check for the attribute DataExchange.Load in the object's event handler -diagnosticName=Add a check for the attribute ExchangeData.Load at the very beginning of the procedure +diagnosticMessage=Add a check for the attribute ExchangeData.Load at the very beginning of the procedure +diagnosticName=There is no check for the attribute DataExchange.Load in the object's event handler diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_ru.properties index d13a2b3e7bb..0b0dca5dc07 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_ru.properties @@ -1,2 +1,2 @@ -diagnosticMessage=Отсутствует проверка признака ОбменДанными.Загрузка в обработчике событий объекта -diagnosticName=Добавьте проверку признака ОбменДанными.Загрузка в самом начале процедуры +diagnosticMessage=Добавьте проверку признака ОбменДанными.Загрузка в самом начале процедуры +diagnosticName=Отсутствует проверка признака ОбменДанными.Загрузка в обработчике событий объекта From becd88b7484f30469a05570b1ad26fde55386d9a Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Sat, 18 Apr 2020 19:58:40 +0300 Subject: [PATCH 076/444] =?UTF-8?q?=D0=A3=D1=81=D0=BA=D0=BE=D1=80=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20-=20=D0=92=D0=BC=D0=B5=D1=81=D1=82=D0=BE?= =?UTF-8?q?=202=D1=85=20=D0=B2=D0=B0=D0=BB=D0=B8=D0=B4=D0=B0=D1=86=D0=B8?= =?UTF-8?q?=D0=B9=20=D0=B2=D1=8B=D0=BF=D0=BE=D0=BB=D0=BD=D1=8F=D1=8E=20?= =?UTF-8?q?=D0=BE=D0=B4=D0=BD=D1=83=20=D0=BE=D0=B1=D1=89=D1=83=D1=8E=20?= =?UTF-8?q?=D0=B2=D0=B0=D0=BB=D0=B8=D0=B4=D0=B0=D1=86=D0=B8=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../InvalidCharacterInFileDiagnostic.java | 33 ++++++++++--------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java index e6f4b64e58a..ad0490e69ca 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java @@ -56,20 +56,23 @@ public class InvalidCharacterInFileDiagnostic extends AbstractVisitorDiagnostic implements QuickFixProvider { - private static final Pattern ILLEGAL_DASH_PATTERN = Pattern.compile("([" + + public static final String SPACE_REGEX = "(?:" + + "\\u00A0" + // 160 + ")"; + + private static final Pattern ILLEGAL_PATTERN = Pattern.compile("(?:[" + "\\u00AD" + // 173 "\\u2012" + // 8210 "\\u2013" + // 8211 "\\u2014" + // 8212 "\\u2015" + // 8213 "\\u2212" + // 8722 - "])", - Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + "])" + + "|" + SPACE_REGEX, + Pattern.UNICODE_CASE); - private static final Pattern ILLEGAL_SPACE_PATTERN = Pattern.compile("([" + - "\\u00A0" + // 160 - "])", - Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + private static final Pattern ILLEGAL_SPACE_PATTERN = Pattern.compile(SPACE_REGEX, + Pattern.UNICODE_CASE); private final String diagnosticMessageDash; private final String diagnosticMessageSpace; @@ -87,18 +90,16 @@ public ParseTree visitFile(BSLParser.FileContext ctx) { .getTokens() .stream() .filter((Token token) -> token.getChannel() == Lexer.HIDDEN || token.getType() == BSLLexer.STRING) + .filter((Token token) -> ILLEGAL_PATTERN.matcher(token.getText()).find()) .forEach(token -> { var text = token.getText(); - if (ILLEGAL_SPACE_PATTERN.matcher(text).find()) { - - diagnosticStorage.addDiagnostic(token, diagnosticMessageSpace); - - } else if (ILLEGAL_DASH_PATTERN.matcher(text).find()) { - - diagnosticStorage.addDiagnostic(token, diagnosticMessageDash); + String message = diagnosticMessageDash; + if (ILLEGAL_SPACE_PATTERN.matcher(text).find()){ + message = diagnosticMessageSpace; + } + diagnosticStorage.addDiagnostic(token, message); - } } ); @@ -129,7 +130,7 @@ public List getQuickFixes( .forEach((Diagnostic diagnostic) -> { Range range = diagnostic.getRange(); TextEdit textEdit = new TextEdit(range, - ILLEGAL_DASH_PATTERN.matcher(documentContext.getText(range)).replaceAll("-")); + ILLEGAL_PATTERN.matcher(documentContext.getText(range)).replaceAll("-")); textEdits.add(textEdit); }); From 28eaa364f9a7650f758543c19b0ff2474b34c211 Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Sat, 18 Apr 2020 22:03:01 +0300 Subject: [PATCH 077/444] =?UTF-8?q?=D1=83=D1=87=D0=B5=D1=82=20=D0=BC=D1=83?= =?UTF-8?q?=D0=BB=D1=8C=D1=82=D0=B8=D1=81=D1=82=D1=80=D0=BE=D1=87=D0=BD?= =?UTF-8?q?=D1=8B=D1=85=20=D1=81=D1=82=D1=80=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../InvalidCharacterInFileDiagnostic.java | 7 ++++- .../InvalidCharacterInFileDiagnosticTest.java | 30 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java index ad0490e69ca..034c98aaca5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java @@ -89,7 +89,12 @@ public ParseTree visitFile(BSLParser.FileContext ctx) { documentContext .getTokens() .stream() - .filter((Token token) -> token.getChannel() == Lexer.HIDDEN || token.getType() == BSLLexer.STRING) + .filter((Token token) -> token.getChannel() == Lexer.HIDDEN + || token.getType() == BSLLexer.STRINGPART + || token.getType() == BSLLexer.STRING + || token.getType() == BSLLexer.STRINGSTART + || token.getType() == BSLLexer.STRINGTAIL + ) .filter((Token token) -> ILLEGAL_PATTERN.matcher(token.getText()).find()) .forEach(token -> { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnosticTest.java index 92017bd4d5d..1013ac881e0 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnosticTest.java @@ -21,6 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import org.eclipse.lsp4j.CodeAction; import org.eclipse.lsp4j.CodeActionKind; import org.eclipse.lsp4j.Diagnostic; @@ -61,6 +62,35 @@ void test() { } + @Test + void testMultiString() { + String module = "//в строке ниже неразрывный пробел\n" + + "А = \" \n" + + "|// минусы с ошибками\n" + + "|//СреднееТире = \n" + + "|–;\n" + + "|//ЦифровоеТире = \n" + + "|‒;\n" + + "|//ДлинноеТире = \n" + + "|—;\n" + + "|//ГоризонтальнаяЛиния = \n" + + "|―;\n" + + "|//НеправильныйМинус = \n" + + "|−;\";\n"; + + var documentContext = TestUtils.getDocumentContext(module); + var diagnostics = getDiagnostics(documentContext); + + assertThat(diagnostics, true) + .hasRange(1, 4, 1, 6) + .hasRange(4, 0, 4, 3) + .hasRange(6, 0, 6, 3) + .hasRange(8, 0, 8, 3) + .hasRange(10, 0, 10, 3) + .hasRange(12, 0, 12, 4) + .hasSize(6); + } + @Test void testQuickFix() { From e7668555c5e4fa7db13334250a86028e65c2baa6 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Mon, 20 Apr 2020 12:06:27 +0700 Subject: [PATCH 078/444] =?UTF-8?q?=D0=BF=D0=BE=D0=B8=D1=81=D0=BA=20=D0=BF?= =?UTF-8?q?=D0=B5=D1=80=D0=B2=D0=BE=D0=B3=D0=BE=20statement=20=D0=B2=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=B0=D0=BC=D0=B5=D1=82=D1=80.=20=D0=9F?= =?UTF-8?q?=D0=BE=20=D1=83=D0=BC=D0=BE=D0=BB=D1=87=D0=B0=D0=BD=D0=B8=D1=8E?= =?UTF-8?q?=20false?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DataExchangeLoadingDiagnostic.java | 46 +++++++++++++++---- ...ataExchangeLoadingDiagnostic_en.properties | 2 + ...ataExchangeLoadingDiagnostic_ru.properties | 2 + .../DataExchangeLoadingDiagnosticTest.java | 26 ++++++++++- .../DataExchangeLoadingDiagnostic.bsl | 10 +++- 5 files changed, 74 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java index 83edfa2c8b1..b0591f95470 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java @@ -23,17 +23,21 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticParameter; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.DiagnosticHelper; import com.github._1c_syntax.bsl.languageserver.utils.Trees; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; +import java.util.Map; import java.util.Optional; +import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; @DiagnosticMetadata( @@ -59,18 +63,35 @@ public class DataExchangeLoadingDiagnostic extends AbstractVisitorDiagnostic { "^(ПередЗаписью|ПриЗаписи|ПередУдалением|BeforeWrite|BeforeDelete|OnWrite)$", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final Pattern searchCondition = Pattern.compile( - "(ОбменДанными.Загрузка=Истина|ОбменДанными.Загрузка|DataExchange.Load=True|DataExchange.Load)$", + "ОбменДанными.Загрузка=Истина|ОбменДанными.Загрузка|DataExchange.Load=True|DataExchange.Load", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + private static final boolean FIND_FIRST = false; + + @DiagnosticParameter( + type = Boolean.class, + defaultValue = "" + FIND_FIRST + ) + private boolean findFirst = FIND_FIRST; + public DataExchangeLoadingDiagnostic(DiagnosticInfo info) { super(info); } + @Override + public void configure(Map configuration) { + if (configuration == null) return; + DiagnosticHelper.configureDiagnostic(this, configuration, "findFirst"); + } + @Override public ParseTree visitProcDeclaration(BSLParser.ProcDeclarationContext ctx) { Optional.of(ctx) .map(BSLParser.ProcDeclarationContext::subName) - .filter(subName -> searchSubNames.matcher(subName.getText()).find() && needCreateIssue(ctx)) + .filter(subName -> + searchSubNames.matcher(subName.getText()).find() + && !checkPassed(ctx) + ) .flatMap(context -> Optional.of(documentContext.getSymbolTree()) .map(symbolTree -> symbolTree.getMethodSymbol((BSLParser.SubContext) getSubContext(ctx))) @@ -79,15 +100,23 @@ public ParseTree visitProcDeclaration(BSLParser.ProcDeclarationContext ctx) { return ctx; } - private boolean needCreateIssue(BSLParser.ProcDeclarationContext ctx) { + private boolean checkPassed(BSLParser.ProcDeclarationContext ctx) { + AtomicInteger orderStatement = new AtomicInteger(); return Optional.of(ctx) .map(BSLParser.ProcDeclarationContext::getParent) .map(BSLParser.ProcedureContext.class::cast) .map(BSLParser.ProcedureContext::subCodeBlock) .map(BSLParser.SubCodeBlockContext::codeBlock) .map(BSLParser.CodeBlockContext::statement) - .flatMap(context -> context.stream().findFirst()) - .filter(context -> !foundLoadConditionWithReturn(context)) + .flatMap(context -> context.stream() + .filter(statement -> { + orderStatement.getAndIncrement(); + if (findFirst && orderStatement.get() > 1) { + return false; + } + return foundLoadConditionWithReturn(statement); + }) + .findFirst()) .isPresent(); } @@ -106,9 +135,10 @@ private boolean foundReturnStatement(BSLParser.IfBranchContext ifBranch) { return Optional.of(ifBranch) .map(BSLParser.IfBranchContext::codeBlock) .map(BSLParser.CodeBlockContext::statement) - .flatMap(context -> context.stream().findFirst()) - .map(BSLParser.StatementContext::compoundStatement) - .map(BSLParser.CompoundStatementContext::returnStatement) + .flatMap(context -> context.stream() + .map(BSLParser.StatementContext::compoundStatement) + .map(BSLParser.CompoundStatementContext::returnStatement) + .findFirst()) .isPresent(); } diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_en.properties index f905e642ceb..85ce51b7d21 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_en.properties @@ -1,2 +1,4 @@ diagnosticMessage=Add a check for the attribute ExchangeData.Load at the very beginning of the procedure diagnosticName=There is no check for the attribute DataExchange.Load in the object's event handler + +findFirst=Check should go first diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_ru.properties index 0b0dca5dc07..f7540a19724 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_ru.properties @@ -1,2 +1,4 @@ diagnosticMessage=Добавьте проверку признака ОбменДанными.Загрузка в самом начале процедуры diagnosticName=Отсутствует проверка признака ОбменДанными.Загрузка в обработчике событий объекта + +findFirst=Проверка должна идити первой diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java index 41653ea5653..39bd6d671d9 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java @@ -26,6 +26,7 @@ import org.junit.jupiter.api.Test; import java.util.List; +import java.util.Map; import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; @@ -36,9 +37,31 @@ class DataExchangeLoadingDiagnosticTest extends AbstractDiagnosticTest diagnostics; + Map configuration; - List diagnostics = getDiagnostics(); + // Проверяем срабатывания без изменения параметров + // when + configuration = diagnosticInstance.getInfo().getDefaultConfiguration(); + diagnosticInstance.configure(configuration); + diagnostics = getDiagnostics(); + // then + assertThat(diagnostics) + .hasSize(2) + .anyMatch(diagnostic -> diagnostic.getRange().equals( + Ranges.create(7, 10, 7, 22))) + .anyMatch(diagnostic -> diagnostic.getRange().equals( + Ranges.create(19, 10, 19, 17))); + + // Проверяем с включенным параметром findFirst + // when + configuration = diagnosticInstance.getInfo().getDefaultConfiguration(); + configuration.put("findFirst", true); + diagnosticInstance.configure(configuration); + diagnostics = getDiagnostics(); + + // then assertThat(diagnostics) .hasSize(3) .anyMatch(diagnostic -> diagnostic.getRange().equals( @@ -47,6 +70,5 @@ void test() { Ranges.create(19, 10, 19, 17))) .anyMatch(diagnostic -> diagnostic.getRange().equals( Ranges.create(33, 10, 33, 22))); - } } diff --git a/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl b/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl index c943ac42539..929bc52d74f 100644 --- a/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl +++ b/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl @@ -1,5 +1,5 @@ Процедура ПередУдалением(Отказ) - Если ОбменДанными.Загрузка = Истина Тогда + Если ОбменДанными.Загрузка Или ДополнительныеСвойства.Свойство("НеПроверятьУникальность") Тогда Возврат; КонецЕсли; Отказ = ОбщийМодуль.ЕстьОтказ(ОбменДанными.Загрузка); @@ -17,7 +17,7 @@ КонецЕсли; КонецПроцедуры -Procedure OnWrite(Cancel) +Procedure OnWrite(Cancel) // Ошибка Var Value; If DataExchange.Recipients Then Return; @@ -35,4 +35,10 @@ Procedure BeforeDelete(Cancel) For Each Item in new Array Do Return; EndDo; + + // Ошибка если ищем только первым + If DataExchange.Load Then + Return; + EndIf; + EndProcedure \ No newline at end of file From 570ff3dd9af5ee0301dd53b4b6a9ed6eb46cd1b8 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Mon, 20 Apr 2020 12:10:41 +0700 Subject: [PATCH 079/444] Precommit --- docs/diagnostics/DataExchangeLoading.md | 14 +++++++++++--- docs/diagnostics/index.md | 2 +- docs/en/diagnostics/DataExchangeLoading.md | 14 +++++++++++--- docs/en/diagnostics/index.md | 2 +- .../configuration/diagnostics-schema.json | 12 ++++++++++-- .../DataExchangeLoadingDiagnostic_ru.properties | 2 +- 6 files changed, 35 insertions(+), 11 deletions(-) diff --git a/docs/diagnostics/DataExchangeLoading.md b/docs/diagnostics/DataExchangeLoading.md index b792db68d54..4dde35aa74c 100644 --- a/docs/diagnostics/DataExchangeLoading.md +++ b/docs/diagnostics/DataExchangeLoading.md @@ -1,8 +1,14 @@ -# Добавьте проверку признака ОбменДанными.Загрузка в самом начале процедуры (DataExchangeLoading) +# Отсутствует проверка признака ОбменДанными.Загрузка в обработчике событий объекта (DataExchangeLoading) | Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Ошибка` | `BSL` | `Критичный` | `Да` | `10` | `standard`
`badpractice`
`unpredictable` | +| `Ошибка` | `BSL` | `Критичный` | `Да` | `5` | `standard`
`badpractice`
`unpredictable` | + +## Параметры + +| Имя | Тип | Описание | Значение по умолчанию | +| :-: | :-: | :-- | :-: | +| `findFirst` | `Булево` | ```Проверка должна идти первой``` | ```false``` | ## Описание диагностики @@ -65,5 +71,7 @@ ### Параметр конфигурационного файла ```json -"DataExchangeLoading": false +"DataExchangeLoading": { + "findFirst": false +} ``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 7037e7ad77c..e2659b87c15 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -28,7 +28,7 @@ | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Лишняя директива компиляции | Да | Важный | Дефект кода | `clumsy`
`standard`
`unpredictable` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Выполнение запроса в цикле | Да | Критичный | Ошибка | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Цикломатическая сложность | Да | Критичный | Дефект кода | `brainoverload` | -| [DataExchangeLoading](DataExchangeLoading.md) | Добавьте проверку признака ОбменДанными.Загрузка в самом начале процедуры | Да | Критичный | Ошибка | `standard`
`badpractice`
`unpredictable` | +| [DataExchangeLoading](DataExchangeLoading.md) | Отсутствует проверка признака ОбменДанными.Загрузка в обработчике событий объекта | Да | Критичный | Ошибка | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Удаление элемента при обходе коллекции посредством оператора "Для каждого ... Из ... Цикл" | Да | Важный | Ошибка | `standard`
`error` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Использование устаревшего метода "ТекущаяДата" | Да | Важный | Ошибка | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Использование устаревшего метода "Найти" | Да | Незначительный | Дефект кода | `deprecated` | diff --git a/docs/en/diagnostics/DataExchangeLoading.md b/docs/en/diagnostics/DataExchangeLoading.md index afbeffb325a..fd29eb2c18e 100644 --- a/docs/en/diagnostics/DataExchangeLoading.md +++ b/docs/en/diagnostics/DataExchangeLoading.md @@ -1,8 +1,14 @@ -# Add a check for the attribute ExchangeData.Load at the very beginning of the procedure (DataExchangeLoading) +# There is no check for the attribute DataExchange.Load in the object's event handler (DataExchangeLoading) | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Error` | `BSL` | `Critical` | `Yes` | `10` | `standard`
`badpractice`
`unpredictable` | +| `Error` | `BSL` | `Critical` | `Yes` | `5` | `standard`
`badpractice`
`unpredictable` | + +## Parameters + +| Name | Type | Description | Default value | +| :-: | :-: | :-- | :-: | +| `findFirst` | `Boolean` | ```Check should go first``` | ```false``` | ## Description @@ -64,5 +70,7 @@ EndProcedure ### Parameter for config ```json -"DataExchangeLoading": false +"DataExchangeLoading": { + "findFirst": false +} ``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 1e53873c90c..52d14d4e402 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -28,7 +28,7 @@ Total: **89** | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Needless compilation directive | Yes | Major | Code smell | `clumsy`
`standard`
`unpredictable` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Execution query on cycle | Yes | Critical | Error | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Cyclomatic complexity | Yes | Critical | Code smell | `brainoverload` | -| [DataExchangeLoading](DataExchangeLoading.md) | Add a check for the attribute ExchangeData.Load at the very beginning of the procedure | Yes | Critical | Error | `standard`
`badpractice`
`unpredictable` | +| [DataExchangeLoading](DataExchangeLoading.md) | There is no check for the attribute DataExchange.Load in the object's event handler | Yes | Critical | Error | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Deleting an item when iterating through collection using the operator "For each ... In ... Do" | Yes | Major | Error | `standard`
`error` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Using of the deprecated method "CurrentDate" | Yes | Major | Error | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Using of the deprecated method "Find" | Yes | Minor | Code smell | `deprecated` | diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json index 660be6ebd5f..8c346966659 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json @@ -151,13 +151,21 @@ "$id": "#/definitions/CyclomaticComplexity" }, "DataExchangeLoading": { - "description": "Add a check for the attribute ExchangeData.Load at the very beginning of the procedure", + "description": "There is no check for the attribute DataExchange.Load in the object's event handler", "default": null, "type": [ "boolean", "object" ], - "title": "Add a check for the attribute ExchangeData.Load at the very beginning of the procedure", + "title": "There is no check for the attribute DataExchange.Load in the object's event handler", + "properties": { + "findFirst": { + "description": "Check should go first", + "default": false, + "type": "boolean", + "title": "Check should go first" + } + }, "$id": "#/definitions/DataExchangeLoading" }, "DeletingCollectionItem": { diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_ru.properties index f7540a19724..b9ef05e50e5 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic_ru.properties @@ -1,4 +1,4 @@ diagnosticMessage=Добавьте проверку признака ОбменДанными.Загрузка в самом начале процедуры diagnosticName=Отсутствует проверка признака ОбменДанными.Загрузка в обработчике событий объекта -findFirst=Проверка должна идити первой +findFirst=Проверка должна идти первой From 2f678c57a9f4c6893e5132e1a322e2b38f65c557 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Mon, 20 Apr 2020 12:23:53 +0700 Subject: [PATCH 080/444] qf --- .../diagnostics/DataExchangeLoadingDiagnostic.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java index b0591f95470..df9278bf19e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java @@ -80,7 +80,9 @@ public DataExchangeLoadingDiagnostic(DiagnosticInfo info) { @Override public void configure(Map configuration) { - if (configuration == null) return; + if (configuration == null) { + return; + } DiagnosticHelper.configureDiagnostic(this, configuration, "findFirst"); } @@ -109,7 +111,7 @@ private boolean checkPassed(BSLParser.ProcDeclarationContext ctx) { .map(BSLParser.SubCodeBlockContext::codeBlock) .map(BSLParser.CodeBlockContext::statement) .flatMap(context -> context.stream() - .filter(statement -> { + .filter((BSLParser.StatementContext statement) -> { orderStatement.getAndIncrement(); if (findFirst && orderStatement.get() > 1) { return false; @@ -120,7 +122,7 @@ private boolean checkPassed(BSLParser.ProcDeclarationContext ctx) { .isPresent(); } - private boolean foundLoadConditionWithReturn(BSLParser.StatementContext ctx) { + private static boolean foundLoadConditionWithReturn(BSLParser.StatementContext ctx) { return Optional.of(ctx) .map(BSLParser.StatementContext::compoundStatement) .map(BSLParser.CompoundStatementContext::ifStatement) @@ -131,7 +133,7 @@ && foundReturnStatement(context)) .isPresent(); } - private boolean foundReturnStatement(BSLParser.IfBranchContext ifBranch) { + private static boolean foundReturnStatement(BSLParser.IfBranchContext ifBranch) { return Optional.of(ifBranch) .map(BSLParser.IfBranchContext::codeBlock) .map(BSLParser.CodeBlockContext::statement) @@ -142,7 +144,7 @@ private boolean foundReturnStatement(BSLParser.IfBranchContext ifBranch) { .isPresent(); } - private ParserRuleContext getSubContext(BSLParser.ProcDeclarationContext ctx) { + private static ParserRuleContext getSubContext(BSLParser.ProcDeclarationContext ctx) { return Trees.getAncestorByRuleIndex((ParserRuleContext) ctx.getRuleContext(), BSLParser.RULE_sub); } } From f75f9f0e3c5753cd60cbf95798538b7d65e5e258 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Mon, 20 Apr 2020 21:32:50 +0700 Subject: [PATCH 081/444] =?UTF-8?q?=D1=83=D0=B1=D1=80=D0=B0=D0=BB=20=D0=BD?= =?UTF-8?q?=D0=B5=D0=BD=D1=83=D0=B6=D0=BD=D1=8B=D0=B9=20configure?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/DataExchangeLoadingDiagnostic.java | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java index df9278bf19e..3af01357cfc 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java @@ -78,14 +78,6 @@ public DataExchangeLoadingDiagnostic(DiagnosticInfo info) { super(info); } - @Override - public void configure(Map configuration) { - if (configuration == null) { - return; - } - DiagnosticHelper.configureDiagnostic(this, configuration, "findFirst"); - } - @Override public ParseTree visitProcDeclaration(BSLParser.ProcDeclarationContext ctx) { Optional.of(ctx) @@ -110,6 +102,7 @@ private boolean checkPassed(BSLParser.ProcDeclarationContext ctx) { .map(BSLParser.ProcedureContext::subCodeBlock) .map(BSLParser.SubCodeBlockContext::codeBlock) .map(BSLParser.CodeBlockContext::statement) + // FIXME: сделай этот фрагмент кода проще и лучше .flatMap(context -> context.stream() .filter((BSLParser.StatementContext statement) -> { orderStatement.getAndIncrement(); From 8854a67c448caacb8c868462212a8e3216ccdb72 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Mon, 20 Apr 2020 22:56:12 +0700 Subject: [PATCH 082/444] =?UTF-8?q?=D1=84=D0=B8=D0=BA=D1=81=20=D1=80=D0=B5?= =?UTF-8?q?=D0=B3=D1=83=D0=BB=D1=8F=D1=80=D0=BA=D0=B8=20+=20map=20to=20fla?= =?UTF-8?q?tmap=20(=D0=B8=D0=B7=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB=D1=81=D1=8F?= =?UTF-8?q?=20=D0=BE=D1=82=20get)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/DataExchangeLoadingDiagnostic.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java index 3af01357cfc..a21afbc4362 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java @@ -28,14 +28,12 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; -import com.github._1c_syntax.bsl.languageserver.utils.DiagnosticHelper; import com.github._1c_syntax.bsl.languageserver.utils.Trees; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; -import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; @@ -63,7 +61,7 @@ public class DataExchangeLoadingDiagnostic extends AbstractVisitorDiagnostic { "^(ПередЗаписью|ПриЗаписи|ПередУдалением|BeforeWrite|BeforeDelete|OnWrite)$", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final Pattern searchCondition = Pattern.compile( - "ОбменДанными.Загрузка=Истина|ОбменДанными.Загрузка|DataExchange.Load=True|DataExchange.Load", + "ОбменДанными\\.Загрузка=Истина|ОбменДанными\\.Загрузка|DataExchange\\.Load=True|DataExchange\\.Load", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final boolean FIND_FIRST = false; @@ -88,8 +86,7 @@ public ParseTree visitProcDeclaration(BSLParser.ProcDeclarationContext ctx) { ) .flatMap(context -> Optional.of(documentContext.getSymbolTree()) - .map(symbolTree -> symbolTree.getMethodSymbol((BSLParser.SubContext) getSubContext(ctx))) - .get()) + .flatMap(symbolTree -> symbolTree.getMethodSymbol((BSLParser.SubContext) getSubContext(ctx)))) .ifPresent(methodSymbol -> diagnosticStorage.addDiagnostic(methodSymbol.getSubNameRange())); return ctx; } From 1e080a44e3d1d67a59551557bae9d3b60b9c6848 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Mon, 20 Apr 2020 23:04:27 +0700 Subject: [PATCH 083/444] =?UTF-8?q?=D0=A7=D0=B8=D1=81=D1=82=D0=BA=D0=B0=20?= =?UTF-8?q?=D1=80=D0=B5=D0=B3=D1=83=D0=BB=D1=8F=D1=80=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/DataExchangeLoadingDiagnostic.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java index a21afbc4362..377ff5df5fa 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java @@ -61,7 +61,7 @@ public class DataExchangeLoadingDiagnostic extends AbstractVisitorDiagnostic { "^(ПередЗаписью|ПриЗаписи|ПередУдалением|BeforeWrite|BeforeDelete|OnWrite)$", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final Pattern searchCondition = Pattern.compile( - "ОбменДанными\\.Загрузка=Истина|ОбменДанными\\.Загрузка|DataExchange\\.Load=True|DataExchange\\.Load", + "ОбменДанными\\.Загрузка|DataExchange\\.Load", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final boolean FIND_FIRST = false; From 6f438abe2fef9e77ee748dfca0bec222fcff46ea Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Mon, 20 Apr 2020 19:09:11 +0300 Subject: [PATCH 084/444] =?UTF-8?q?=D0=9D=D0=B5=D1=82=D0=BE=D1=87=D0=BD?= =?UTF-8?q?=D1=8B=D0=B5=20=D1=80=D0=B5=D0=B3=D1=83=D0=BB=D1=8F=D1=80=D0=BA?= =?UTF-8?q?=D0=B8=20-=20=D0=BD=D0=B5=D1=82=D0=BE=D1=87=D0=BD=D0=BE=D0=B5?= =?UTF-8?q?=20=D0=B8=D1=81=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D1=82=D0=BE=D1=87=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../configuration/LanguageServerConfiguration.java | 2 +- .../diagnostics/TimeoutsInExternalResourcesDiagnostic.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java index cecc4bbc843..ad412939633 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java @@ -69,7 +69,7 @@ public final class LanguageServerConfiguration { private static final ComputeDiagnosticsSkipSupport DEFAULT_COMPUTE_DIAGNOSTICS_SUPPORT_VARIANT = ComputeDiagnosticsSkipSupport.NEVER; - private static final Pattern searchConfiguration = Pattern.compile("Configuration.(xml|mdo)$"); + private static final Pattern searchConfiguration = Pattern.compile("Configuration\\.(xml|mdo)$"); private DiagnosticLanguage diagnosticLanguage; private boolean showCognitiveComplexityCodeLens; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TimeoutsInExternalResourcesDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TimeoutsInExternalResourcesDiagnostic.java index 7d9c8ab7ce5..6a4bfc16cbe 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TimeoutsInExternalResourcesDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TimeoutsInExternalResourcesDiagnostic.java @@ -53,7 +53,7 @@ ) public class TimeoutsInExternalResourcesDiagnostic extends AbstractVisitorDiagnostic { - private static final Pattern PATTERN_TIMEOUT = Pattern.compile("^.(Таймаут|Timeout)", + private static final Pattern PATTERN_TIMEOUT = Pattern.compile("^\\.(Таймаут|Timeout)", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final Pattern PATTERN_NEW_EXPRESSION = Pattern.compile( "^(FTPСоединение|FTPConnection|HTTPСоединение|HTTPConnection|WSОпределения|WSDefinitions|WSПрокси|WSProxy)", From 020625675f43b2faeaea34d345c6b6ac22906b7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=B2=D0=B0=D0=BD=D0=BE=D0=B2=20=D0=AD=D0=B4=D1=83?= =?UTF-8?q?=D0=B0=D1=80=D0=B4?= Date: Mon, 20 Apr 2020 22:07:28 +0300 Subject: [PATCH 085/444] =?UTF-8?q?=D0=94=D0=B8=D0=B0=D0=B3=D0=BD=D0=BE?= =?UTF-8?q?=D1=81=D1=82=D0=B8=D0=BA=D0=B0=20MultilingualStringHasAllDeclar?= =?UTF-8?q?edLanguages=20=D0=B1=D0=BE=D0=BB=D1=8C=D1=88=D0=B5=20=D0=BD?= =?UTF-8?q?=D0=B5=20=D1=81=D1=80=D0=B0=D0=B1=D0=B0=D1=82=D1=8B=D0=B2=D0=B0?= =?UTF-8?q?=D0=B5=D1=82=20=D0=B5=D1=81=D0=BB=D0=B8=20=D0=BF=D0=B5=D1=80?= =?UTF-8?q?=D0=B2=D1=8B=D0=BC=20=D0=BF=D0=B0=D1=80=D0=B0=D0=BC=D0=B5=D1=82?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=20=D0=9D=D0=A1=D1=82=D1=80=20=D0=B8=D0=B4?= =?UTF-8?q?=D0=B5=D1=82=20=D0=BF=D0=B5=D1=80=D0=B5=D0=BC=D0=B5=D0=BD=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../languageserver/utils/MultilingualStringAnalyser.java | 9 ++++++--- src/test/resources/cli/test.bsl | 2 +- ...ltilingualStringHasAllDeclaredLanguagesDiagnostic.bsl | 6 ++++++ 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MultilingualStringAnalyser.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MultilingualStringAnalyser.java index b0a7c618227..a4c34ad530d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MultilingualStringAnalyser.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MultilingualStringAnalyser.java @@ -75,7 +75,10 @@ public MultilingualStringAnalyser(String declaredLanguages) { } private static boolean isNotMultilingualString(BSLParser.GlobalMethodCallContext globalMethodCallContext) { - return !NSTR_METHOD_NAME_PATTERN.matcher(globalMethodCallContext.methodName().getText()).find(); + String firstParameterMultilingualString = getMultilingualString(globalMethodCallContext); + + return !(firstParameterMultilingualString.isEmpty() || firstParameterMultilingualString.startsWith("\"")) + || !NSTR_METHOD_NAME_PATTERN.matcher(globalMethodCallContext.methodName().getText()).find(); } private static boolean hasTemplateInParents(ParserRuleContext globalMethodCallContext) { @@ -129,7 +132,7 @@ public boolean parse(BSLParser.GlobalMethodCallContext ctx) { private void expandMultilingualString() { - Matcher matcher = NSTR_LANG_PATTERN.matcher(getMultilingualString()); + Matcher matcher = NSTR_LANG_PATTERN.matcher(getMultilingualString(this.globalMethodCallContext)); while (matcher.find()) { Matcher cutMatcher = NSTR_LANG_CUT_PATTERN.matcher(matcher.group()); @@ -139,7 +142,7 @@ private void expandMultilingualString() { } - private String getMultilingualString() { + private static String getMultilingualString(BSLParser.GlobalMethodCallContext globalMethodCallContext) { return globalMethodCallContext.doCall().callParamList().callParam(0).getText(); } diff --git a/src/test/resources/cli/test.bsl b/src/test/resources/cli/test.bsl index b07880b9f3c..013e3b93341 100644 --- a/src/test/resources/cli/test.bsl +++ b/src/test/resources/cli/test.bsl @@ -1 +1 @@ -Сообщить("Привет, мир!"); +Сообщить("Привет, мир!"); \ No newline at end of file diff --git a/src/test/resources/diagnostics/MultilingualStringHasAllDeclaredLanguagesDiagnostic.bsl b/src/test/resources/diagnostics/MultilingualStringHasAllDeclaredLanguagesDiagnostic.bsl index 017314c136c..cafbc817caa 100644 --- a/src/test/resources/diagnostics/MultilingualStringHasAllDeclaredLanguagesDiagnostic.bsl +++ b/src/test/resources/diagnostics/MultilingualStringHasAllDeclaredLanguagesDiagnostic.bsl @@ -42,4 +42,10 @@ БыстрыйДоступПредставление = СтроковыеФункцииКлиентСервер.СтрокаСЧисломДляЛюбогоЯзыка( НСтр("ru = ';%1 пользователь;;%1 пользователя;%1 пользователей;%1 пользователя'"), КоличествоПользователей); + Для каждого КодЯзыка Из КодыЯзыков Цикл + + Элемент[ИмяЛокализуемогоРеквизита(ИмяРеквизита, КодЯзыка)] = НСтр(ИсходнаяСтрока, КодЯзыка); + + КонецЦикла; + КонецПроцелуры \ No newline at end of file From 592fe3920d5c16a7c7b39a03591c39dbb64d1671 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=B2=D0=B0=D0=BD=D0=BE=D0=B2=20=D0=AD=D0=B4=D1=83?= =?UTF-8?q?=D0=B0=D1=80=D0=B4?= Date: Sun, 19 Apr 2020 02:06:09 +0300 Subject: [PATCH 086/444] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D0=B2=D0=B5=D1=80?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=B8=20=D1=80=D0=B5=D1=81=D1=83=D1=80=D1=81?= =?UTF-8?q?=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ExcessiveAutoTestCheckDiagnostic.java | 65 ++++++++++++++ ...ssiveAutoTestCheckDiagnostic_en.properties | 2 + ...ssiveAutoTestCheckDiagnostic_ru.properties | 2 + .../ExcessiveAutoTestCheckDiagnosticTest.java | 30 +++++++ .../ExcessiveAutoTestCheckDiagnostic.bsl | 86 +++++++++++++++++++ 5 files changed, 185 insertions(+) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/ExcessiveAutoTestCheckDiagnostic.bsl diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java new file mode 100644 index 00000000000..b0d56c33dcb --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java @@ -0,0 +1,65 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; +import org.antlr.v4.runtime.tree.ParseTree; + +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.MINOR, + minutesToFix = 1, + modules = { + ModuleType.FormModule, + ModuleType.ObjectModule, + ModuleType.RecordSetModule, + ModuleType.CommonModule + }, + tags = { + DiagnosticTag.STANDARD, + DiagnosticTag.DEPRECATED + } +) +public class ExcessiveAutoTestCheckDiagnostic extends AbstractVisitorDiagnostic { + + private static final Pattern ERROR_EXPRESSION = Pattern.compile( + "(\\.Свойство\\(\"АвтоТест\"\\)|=\"АвтоТест\"|\\.Property\\(\"AutoTest\"\\)|=\"AutoTest\")$", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE + ); + + public ExcessiveAutoTestCheckDiagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + public ParseTree visitIfBranch(BSLParser.IfBranchContext ctx) { + + if (expressionMatchesPattern(ctx.expression()) && codeBlockWithOnlyReturn(ctx.codeBlock())) { + diagnosticStorage.addDiagnostic((BSLParser.IfStatementContext) ctx.getParent()); + return ctx; + } + + return super.visitIfBranch(ctx); + } + + private boolean expressionMatchesPattern(BSLParser.ExpressionContext expression) { + return ERROR_EXPRESSION.matcher(expression.getText()).find(); + } + + private boolean codeBlockWithOnlyReturn(BSLParser.CodeBlockContext codeBlock) { + return codeBlock + .getTokens() + .stream() + .map(t -> t.getType()) + .filter(t -> t != BSLParser.WHITE_SPACE) + .filter(t -> t != BSLParser.LINE_COMMENT) + .filter(t -> t != BSLParser.SEMICOLON) + .noneMatch(t -> t != BSLParser.RETURN_KEYWORD); + } +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic_en.properties new file mode 100644 index 00000000000..4f5c9f199c6 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Delete parameter "AutoTest" check +diagnosticName=Excessive AutoTest Check diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic_ru.properties new file mode 100644 index 00000000000..710d74fea0a --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Удалите проверку параметра "АвтоТест" +diagnosticName=Избыточная проверка параметра АвтоТест diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnosticTest.java new file mode 100644 index 00000000000..4862264db48 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnosticTest.java @@ -0,0 +1,30 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class ExcessiveAutoTestCheckDiagnosticTest extends AbstractDiagnosticTest { + ExcessiveAutoTestCheckDiagnosticTest() { + super(ExcessiveAutoTestCheckDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(6); + assertThat(diagnostics, true) + .hasRange(3, 4, 7, 13) + .hasRange(14, 4, 16, 13) + .hasRange(22, 4, 26, 13) + .hasRange(46, 4, 48, 9) + .hasRange(54, 4, 56, 9) + .hasRange(62, 4, 66, 9); + + } +} diff --git a/src/test/resources/diagnostics/ExcessiveAutoTestCheckDiagnostic.bsl b/src/test/resources/diagnostics/ExcessiveAutoTestCheckDiagnostic.bsl new file mode 100644 index 00000000000..3dc0a5f7e61 --- /dev/null +++ b/src/test/resources/diagnostics/ExcessiveAutoTestCheckDiagnostic.bsl @@ -0,0 +1,86 @@ + +Процедура ПриСозданииНаСервере() + + Если Параметры.Свойство("АвтоТест") Тогда // Ругаемся + + Возврат; + + КонецЕсли; + +КонецПроцедуры + +Процедура ОбработкаЗаполнения(ДанныеЗаполнения, ТестЗаполения, СтандартнаяОбработка) + + // Пропускаем обработку, чтобы гарантировать получение формы при передаче параметра "АвтоТест" + Если ДанныеЗаполнения = "АвтоТест" Тогда // Ругаемся + Возврат; + КонецЕсли; + +КонецПроцедуры + +Процедура ПроверитьВыполение(Перечень) + + Если Перечень.Свойство("АвтоТест") Тогда // Ругаемся так как могло быть передано из формы + + Возврат; + + КонецЕсли; + +КонецПроцедуры + +Процедура БезОшибок() + + Перечень.Вставить("АвтоТест", "АвтоТест"); + + Если Перечень.Свойство("АвтоТест") Тогда // Тут не ругаемся + + ВыполняемДействиеСПеречнем(Перечень); + Возврат; + + КонецЕсли; + +КонецПроцедуры + +&AtServer +Procedure OnCreateAtServer() + + If Parameters.Property("AutoTest") Then // Issue + Return; + EndIf; + +EndProcedure + +Procedure Filling() + + If VariableName = "AutoTest" Then // Issue + Return; + EndIf; + +EndProcedure + +Procedure Check(List) + + If List.Property("AutoTest") Then // Issue + + Return; + + EndIf; + +EndProcedure + +Procedure NoError(List) + + If List.Property("AutoTest") Then // No error + + List.Delete("AutoTest"); + Return; + + EndIf; + +EndProcedure + +Если Отказ Тогда + + Возврат; + +КонецЕсли; \ No newline at end of file From 75e42ea3c5d0636affb4cc383dcf97ba9ae83e3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=B2=D0=B0=D0=BD=D0=BE=D0=B2=20=D0=AD=D0=B4=D1=83?= =?UTF-8?q?=D0=B0=D1=80=D0=B4?= Date: Mon, 20 Apr 2020 21:24:14 +0300 Subject: [PATCH 087/444] docs --- docs/diagnostics/ExcessiveAutoTestCheck.md | 45 +++++++++++++++++++ docs/en/diagnostics/ExcessiveAutoTestCheck.md | 36 +++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 docs/diagnostics/ExcessiveAutoTestCheck.md create mode 100644 docs/en/diagnostics/ExcessiveAutoTestCheck.md diff --git a/docs/diagnostics/ExcessiveAutoTestCheck.md b/docs/diagnostics/ExcessiveAutoTestCheck.md new file mode 100644 index 00000000000..577a9cd3773 --- /dev/null +++ b/docs/diagnostics/ExcessiveAutoTestCheck.md @@ -0,0 +1,45 @@ +# () + + + +## + + +## Описание диагностики +Стандарт 772 "Взаимодействие со средствами автоматизированного тестирования" был отменен. +В связи с этим, больше не нужна проверка параметра "АвтоТест" в коде форм. + +## Примеры +```bsl +Если Параметры.Свойство("АвтоТест") Тогда + Возврат; +КонецЕсли; +``` + +и обработчике ОбработкаЗаполнения модуля объекта (набора записей): + +```bsl +// Пропускаем обработку, чтобы гарантировать получение формы при передаче параметра "АвтоТест". +Если ДанныеЗаполнения = "АвтоТест" Тогда + Возврат; +КонецЕсли; +``` + +## Источники +* Источник: [Стандарт: Тексты модулей пункт 3](https://its.1c.ru/db/v8std#content:456:hdoc:3) + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Параметр конфигурационного файла + +```json +"": +``` \ No newline at end of file diff --git a/docs/en/diagnostics/ExcessiveAutoTestCheck.md b/docs/en/diagnostics/ExcessiveAutoTestCheck.md new file mode 100644 index 00000000000..4c1f1f6c135 --- /dev/null +++ b/docs/en/diagnostics/ExcessiveAutoTestCheck.md @@ -0,0 +1,36 @@ +# Excessive AutoTest Check + + + +## + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Parameter for config + +```json +"": +``` From 5a45929e363cb8db2987b6c3f7bbf69daef13135 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=B2=D0=B0=D0=BD=D0=BE=D0=B2=20=D0=AD=D0=B4=D1=83?= =?UTF-8?q?=D0=B0=D1=80=D0=B4?= Date: Mon, 20 Apr 2020 22:25:34 +0300 Subject: [PATCH 088/444] precommit --- docs/diagnostics/ExcessiveAutoTestCheck.md | 18 ++++++++-------- docs/diagnostics/index.md | 5 +++-- docs/en/diagnostics/ExcessiveAutoTestCheck.md | 16 +++++++------- docs/en/diagnostics/index.md | 5 +++-- .../ExcessiveAutoTestCheckDiagnostic.java | 21 +++++++++++++++++++ .../configuration/diagnostics-schema.json | 10 +++++++++ .../languageserver/configuration/schema.json | 3 +++ .../ExcessiveAutoTestCheckDiagnosticTest.java | 21 +++++++++++++++++++ 8 files changed, 78 insertions(+), 21 deletions(-) diff --git a/docs/diagnostics/ExcessiveAutoTestCheck.md b/docs/diagnostics/ExcessiveAutoTestCheck.md index 577a9cd3773..0ccd88ca4de 100644 --- a/docs/diagnostics/ExcessiveAutoTestCheck.md +++ b/docs/diagnostics/ExcessiveAutoTestCheck.md @@ -1,8 +1,8 @@ -# () +# Избыточная проверка параметра АвтоТест (ExcessiveAutoTestCheck) - - -## +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Дефект кода` | `BSL`
`OS` | `Незначительный` | `Да` | `1` | `standard`
`deprecated` | ## Описание диагностики @@ -29,17 +29,17 @@ * Источник: [Стандарт: Тексты модулей пункт 3](https://its.1c.ru/db/v8std#content:456:hdoc:3) ## Сниппеты - + ### Экранирование кода ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:ExcessiveAutoTestCheck-off +// BSLLS:ExcessiveAutoTestCheck-on ``` ### Параметр конфигурационного файла ```json -"": -``` \ No newline at end of file +"ExcessiveAutoTestCheck": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index e2659b87c15..a96bb0ad542 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,9 +8,9 @@ ## Список реализованных диагностик -Общее количество: **89** +Общее количество: **90** -* Дефект кода: **55** +* Дефект кода: **56** * Уязвимость: **2** * Ошибка: **30** * Потенциальная уязвимость: **2** @@ -38,6 +38,7 @@ | [EmptyCodeBlock](EmptyCodeBlock.md) | Пустой блок кода | Да | Важный | Дефект кода | `badpractice`
`suspicious` | | [EmptyRegion](EmptyRegion.md) | Область не должна быть пустой | Да | Информационный | Дефект кода | `standard` | | [EmptyStatement](EmptyStatement.md) | Пустой оператор | Да | Информационный | Дефект кода | `badpractice` | +| [ExcessiveAutoTestCheck](ExcessiveAutoTestCheck.md) | Избыточная проверка параметра АвтоТест | Да | Незначительный | Дефект кода | `standard`
`deprecated` | | [ExtraCommas](ExtraCommas.md) | Запятые без указания параметра в конце вызова метода | Да | Важный | Дефект кода | `standard`
`badpractice` | | [FormDataToValue](FormDataToValue.md) | Использование метода ДанныеФормыВЗначение | Да | Информационный | Дефект кода | `badpractice` | | [FunctionNameStartsWithGet](FunctionNameStartsWithGet.md) | Имя функции не должно начинаться с "Получить" | Нет | Информационный | Дефект кода | `standard` | diff --git a/docs/en/diagnostics/ExcessiveAutoTestCheck.md b/docs/en/diagnostics/ExcessiveAutoTestCheck.md index 4c1f1f6c135..4b27bd3522b 100644 --- a/docs/en/diagnostics/ExcessiveAutoTestCheck.md +++ b/docs/en/diagnostics/ExcessiveAutoTestCheck.md @@ -1,8 +1,8 @@ -# Excessive AutoTest Check +# Excessive AutoTest Check (ExcessiveAutoTestCheck) - - -## +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Code smell` | `BSL`
`OS` | `Minor` | `Yes` | `1` | `standard`
`deprecated` | ## Description @@ -20,17 +20,17 @@ * Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) --> ## Snippets - + ### Diagnostic ignorance in code ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:ExcessiveAutoTestCheck-off +// BSLLS:ExcessiveAutoTestCheck-on ``` ### Parameter for config ```json -"": +"ExcessiveAutoTestCheck": false ``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 52d14d4e402..f0bc7a14bbe 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,10 +8,10 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **89** +Total: **90** * Error: **30** -* Code smell: **55** +* Code smell: **56** * Vulnerability: **2** * Security Hotspot: **2** @@ -38,6 +38,7 @@ Total: **89** | [EmptyCodeBlock](EmptyCodeBlock.md) | Empty code block | Yes | Major | Code smell | `badpractice`
`suspicious` | | [EmptyRegion](EmptyRegion.md) | The region should not be empty | Yes | Info | Code smell | `standard` | | [EmptyStatement](EmptyStatement.md) | Empty statement | Yes | Info | Code smell | `badpractice` | +| [ExcessiveAutoTestCheck](ExcessiveAutoTestCheck.md) | Excessive AutoTest Check | Yes | Minor | Code smell | `standard`
`deprecated` | | [ExtraCommas](ExtraCommas.md) | Commas without a parameter at the end of a method call | Yes | Major | Code smell | `standard`
`badpractice` | | [FormDataToValue](FormDataToValue.md) | FormDataToValue method call | Yes | Info | Code smell | `badpractice` | | [FunctionNameStartsWithGet](FunctionNameStartsWithGet.md) | Function name shouldn't start with "Получить" | No | Info | Code smell | `standard` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java index b0d56c33dcb..6f62abf9e05 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java @@ -1,3 +1,24 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json index 8c346966659..4865d5c49a2 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json @@ -266,6 +266,16 @@ "title": "Empty statement", "$id": "#/definitions/EmptyStatement" }, + "ExcessiveAutoTestCheck": { + "description": "Excessive AutoTest Check", + "default": null, + "type": [ + "boolean", + "object" + ], + "title": "Excessive AutoTest Check", + "$id": "#/definitions/ExcessiveAutoTestCheck" + }, "ExtraCommas": { "description": "Commas without a parameter at the end of a method call", "default": null, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index befc3db93e5..68a6a5ac293 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -164,6 +164,9 @@ "EmptyStatement": { "$ref": "diagnostics-schema.json#/definitions/EmptyStatement" }, + "ExcessiveAutoTestCheck": { + "$ref": "diagnostics-schema.json#/definitions/ExcessiveAutoTestCheck" + }, "ExtraCommas": { "$ref": "diagnostics-schema.json#/definitions/ExtraCommas" }, diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnosticTest.java index 4862264db48..643ea145e52 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnosticTest.java @@ -1,3 +1,24 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; import org.eclipse.lsp4j.Diagnostic; From fa2292ee5c9b46395e26e2e5d86dcf125eef61b4 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Tue, 21 Apr 2020 09:07:37 +0300 Subject: [PATCH 089/444] begin transaction fp fix --- .../BeginTransactionBeforeTryCatchDiagnostic.java | 13 ++++++++----- .../BeginTransactionBeforeTryCatchDiagnostic.bsl | 5 ++++- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BeginTransactionBeforeTryCatchDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BeginTransactionBeforeTryCatchDiagnostic.java index b16e5dc3bc5..5776dc85206 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BeginTransactionBeforeTryCatchDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BeginTransactionBeforeTryCatchDiagnostic.java @@ -31,6 +31,7 @@ import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; +import java.util.Optional; import java.util.regex.Pattern; import java.util.stream.Stream; @@ -44,7 +45,7 @@ ) public class BeginTransactionBeforeTryCatchDiagnostic extends AbstractVisitorDiagnostic { private static final Pattern BEGIN_TRANSACTION_PATTERN = Pattern.compile( - "НачатьТранзакцию|BeginTransaction", + "^НачатьТранзакцию$|^BeginTransaction$", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private BSLParserRuleContext nodeBeginTransaction; @@ -60,10 +61,12 @@ private static boolean isGlobalMethodBeginTransaction(BSLParser.StatementContext if (ctx.getStart().getType() != BSLParser.IDENTIFIER) { return false; } - return ctx.getChildCount() > 0 - && ctx.getChild(0).getChildCount() > 0 - && ctx.getChild(0).getChild(0) instanceof BSLParser.GlobalMethodCallContext - && BEGIN_TRANSACTION_PATTERN.matcher(ctx.getText()).find(); + return Optional.of(ctx) + .map(BSLParser.StatementContext::callStatement) + .map(BSLParser.CallStatementContext::globalMethodCall) + .map(BSLParser.GlobalMethodCallContext::methodName) + .map(methodNameContext -> BEGIN_TRANSACTION_PATTERN.matcher(methodNameContext.getText()).matches()) + .orElse(false); } @Override diff --git a/src/test/resources/diagnostics/BeginTransactionBeforeTryCatchDiagnostic.bsl b/src/test/resources/diagnostics/BeginTransactionBeforeTryCatchDiagnostic.bsl index bd747c92626..c5af4eb1cff 100644 --- a/src/test/resources/diagnostics/BeginTransactionBeforeTryCatchDiagnostic.bsl +++ b/src/test/resources/diagnostics/BeginTransactionBeforeTryCatchDiagnostic.bsl @@ -102,4 +102,7 @@ НачатьТранзакцию(); // <-- Ошибка: просто в конце модуля -Коннектор.НачатьТранзакцию(); // Игнорируем, это не ошибка \ No newline at end of file +Коннектор.НачатьТранзакцию(); // Игнорируем, это не ошибка +ОбработкаПотокаНачатьТранзакцию(); // Игнор +BeginTransactionОбработкаПотокаНачать(); // Игнор +ОбработкаBeginTransactionПотокаНачать(); // Игнор From 5626489b2031972ecfd4ffc14e35554cd3bec50b Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Mon, 20 Apr 2020 22:02:55 +0300 Subject: [PATCH 090/444] DataExchangeLoadingDiagnostic npe fix --- .../diagnostics/DataExchangeLoadingDiagnostic.java | 9 +++++---- .../diagnostics/DataExchangeLoadingDiagnostic.bsl | 12 +++++++++++- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java index 377ff5df5fa..2a692d5c736 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java @@ -124,13 +124,14 @@ && foundReturnStatement(context)) } private static boolean foundReturnStatement(BSLParser.IfBranchContext ifBranch) { - return Optional.of(ifBranch) - .map(BSLParser.IfBranchContext::codeBlock) + + return Optional.ofNullable(ifBranch.codeBlock()) .map(BSLParser.CodeBlockContext::statement) - .flatMap(context -> context.stream() + .flatMap(statementContexts -> statementContexts.stream() .map(BSLParser.StatementContext::compoundStatement) .map(BSLParser.CompoundStatementContext::returnStatement) - .findFirst()) + .map(Optional::ofNullable) + .findAny()) .isPresent(); } diff --git a/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl b/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl index 929bc52d74f..37388ddc43f 100644 --- a/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl +++ b/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl @@ -41,4 +41,14 @@ Procedure BeforeDelete(Cancel) Return; EndIf; -EndProcedure \ No newline at end of file +EndProcedure + +Процедура ПриЗаписи(Отказ) + Если ОбменДанными.Загрузка Тогда + Если Не ДополнительныеСвойства.Свойство("ПропуститьОбновлениеВерсииДатЗапретаИзменения") Тогда + ДатыЗапретаИзмененияСлужебный.ОбновитьВерсиюДатЗапретаИзмененияПриЗагрузкеДанных(ЭтотОбъект); + КонецЕсли; + Очистить(); + Возврат; + КонецЕсли; +КонецПроцедуры From 65520bf609dc2ca91a7fd1446720564f84ac4b86 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Fri, 17 Apr 2020 00:47:31 +0300 Subject: [PATCH 091/444] CommonModuleAssignDiagnostic --- build.gradle.kts | 2 +- docs/diagnostics/CommonModuleAssign.md | 40 ++++++++++ docs/diagnostics/index.md | 1 + docs/en/diagnostics/CommonModuleAssign.md | 36 +++++++++ docs/en/diagnostics/index.md | 1 + .../CommonModuleAssignDiagnostic.java | 71 ++++++++++++++++++ .../configuration/diagnostics-schema.json | 10 +++ .../languageserver/configuration/schema.json | 3 + ...CommonModuleAssignDiagnostic_en.properties | 2 + ...CommonModuleAssignDiagnostic_ru.properties | 2 + .../CommonModuleAssignDiagnosticTest.java | 73 +++++++++++++++++++ .../CommonModuleAssignDiagnostic.bsl | 4 + 12 files changed, 244 insertions(+), 1 deletion(-) create mode 100644 docs/diagnostics/CommonModuleAssign.md create mode 100644 docs/en/diagnostics/CommonModuleAssign.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/CommonModuleAssignDiagnostic.bsl diff --git a/build.gradle.kts b/build.gradle.kts index 6b44f06a1ca..1fcb2a6bf78 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -87,7 +87,7 @@ dependencies { } implementation("com.github.1c-syntax", "utils", "0.2.1") - implementation("com.github.1c-syntax", "mdclasses", "v0.4.2") + implementation("com.github.1c-syntax", "mdclasses", "907eb24da8c174e99bb9bb7d309d43d0c80fd562") compileOnly("org.projectlombok", "lombok", lombok.version) diff --git a/docs/diagnostics/CommonModuleAssign.md b/docs/diagnostics/CommonModuleAssign.md new file mode 100644 index 00000000000..d984c3f3053 --- /dev/null +++ b/docs/diagnostics/CommonModuleAssign.md @@ -0,0 +1,40 @@ +# Присвоение общему модулю (CommonModuleAssign) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Ошибка` | `BSL`
`OS` | `Блокирующий` | `Да` | `2` | `error` | + + +## Описание диагностики + + +При присвоении значения общему модулю будет вызвано исключение. +Такая ситуация возможна когда в конфигурацию добавляется общий модуль с +именем которое уже задействованном для переменной. + +## Примеры + + +## Источники + + + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:CommonModuleAssign-off +// BSLLS:CommonModuleAssign-on +``` + +### Параметр конфигурационного файла + +```json +"CommonModuleAssign": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index a96bb0ad542..45529c8bdcb 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -24,6 +24,7 @@ | [CognitiveComplexity](CognitiveComplexity.md) | Когнитивная сложность | Да | Критичный | Дефект кода | `brainoverload` | | [CommentedCode](CommentedCode.md) | Закомментированный фрагмент кода | Да | Незначительный | Дефект кода | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Нарушение правил работы с транзакциями для метода 'ЗафиксироватьТранзакцию' | Да | Важный | Ошибка | `standard` | +| [CommonModuleAssign](CommonModuleAssign.md) | Присвоение общему модулю | Да | Блокирующий | Ошибка | `error` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Директивы компиляции методов | Да | Важный | Дефект кода | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Лишняя директива компиляции | Да | Важный | Дефект кода | `clumsy`
`standard`
`unpredictable` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Выполнение запроса в цикле | Да | Критичный | Ошибка | `performance` | diff --git a/docs/en/diagnostics/CommonModuleAssign.md b/docs/en/diagnostics/CommonModuleAssign.md new file mode 100644 index 00000000000..3ee862696f3 --- /dev/null +++ b/docs/en/diagnostics/CommonModuleAssign.md @@ -0,0 +1,36 @@ +# CommonModuleAssign (CommonModuleAssign) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Error` | `BSL`
`OS` | `Blocker` | `Yes` | `2` | `error` | + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:CommonModuleAssign-off +// BSLLS:CommonModuleAssign-on +``` + +### Parameter for config + +```json +"CommonModuleAssign": false +``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index f0bc7a14bbe..3289cd3f6d4 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -24,6 +24,7 @@ Total: **90** | [CognitiveComplexity](CognitiveComplexity.md) | Cognitive complexity | Yes | Critical | Code smell | `brainoverload` | | [CommentedCode](CommentedCode.md) | Commented out code | Yes | Minor | Code smell | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Violating transaction rules for the 'CommitTransaction' method | Yes | Major | Error | `standard` | +| [CommonModuleAssign](CommonModuleAssign.md) | CommonModuleAssign | Yes | Blocker | Error | `error` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Methods compilation directive | Yes | Major | Code smell | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Needless compilation directive | Yes | Major | Code smell | `clumsy`
`standard`
`unpredictable` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Execution query on cycle | Yes | Critical | Error | `performance` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic.java new file mode 100644 index 00000000000..7186b144dc9 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic.java @@ -0,0 +1,71 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.mdclasses.mdo.MDObjectBase; +import com.github._1c_syntax.mdclasses.metadata.Configuration; +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.TerminalNode; + +import java.util.Locale; +import java.util.Map; + +@DiagnosticMetadata( + type = DiagnosticType.ERROR, + severity = DiagnosticSeverity.BLOCKER, + minutesToFix = 2, + tags = { + DiagnosticTag.ERROR + } + +) +public class CommonModuleAssignDiagnostic extends AbstractVisitorDiagnostic { + + public CommonModuleAssignDiagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + public ParseTree visitLValue(BSLParser.LValueContext ctx) { + + TerminalNode identifier = ctx.IDENTIFIER(); + + if (identifier == null + || ctx.acceptor() != null) { + return ctx; + } + + Configuration configuration = documentContext.getServerContext().getConfiguration(); + if (configuration.commonModuleIsPresent(identifier.getText())) { + diagnosticStorage.addDiagnostic(identifier, info.getMessage(identifier.getText())); + } + + return ctx; + } + +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json index 4865d5c49a2..08206bf8600 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json @@ -96,6 +96,16 @@ "title": "Violating transaction rules for the 'CommitTransaction' method", "$id": "#/definitions/CommitTransactionOutsideTryCatch" }, + "CommonModuleAssign": { + "description": "CommonModuleAssign", + "default": null, + "type": [ + "boolean", + "object" + ], + "title": "CommonModuleAssign", + "$id": "#/definitions/CommonModuleAssign" + }, "CompilationDirectiveLost": { "description": "Methods compilation directive", "default": null, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 68a6a5ac293..a9c9b7086c0 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -122,6 +122,9 @@ "CommitTransactionOutsideTryCatch": { "$ref": "diagnostics-schema.json#/definitions/CommitTransactionOutsideTryCatch" }, + "CommonModuleAssign": { + "$ref": "diagnostics-schema.json#/definitions/CommonModuleAssign" + }, "CompilationDirectiveLost": { "$ref": "diagnostics-schema.json#/definitions/CompilationDirectiveLost" }, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic_en.properties new file mode 100644 index 00000000000..1a7b8febc02 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Rename variable, %s it's common module +diagnosticName=CommonModuleAssign diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic_ru.properties new file mode 100644 index 00000000000..efff9745f56 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Переименуйте переменную, т.к %s это имя общего модуля +diagnosticName=Присвоение общему модулю diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnosticTest.java new file mode 100644 index 00000000000..32eca5b1861 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnosticTest.java @@ -0,0 +1,73 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.ServerContext; +import com.github._1c_syntax.mdclasses.metadata.Configuration; +import com.github._1c_syntax.utils.Absolute; +import lombok.SneakyThrows; +import org.apache.commons.io.FileUtils; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class CommonModuleAssignDiagnosticTest extends AbstractDiagnosticTest { + CommonModuleAssignDiagnosticTest() { + super(CommonModuleAssignDiagnostic.class); + } + + private static final String PATH_TO_METADATA = "src/test/resources/metadata"; + private static final String PATH_TO_MODULE_FILE = "src/test/resources/diagnostics/CommonModuleAssignDiagnostic.bsl"; + + + @SneakyThrows + @Test + void test() { + + Path path = Absolute.path(PATH_TO_METADATA); + ServerContext serverContext = new ServerContext(path); + Configuration configurationMetadata = serverContext.getConfiguration(); + + + Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + DocumentContext documentContext = new DocumentContext( + testFile.toUri(), + FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), + serverContext + ); + + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(3, 0, 3, 17); + + } +} diff --git a/src/test/resources/diagnostics/CommonModuleAssignDiagnostic.bsl b/src/test/resources/diagnostics/CommonModuleAssignDiagnostic.bsl new file mode 100644 index 00000000000..d3f389a5cc7 --- /dev/null +++ b/src/test/resources/diagnostics/CommonModuleAssignDiagnostic.bsl @@ -0,0 +1,4 @@ + + +А = ПервыйОбщийМодуль; +ПервыйОбщиймодуль = 1; From d3ad313ebe06b25e6ba2284fabde4b0140d92ff6 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Fri, 17 Apr 2020 10:24:03 +0300 Subject: [PATCH 092/444] getCommonModule is Optional --- build.gradle.kts | 2 +- .../diagnostics/CommonModuleAssignDiagnostic.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 1fcb2a6bf78..de7bf935b05 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -87,7 +87,7 @@ dependencies { } implementation("com.github.1c-syntax", "utils", "0.2.1") - implementation("com.github.1c-syntax", "mdclasses", "907eb24da8c174e99bb9bb7d309d43d0c80fd562") + implementation("com.github.1c-syntax", "mdclasses", "82033ffb7dd8f4b4538ac431a722e480ad83b764") compileOnly("org.projectlombok", "lombok", lombok.version) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic.java index 7186b144dc9..8c495cd168f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic.java @@ -61,7 +61,7 @@ public ParseTree visitLValue(BSLParser.LValueContext ctx) { } Configuration configuration = documentContext.getServerContext().getConfiguration(); - if (configuration.commonModuleIsPresent(identifier.getText())) { + if (configuration.getCommonModule(identifier.getText()).isPresent()) { diagnosticStorage.addDiagnostic(identifier, info.getMessage(identifier.getText())); } From 40385621e49d67ca1684d2fdfeed7f71287c79b6 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Tue, 21 Apr 2020 11:40:43 +0300 Subject: [PATCH 093/444] =?UTF-8?q?=D0=A3=D0=B7=D0=BE=D1=80=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle.kts | 2 +- docs/diagnostics/CommonModuleAssign.md | 2 +- docs/diagnostics/index.md | 4 ++-- docs/en/diagnostics/index.md | 4 ++-- .../diagnostics/CommonModuleAssignDiagnostic.java | 4 ---- 5 files changed, 6 insertions(+), 10 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index de7bf935b05..9704149e2b2 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -87,7 +87,7 @@ dependencies { } implementation("com.github.1c-syntax", "utils", "0.2.1") - implementation("com.github.1c-syntax", "mdclasses", "82033ffb7dd8f4b4538ac431a722e480ad83b764") + implementation("com.github.1c-syntax", "mdclasses", "86be1579c4") compileOnly("org.projectlombok", "lombok", lombok.version) diff --git a/docs/diagnostics/CommonModuleAssign.md b/docs/diagnostics/CommonModuleAssign.md index d984c3f3053..500bccdfbef 100644 --- a/docs/diagnostics/CommonModuleAssign.md +++ b/docs/diagnostics/CommonModuleAssign.md @@ -24,8 +24,8 @@ * Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) --> ## Сниппеты - + ### Экранирование кода ```bsl diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 45529c8bdcb..0e68437ce24 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,11 +8,11 @@ ## Список реализованных диагностик -Общее количество: **90** +Общее количество: **91** * Дефект кода: **56** * Уязвимость: **2** -* Ошибка: **30** +* Ошибка: **31** * Потенциальная уязвимость: **2** | Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги | diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 3289cd3f6d4..89d07016df4 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,9 +8,9 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **90** +Total: **91** -* Error: **30** +* Error: **31** * Code smell: **56** * Vulnerability: **2** * Security Hotspot: **2** diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic.java index 8c495cd168f..77752bd2043 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic.java @@ -27,14 +27,10 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.parser.BSLParser; -import com.github._1c_syntax.mdclasses.mdo.MDObjectBase; import com.github._1c_syntax.mdclasses.metadata.Configuration; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; -import java.util.Locale; -import java.util.Map; - @DiagnosticMetadata( type = DiagnosticType.ERROR, severity = DiagnosticSeverity.BLOCKER, From 6da2c060a760ab730e7bdce6ee62590bd6d4cb5c Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Tue, 21 Apr 2020 14:33:48 +0300 Subject: [PATCH 094/444] Apply suggestions from code review --- docs/diagnostics/CommonModuleAssign.md | 2 +- .../diagnostics/CommonModuleAssignDiagnostic_en.properties | 2 +- .../diagnostics/CommonModuleAssignDiagnostic_ru.properties | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/diagnostics/CommonModuleAssign.md b/docs/diagnostics/CommonModuleAssign.md index 500bccdfbef..534c41d57d0 100644 --- a/docs/diagnostics/CommonModuleAssign.md +++ b/docs/diagnostics/CommonModuleAssign.md @@ -10,7 +10,7 @@ При присвоении значения общему модулю будет вызвано исключение. Такая ситуация возможна когда в конфигурацию добавляется общий модуль с -именем которое уже задействованном для переменной. +именем, которое уже задействовано для переменной. ## Примеры diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic_en.properties index 1a7b8febc02..ab5d844c83e 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic_en.properties @@ -1,2 +1,2 @@ -diagnosticMessage=Rename variable, %s it's common module +diagnosticMessage=Rename variable, %s is a common module name diagnosticName=CommonModuleAssign diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic_ru.properties index efff9745f56..70083abe48b 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic_ru.properties @@ -1,2 +1,2 @@ -diagnosticMessage=Переименуйте переменную, т.к %s это имя общего модуля +diagnosticMessage=Переименуйте переменную, т.к %s - это имя общего модуля diagnosticName=Присвоение общему модулю From 9ab8e4a0fc1d2ed6f9852a69b9e347adf1925866 Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Tue, 21 Apr 2020 17:50:49 +0300 Subject: [PATCH 095/444] =?UTF-8?q?=D0=B4=D0=B8=D0=B0=D0=B3=D0=BD=D0=BE?= =?UTF-8?q?=D1=81=D1=82=D0=B8=D0=BA=D0=B0=20=D0=9F=D0=BE=D0=B4=D1=80=D1=8F?= =?UTF-8?q?=D0=B4=20=D0=B8=D0=B4=D1=83=D1=89=D0=B8=D0=B5=20=D0=BF=D1=83?= =?UTF-8?q?=D1=81=D1=82=D1=8B=D0=B5=20=D1=81=D1=82=D1=80=D0=BE=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle.kts | 2 +- docs/diagnostics/ConsecutiveEmptyLines.md | 38 +++ docs/diagnostics/index.md | 5 +- docs/en/diagnostics/ConsecutiveEmptyLines.md | 34 ++ docs/en/diagnostics/index.md | 5 +- .../ConsecutiveEmptyLinesDiagnostic.java | 133 ++++++++ .../configuration/diagnostics-schema.json | 18 + .../languageserver/configuration/schema.json | 3 + ...secutiveEmptyLinesDiagnostic_en.properties | 4 + ...secutiveEmptyLinesDiagnostic_ru.properties | 4 + .../diagnostics/AbstractDiagnosticTest.java | 20 +- .../ConsecutiveEmptyLinesDiagnosticTest.java | 310 ++++++++++++++++++ .../ConsecutiveEmptyLinesDiagnostic.bsl | 34 ++ 13 files changed, 601 insertions(+), 9 deletions(-) create mode 100644 docs/diagnostics/ConsecutiveEmptyLines.md create mode 100644 docs/en/diagnostics/ConsecutiveEmptyLines.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/ConsecutiveEmptyLinesDiagnostic.bsl diff --git a/build.gradle.kts b/build.gradle.kts index 9704149e2b2..11e75582b2b 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -77,7 +77,7 @@ dependencies { implementation("org.reflections", "reflections", "0.9.10") - implementation("com.github.1c-syntax", "bsl-parser", "0.14.0") { + implementation("com.github.1c-syntax", "bsl-parser", "01cc1512e10b667a0ec3fdd2307ca0221bf52684") { exclude("com.tunnelvisionlabs", "antlr4-annotations") exclude("com.ibm.icu", "*") exclude("org.antlr", "ST4") diff --git a/docs/diagnostics/ConsecutiveEmptyLines.md b/docs/diagnostics/ConsecutiveEmptyLines.md new file mode 100644 index 00000000000..870d6df000d --- /dev/null +++ b/docs/diagnostics/ConsecutiveEmptyLines.md @@ -0,0 +1,38 @@ +# Подряд идущие пустые строки (ConsecutiveEmptyLines) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Дефект кода` | `BSL`
`OS` | `Информационный` | `Да` | `1` | `badpractice` | + +## Параметры + +| Имя | Тип | Описание | Значение по умолчанию | +| :-: | :-: | :-- | :-: | +| `allowedEmptyLinesCount` | `Целое` | ```Максимально разрешенное количество пустых строк``` | ```1``` | + + +## Описание диагностики + + +Для разделения блоков кода между собой используется вставка пустой строки. + +Вставка 2-х и более пустых строк не несет данной ценности и приводит к бессмысленному увеличению длины метода или модуля. + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:ConsecutiveEmptyLines-off +// BSLLS:ConsecutiveEmptyLines-on +``` + +### Параметр конфигурационного файла + +```json +"ConsecutiveEmptyLines": { + "allowedEmptyLinesCount": 1 +} +``` + diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 0e68437ce24..6dce551df6a 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,9 +8,9 @@ ## Список реализованных диагностик -Общее количество: **91** +Общее количество: **92** -* Дефект кода: **56** +* Дефект кода: **57** * Уязвимость: **2** * Ошибка: **31** * Потенциальная уязвимость: **2** @@ -27,6 +27,7 @@ | [CommonModuleAssign](CommonModuleAssign.md) | Присвоение общему модулю | Да | Блокирующий | Ошибка | `error` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Директивы компиляции методов | Да | Важный | Дефект кода | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Лишняя директива компиляции | Да | Важный | Дефект кода | `clumsy`
`standard`
`unpredictable` | +| [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Подряд идущие пустые строки | Да | Информационный | Дефект кода | `badpractice` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Выполнение запроса в цикле | Да | Критичный | Ошибка | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Цикломатическая сложность | Да | Критичный | Дефект кода | `brainoverload` | | [DataExchangeLoading](DataExchangeLoading.md) | Отсутствует проверка признака ОбменДанными.Загрузка в обработчике событий объекта | Да | Критичный | Ошибка | `standard`
`badpractice`
`unpredictable` | diff --git a/docs/en/diagnostics/ConsecutiveEmptyLines.md b/docs/en/diagnostics/ConsecutiveEmptyLines.md new file mode 100644 index 00000000000..d4ee1307f9a --- /dev/null +++ b/docs/en/diagnostics/ConsecutiveEmptyLines.md @@ -0,0 +1,34 @@ +# Consecutive empty lines (ConsecutiveEmptyLines) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Code smell` | `BSL`
`OS` | `Info` | `Yes` | `1` | `badpractice` | + +## Parameters + +| Name | Type | Description | Default value | +| :-: | :-: | :-- | :-: | +| `allowedEmptyLinesCount` | `Integer` | ```Maximum allowed consecutive empty lines``` | ```1``` | + + +## Description + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:ConsecutiveEmptyLines-off +// BSLLS:ConsecutiveEmptyLines-on +``` + +### Parameter for config + +```json +"ConsecutiveEmptyLines": { + "allowedEmptyLinesCount": 1 +} +``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 89d07016df4..659c900dc05 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,10 +8,10 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **91** +Total: **92** * Error: **31** -* Code smell: **56** +* Code smell: **57** * Vulnerability: **2** * Security Hotspot: **2** @@ -27,6 +27,7 @@ Total: **91** | [CommonModuleAssign](CommonModuleAssign.md) | CommonModuleAssign | Yes | Blocker | Error | `error` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Methods compilation directive | Yes | Major | Code smell | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Needless compilation directive | Yes | Major | Code smell | `clumsy`
`standard`
`unpredictable` | +| [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Consecutive empty lines | Yes | Info | Code smell | `badpractice` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Execution query on cycle | Yes | Critical | Error | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Cyclomatic complexity | Yes | Critical | Code smell | `brainoverload` | | [DataExchangeLoading](DataExchangeLoading.md) | There is no check for the attribute DataExchange.Load in the object's event handler | Yes | Critical | Error | `standard`
`badpractice`
`unpredictable` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnostic.java new file mode 100644 index 00000000000..8edb2e76bad --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnostic.java @@ -0,0 +1,133 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticParameter; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.providers.CodeActionProvider; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.parser.BSLLexer; +import org.antlr.v4.runtime.Token; +import org.eclipse.lsp4j.CodeAction; +import org.eclipse.lsp4j.CodeActionParams; +import org.eclipse.lsp4j.Diagnostic; +import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.TextEdit; + +import java.util.List; +import java.util.stream.Collectors; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.INFO, + minutesToFix = 1, + tags = { + DiagnosticTag.BADPRACTICE + } +) +public class ConsecutiveEmptyLinesDiagnostic extends AbstractDiagnostic implements QuickFixProvider { + + private static final int DEFAULT_ALLOWED_EMPTY_LINES_COUNT = 1; + + @DiagnosticParameter( + type = Integer.class, + defaultValue = "" + DEFAULT_ALLOWED_EMPTY_LINES_COUNT + ) + private int allowedEmptyLinesCount = DEFAULT_ALLOWED_EMPTY_LINES_COUNT; + + public ConsecutiveEmptyLinesDiagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + protected void check(DocumentContext documentContext) { + + final var tokens = documentContext.getTokens(); + if (tokens.isEmpty()){ + return; + } + + final int[] prevLineStorage = {0}; + // без EOF, т.к. его проще и чуть быстрее обработать вне цикла + tokens.subList(0, tokens.size() - 1) + .stream() + .filter(token -> token.getType() != BSLLexer.WHITE_SPACE) + .mapToInt(Token::getLine) + .distinct() + .forEachOrdered((int currentLine) -> { + checkEmptyLines(currentLine - 1, prevLineStorage[0]); + prevLineStorage[0] = currentLine; + }); + + checkEmptyLines(getEofTokenLine(tokens), prevLineStorage[0]); + } + + private void checkEmptyLines(int currentLine, int previousLine) { + if (currentLine - previousLine > allowedEmptyLinesCount){ + addIssue(previousLine, currentLine); + } + } + + private static int getEofTokenLine(List tokens) { + return tokens.get(tokens.size() - 1).getLine(); + } + + private void addIssue(int startEmptyLine, int lastEmptyLine) { + diagnosticStorage.addDiagnostic(startEmptyLine, 0, lastEmptyLine - 1, 0); + } + + @Override + public List getQuickFixes( + List diagnostics, CodeActionParams params, DocumentContext documentContext) { + + var eofTokenLine = getEofTokenLine(documentContext.getTokens()); + + var textEdits = diagnostics.stream() + .map(diagnostic -> getQuickFixText(diagnostic, eofTokenLine)) + .collect(Collectors.toList()); + + return CodeActionProvider.createCodeActions( + textEdits, + info.getResourceString("quickFixMessage"), + documentContext.getUri(), + diagnostics + ); + } + + private static TextEdit getQuickFixText(Diagnostic diagnostic, int eofTokenLine) { + Range range = diagnostic.getRange(); + + int endLine = range.getEnd().getLine() + 1; + String newText = "\n"; + if (endLine == eofTokenLine){ + endLine--; + newText = ""; + } + Range newRange = Ranges.create(range.getStart().getLine(), 0, endLine, 0); + return new TextEdit(newRange, newText); + } +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json index 08206bf8600..eaebb43623e 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json @@ -126,6 +126,24 @@ "title": "Needless compilation directive", "$id": "#/definitions/CompilationDirectiveNeedLess" }, + "ConsecutiveEmptyLines": { + "description": "Consecutive empty lines", + "default": null, + "type": [ + "boolean", + "object" + ], + "title": "Consecutive empty lines", + "properties": { + "allowedEmptyLinesCount": { + "description": "Maximum allowed consecutive empty lines", + "default": 1, + "type": "integer", + "title": "Maximum allowed consecutive empty lines" + } + }, + "$id": "#/definitions/ConsecutiveEmptyLines" + }, "CreateQueryInCycle": { "description": "Execution query on cycle", "default": null, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index a9c9b7086c0..6123c084a4b 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -131,6 +131,9 @@ "CompilationDirectiveNeedLess": { "$ref": "diagnostics-schema.json#/definitions/CompilationDirectiveNeedLess" }, + "ConsecutiveEmptyLines": { + "$ref": "diagnostics-schema.json#/definitions/ConsecutiveEmptyLines" + }, "CreateQueryInCycle": { "$ref": "diagnostics-schema.json#/definitions/CreateQueryInCycle" }, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnostic_en.properties new file mode 100644 index 00000000000..cfdc04aad50 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnostic_en.properties @@ -0,0 +1,4 @@ +diagnosticMessage=Modules must not have consecutive empty lines +diagnosticName=Consecutive empty lines +allowedEmptyLinesCount=Maximum allowed consecutive empty lines +quickFixMessage=Remove consecutive empty lines diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnostic_ru.properties new file mode 100644 index 00000000000..614adfdbe5b --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnostic_ru.properties @@ -0,0 +1,4 @@ +diagnosticMessage=Удалите лишние последовательные пустые строки +diagnosticName=Подряд идущие пустые строки +allowedEmptyLinesCount=Максимально разрешенное количество пустых строк +quickFixMessage=Удалить лишние последовательные пустые строки diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractDiagnosticTest.java index bf5079d1bf8..faf83ef5ee8 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractDiagnosticTest.java @@ -63,7 +63,10 @@ protected List getDiagnostics(String simpleFileName) { } protected List getQuickFixes(Diagnostic diagnostic) { - DocumentContext documentContext = getDocumentContext(); + return getQuickFixes(diagnostic, getDocumentContext()); + } + + protected List getQuickFixes(Diagnostic diagnostic, DocumentContext documentContext) { return getQuickFixes(documentContext, Collections.singletonList(diagnostic), diagnostic.getRange()); } @@ -101,14 +104,23 @@ protected DocumentContext getDocumentContext() { @SneakyThrows protected DocumentContext getDocumentContext(String SimpleFileName) { + String textDocumentContent = getText(SimpleFileName); + + return TestUtils.getDocumentContext(textDocumentContent); + } + + protected String getText() { + return getText(diagnosticInstance.getClass().getSimpleName()); + } + + @SneakyThrows + protected String getText(String SimpleFileName) { String filePath = "diagnostics/" + SimpleFileName + ".bsl"; - String textDocumentContent = IOUtils.resourceToString( + return IOUtils.resourceToString( filePath, StandardCharsets.UTF_8, this.getClass().getClassLoader() ); - - return TestUtils.getDocumentContext(textDocumentContent); } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnosticTest.java new file mode 100644 index 00000000000..ef89bdcb190 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnosticTest.java @@ -0,0 +1,310 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import org.eclipse.lsp4j.CodeAction; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class ConsecutiveEmptyLinesDiagnosticTest extends AbstractDiagnosticTest { + ConsecutiveEmptyLinesDiagnosticTest() { + super(ConsecutiveEmptyLinesDiagnostic.class); + } + + @Test + void test_EmptyTwoFirstLines() { + String module = " \n" + + "\n" + + "КонецПроцедуры"; + + List diagnostics = getDiagnosticsForText(module); + + assertThat(diagnostics, true) + .hasRange(0, 0, 1, 0) + .hasSize(1) + ; + } + + @Test + void test_EmptyThreeFirstLines() { + String module = " \n" + + "\n" + + "\n" + + "КонецПроцедуры"; + + List diagnostics = getDiagnosticsForText(module); + + assertThat(diagnostics, true) + .hasRange(0, 0, 2, 0) + .hasSize(1) + ; + } + + @Test + void test_EmptyTwoInnerLines() { + String module = "Процедура Первая()\n" + + "\n" + + "\n" + + "КонецПроцедуры"; + + List diagnostics = getDiagnosticsForText(module); + + assertThat(diagnostics, true) + .hasRange(1, 0, 2, 0) + .hasSize(1) + ; + } + + @Test + void test_EmptyTwoInnerLinesWithSpaces() { + String module = "Процедура Первая() \n" + + " \n" + + " \n" + + "КонецПроцедуры"; + + List diagnostics = getDiagnosticsForText(module); + + assertThat(diagnostics, true) + .hasRange(1, 0, 2, 0) + .hasSize(1) + ; + } + + @Test + void test_WorseEmptyTwoInnerLines() { + String module = "Процедура Первая() \n" + + " \n" + + " Метод1(); //комментарии \n" + + "\n" + + " \n" + + "КонецПроцедуры"; + + List diagnostics = getDiagnosticsForText(module); + + assertThat(diagnostics, true) + .hasRange(3, 0, 4, 0) + .hasSize(1) + ; + } + + @Test + void test_EmptyThreeInnerLines() { + String module = "Процедура Первая()\n" + + "\n" + + "\n" + + "\n" + + "КонецПроцедуры"; + + List diagnostics = getDiagnosticsForText(module); + + assertThat(diagnostics, true) + .hasRange(1, 0, 3, 0) + .hasSize(1) + ; + } + + @Test + void test_EmptyLastLines() { + String module = "Перем А;\n" + + "\n"; + + List diagnostics = getDiagnosticsForText(module); + + assertThat(diagnostics, true) + .hasRange(1, 0, 2, 0) + .hasSize(1) + ; + } + + @Test + void test_EmptyModule() { + String module = ""; + + List diagnostics = getDiagnosticsForText(module); + + assertThat(diagnostics, true) + .hasSize(0) + ; + } + + @Test + void test_OneLine() { + // если в конце файла есть пустая строка и EOF, то для пользователя это выглядит как 2 пустые строки + // и правило должно сработать + String module = "\n"; + + List diagnostics = getDiagnosticsForText(module); + + assertThat(diagnostics, true) + .hasRange(0, 0, 1, 0) + .hasSize(1) + ; + } + + @Test + void test_EmptyLinePlusOneFilledLine() { + String module = "\n//комментарий"; + + List diagnostics = getDiagnosticsForText(module); + + assertThat(diagnostics, true) + .hasSize(0) + ; + } + + @Test + void test_ConfigureEmptyLineParam() { + setTwoForAllowedEmptyLinesCount(); + + String module = "Процедура Первая()\n" + + "\n" + + "\n" + + "\n" + + "КонецПроцедуры"; + + List diagnostics = getDiagnosticsForText(module); + + assertThat(diagnostics, true) + .hasRange(1, 0, 3, 0) + .hasSize(1) + ; + } + + @Test + void test_ConfigureEmptyLineParamNoIssue() { + setTwoForAllowedEmptyLinesCount(); + + String module = "Процедура Первая()\n" + + "\n" + + "\n" + + "КонецПроцедуры"; + + List diagnostics = getDiagnosticsForText(module); + + assertThat(diagnostics, true) + .hasSize(0) + ; + } + + private void setTwoForAllowedEmptyLinesCount() { + Map configuration = diagnosticInstance.getInfo().getDefaultConfiguration(); + configuration.put("allowedEmptyLinesCount", 2); + diagnosticInstance.configure(configuration); + } + + @Test + void test_moduleWith_CRLF_And_Spaces() { + checkFileText(false); + } + + @Test + void test_moduleWith_CR_And_Spaces_And_Tab() { + checkFileText(true); + } + + void checkFileText(boolean use_CR_WithTab) { + + String module = getText(); + + if (use_CR_WithTab){ + module = module.replace("\n", "\r"); + module = module.replace(" ", "\t"); + } + + List diagnostics = getDiagnosticsForText(module); + + assertThat(diagnostics, true) + .hasRange(0, 0, 1, 0) + .hasRange(5, 0, 6, 0) + .hasRange(10, 0, 11, 0) + .hasRange(14, 0, 15, 0) + .hasRange(17, 0, 18, 0) + .hasRange(22, 0, 23, 0) + .hasRange(26, 0, 27, 0) + .hasRange(29, 0, 31, 0) + .hasRange(33, 0, 34, 0) + .hasSize(9); + } + + @Test + void testQuickFix() { + String module = getText(); + checkQuickFixes(module, true); + } + + private void checkQuickFixes(String module, boolean haveFix) { + final DocumentContext documentContext = TestUtils.getDocumentContext(module); + List diagnostics = getDiagnostics(documentContext); + + diagnostics.forEach(diagnostic -> checkFix(documentContext, diagnostic, haveFix)); + } + + @Test + void testQuickFixLastLines() { + String module = "Перем А;\n" + + "\n"; + checkQuickFixes(module, true); + } + + @Test + void testQuickFixEmptyModule() { + String module = ""; + checkQuickFixes(module, false); + } + + @Test + void testQuickFixOneLine() { + String module = "\n"; + checkQuickFixes(module, true); + } + + private void checkFix(DocumentContext documentContext, Diagnostic diagnostic, boolean haveFix) { + List quickFixes = getQuickFixes(diagnostic, documentContext); + + assertThat(quickFixes).hasSize(1); + + final CodeAction quickFix = quickFixes.get(0); + + if (haveFix){ + assertThat(quickFix).of(diagnosticInstance).in(documentContext) + .fixes(diagnostic); + + assertThat(quickFix).in(documentContext) + .hasChanges(1); + } else { + assertThat(quickFix).in(documentContext) + .hasChanges(0); + } + } + + private List getDiagnosticsForText(String textDocumentContent) { + DocumentContext documentContext = TestUtils.getDocumentContext(textDocumentContent); + return getDiagnostics(documentContext); + } +} diff --git a/src/test/resources/diagnostics/ConsecutiveEmptyLinesDiagnostic.bsl b/src/test/resources/diagnostics/ConsecutiveEmptyLinesDiagnostic.bsl new file mode 100644 index 00000000000..df679c5d832 --- /dev/null +++ b/src/test/resources/diagnostics/ConsecutiveEmptyLinesDiagnostic.bsl @@ -0,0 +1,34 @@ + + +//Ловим в начале модуля с пробелами +Перем Первая; +//ловим до методов c пробелами + + +Процедура Метод1() + + Если Истина Тогда //не ловим с пробелами до строки кода и ловим с пробелами после строки + + + КонецЕсли; + //Ловим строки после + + +КонецПроцедуры//ловим + + +Функция Метод2() + + Метод1(); //не ловим с пробелами до строки кода и ловим с пробелами после строки + + +КонецФункции +//Ловим в теле с пробелами + + +//Ловим 3 строки + + + +//Ловим в самом конце модуля + From 43ae7f7b3aa19bdadcf4070f29f24fa4acc65773 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Thu, 9 Apr 2020 22:07:00 +0300 Subject: [PATCH 096/444] =?UTF-8?q?=D0=A0=D0=B5=D1=84=D0=B0=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D0=BD=D0=B3=20=D0=BA=D0=BE=D0=BD=D1=84=D0=B8?= =?UTF-8?q?=D0=B3=D1=83=D1=80=D0=B0=D1=86=D0=B8=D0=B8.=20=D0=A0=D0=B0?= =?UTF-8?q?=D0=B7=D0=BD=D0=B5=D1=81=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=BD=D1=84=D0=B8=D0=B3=D1=83=D1=80=D0=B0=D1=86=D0=B8=D0=B8=20?= =?UTF-8?q?=D0=BF=D0=BE=20=D1=80=D0=B0=D0=B7=D0=BD=D1=8B=D0=BC=20options?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BSLTextDocumentService.java | 8 +- .../LanguageServerConfiguration.java | 98 ++----------------- .../codelens/CodeLensOptions.java | 36 +++++++ .../ComputeTrigger.java} | 4 +- .../diagnostics/DiagnosticsOptions.java | 47 +++++++++ .../Language.java} | 8 +- .../SkipSupport.java} | 4 +- .../databind/RulesDeserializer.java | 65 ++++++++++++ .../diagnostics/DiagnosticSupplier.java | 20 ++-- .../diagnostics/metadata/DiagnosticInfo.java | 17 ++-- .../reporter/GenericIssueReport.java | 2 +- .../providers/CodeLensProvider.java | 4 +- .../LanguageServerConfigurationTest.java | 24 +++-- .../diagnostics/DiagnosticSupplierTest.java | 16 +-- .../languageserver/diagnostics/SmokyTest.java | 2 +- .../metadata/DiagnosticInfoTest.java | 4 +- .../providers/CodeActionProviderTest.java | 2 +- src/test/resources/.bsl-language-server.json | 28 +++--- 18 files changed, 234 insertions(+), 155 deletions(-) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/CodeLensOptions.java rename src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/{ComputeDiagnosticsTrigger.java => diagnostics/ComputeTrigger.java} (89%) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java rename src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/{DiagnosticLanguage.java => diagnostics/Language.java} (84%) rename src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/{ComputeDiagnosticsSkipSupport.java => diagnostics/SkipSupport.java} (90%) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/RulesDeserializer.java diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentService.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentService.java index 622c76f9b47..89d0dea4e30 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentService.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentService.java @@ -22,7 +22,7 @@ package com.github._1c_syntax.bsl.languageserver; import com.github._1c_syntax.bsl.languageserver.codeactions.QuickFixSupplier; -import com.github._1c_syntax.bsl.languageserver.configuration.ComputeDiagnosticsTrigger; +import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.ComputeTrigger; import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.context.ServerContext; @@ -227,7 +227,7 @@ public CompletableFuture rename(RenameParams params) { @Override public void didOpen(DidOpenTextDocumentParams params) { DocumentContext documentContext = context.addDocument(params.getTextDocument()); - if (configuration.getComputeDiagnosticsTrigger() != ComputeDiagnosticsTrigger.NEVER) { + if (configuration.getDiagnosticsOptions().getComputeTrigger() != ComputeTrigger.NEVER) { validate(documentContext); } } @@ -244,7 +244,7 @@ public void didChange(DidChangeTextDocumentParams params) { diagnosticProvider.clearComputedDiagnostics(documentContext); documentContext.rebuild(params.getContentChanges().get(0).getText()); - if (configuration.getComputeDiagnosticsTrigger() == ComputeDiagnosticsTrigger.ONTYPE) { + if (configuration.getDiagnosticsOptions().getComputeTrigger() == ComputeTrigger.ONTYPE) { validate(documentContext); } } @@ -271,7 +271,7 @@ public void didSave(DidSaveTextDocumentParams params) { return; } - if (configuration.getComputeDiagnosticsTrigger() != ComputeDiagnosticsTrigger.NEVER) { + if (configuration.getDiagnosticsOptions().getComputeTrigger() != ComputeTrigger.NEVER) { validate(documentContext); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java index ad412939633..a57ee35516c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java @@ -23,19 +23,14 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JavaType; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.github._1c_syntax.bsl.languageserver.configuration.codelens.CodeLensOptions; +import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.DiagnosticsOptions; import com.github._1c_syntax.utils.Absolute; import lombok.AllArgsConstructor; import lombok.Data; import lombok.extern.slf4j.Slf4j; -import org.eclipse.lsp4j.jsonrpc.messages.Either; import javax.annotation.Nullable; import java.io.File; @@ -43,11 +38,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; import java.util.List; -import java.util.Map; import java.util.Optional; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -61,41 +52,22 @@ @JsonIgnoreProperties(ignoreUnknown = true) public final class LanguageServerConfiguration { - public static final DiagnosticLanguage DEFAULT_DIAGNOSTIC_LANGUAGE = DiagnosticLanguage.RU; - private static final boolean DEFAULT_SHOW_COGNITIVE_COMPLEXITY_CODE_LENS = Boolean.TRUE; - private static final boolean DEFAULT_SHOW_CYCLOMATIC_COMPLEXITY_CODE_LENS = Boolean.TRUE; - private static final ComputeDiagnosticsTrigger DEFAULT_COMPUTE_DIAGNOSTICS_TRIGGER - = ComputeDiagnosticsTrigger.ONSAVE; - private static final ComputeDiagnosticsSkipSupport DEFAULT_COMPUTE_DIAGNOSTICS_SUPPORT_VARIANT - = ComputeDiagnosticsSkipSupport.NEVER; - private static final Pattern searchConfiguration = Pattern.compile("Configuration\\.(xml|mdo)$"); - private DiagnosticLanguage diagnosticLanguage; - private boolean showCognitiveComplexityCodeLens; - private boolean showCyclomaticComplexityCodeLens; - private ComputeDiagnosticsTrigger computeDiagnosticsTrigger; - private ComputeDiagnosticsSkipSupport computeDiagnosticsSkipSupport; + @JsonProperty("diagnostics") + private DiagnosticsOptions diagnosticsOptions; + @JsonProperty("codeLens") + private CodeLensOptions codeLensOptions; @Nullable private File traceLog; - @JsonDeserialize(using = LanguageServerConfiguration.DiagnosticsDeserializer.class) - private Map>> diagnostics; @Nullable private Path configurationRoot; private LanguageServerConfiguration() { - this(DEFAULT_DIAGNOSTIC_LANGUAGE); - } - - private LanguageServerConfiguration(DiagnosticLanguage diagnosticLanguage) { this( - diagnosticLanguage, - DEFAULT_SHOW_COGNITIVE_COMPLEXITY_CODE_LENS, - DEFAULT_SHOW_CYCLOMATIC_COMPLEXITY_CODE_LENS, - DEFAULT_COMPUTE_DIAGNOSTICS_TRIGGER, - DEFAULT_COMPUTE_DIAGNOSTICS_SUPPORT_VARIANT, + new DiagnosticsOptions(), + new CodeLensOptions(), null, - new HashMap<>(), null ); } @@ -123,10 +95,6 @@ public static LanguageServerConfiguration create() { return new LanguageServerConfiguration(); } - public static LanguageServerConfiguration create(DiagnosticLanguage diagnosticLanguage) { - return new LanguageServerConfiguration(diagnosticLanguage); - } - public static Path getCustomConfigurationRoot(LanguageServerConfiguration configuration, Path srcDir) { Path rootPath = null; @@ -179,52 +147,4 @@ private static File getConfigurationFile(Path rootPath) { return configurationFile; } - static class DiagnosticsDeserializer extends JsonDeserializer>>> { - - @Override - public Map>> deserialize( - JsonParser p, - DeserializationContext context - ) throws IOException { - - JsonNode diagnostics = p.getCodec().readTree(p); - - if (diagnostics == null) { - return Collections.emptyMap(); - } - - ObjectMapper mapper = new ObjectMapper(); - Map>> diagnosticsMap = new HashMap<>(); - - Iterator> diagnosticsNodes = diagnostics.fields(); - diagnosticsNodes.forEachRemaining((Map.Entry entry) -> { - JsonNode diagnosticConfig = entry.getValue(); - if (diagnosticConfig.isBoolean()) { - diagnosticsMap.put(entry.getKey(), Either.forLeft(diagnosticConfig.asBoolean())); - } else { - Map diagnosticConfiguration = getDiagnosticConfiguration(mapper, entry.getValue()); - diagnosticsMap.put(entry.getKey(), Either.forRight(diagnosticConfiguration)); - } - }); - - return diagnosticsMap; - } - - private static Map getDiagnosticConfiguration( - ObjectMapper mapper, - JsonNode diagnosticConfig - ) { - Map diagnosticConfiguration; - try { - JavaType type = mapper.getTypeFactory().constructType(new TypeReference>() {}); - diagnosticConfiguration = mapper.readValue(mapper.treeAsTokens(diagnosticConfig), type); - } catch (IOException e) { - LOGGER.error("Can't deserialize diagnostic configuration", e); - return null; - } - return diagnosticConfiguration; - } - - } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/CodeLensOptions.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/CodeLensOptions.java new file mode 100644 index 00000000000..f1e718b527e --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/CodeLensOptions.java @@ -0,0 +1,36 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.configuration.codelens; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class CodeLensOptions { + private boolean showCognitiveComplexity = true; + private boolean showCyclomaticComplexity = true; +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/ComputeDiagnosticsTrigger.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/ComputeTrigger.java similarity index 89% rename from src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/ComputeDiagnosticsTrigger.java rename to src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/ComputeTrigger.java index 338e8a49caf..ddd9171d145 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/ComputeDiagnosticsTrigger.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/ComputeTrigger.java @@ -19,9 +19,9 @@ * 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.configuration; +package com.github._1c_syntax.bsl.languageserver.configuration.diagnostics; -public enum ComputeDiagnosticsTrigger { +public enum ComputeTrigger { ONTYPE, ONSAVE, NEVER diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java new file mode 100644 index 00000000000..f33404b2c2f --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java @@ -0,0 +1,47 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.configuration.diagnostics; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.databind.RulesDeserializer; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.eclipse.lsp4j.jsonrpc.messages.Either; + +import java.util.HashMap; +import java.util.Map; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class DiagnosticsOptions { + private Language language = Language.RU; + private ComputeTrigger computeTrigger = ComputeTrigger.ONSAVE; + private SkipSupport skipSupport = SkipSupport.NEVER; + private Mode mode = Mode.ON; + + @JsonDeserialize(using = RulesDeserializer.class) + private Map>> rules = new HashMap<>(); +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/DiagnosticLanguage.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Language.java similarity index 84% rename from src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/DiagnosticLanguage.java rename to src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Language.java index 9937963caea..2cb62faa95f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/DiagnosticLanguage.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Language.java @@ -19,15 +19,17 @@ * 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.configuration; +package com.github._1c_syntax.bsl.languageserver.configuration.diagnostics; -public enum DiagnosticLanguage { +public enum Language { RU("ru"), EN("en"); + public static final Language DEFAULT_LANGUAGE = RU; + private final String languageCode; - DiagnosticLanguage(String languageCode) { + Language(String languageCode) { this.languageCode = languageCode; } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/ComputeDiagnosticsSkipSupport.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/SkipSupport.java similarity index 90% rename from src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/ComputeDiagnosticsSkipSupport.java rename to src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/SkipSupport.java index 44a40192890..3ab9bed9c69 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/ComputeDiagnosticsSkipSupport.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/SkipSupport.java @@ -19,11 +19,11 @@ * 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.configuration; +package com.github._1c_syntax.bsl.languageserver.configuration.diagnostics; import com.fasterxml.jackson.annotation.JsonProperty; -public enum ComputeDiagnosticsSkipSupport { +public enum SkipSupport { @JsonProperty("withSupportLocked") WITH_SUPPORT_LOCKED, @JsonProperty("withSupport") diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/RulesDeserializer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/RulesDeserializer.java new file mode 100644 index 00000000000..3d2384ab800 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/RulesDeserializer.java @@ -0,0 +1,65 @@ +package com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.databind; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.lsp4j.jsonrpc.messages.Either; + +import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +@Slf4j +public class RulesDeserializer extends JsonDeserializer>>> { + @Override + public Map>> deserialize( + JsonParser p, + DeserializationContext context + ) throws IOException { + + JsonNode diagnostics = p.getCodec().readTree(p); + + if (diagnostics == null) { + return Collections.emptyMap(); + } + + ObjectMapper mapper = new ObjectMapper(); + Map>> diagnosticsMap = new HashMap<>(); + + Iterator> diagnosticsNodes = diagnostics.fields(); + diagnosticsNodes.forEachRemaining((Map.Entry entry) -> { + JsonNode diagnosticConfig = entry.getValue(); + if (diagnosticConfig.isBoolean()) { + diagnosticsMap.put(entry.getKey(), Either.forLeft(diagnosticConfig.asBoolean())); + } else { + Map diagnosticConfiguration = getDiagnosticConfiguration(mapper, entry.getValue()); + diagnosticsMap.put(entry.getKey(), Either.forRight(diagnosticConfiguration)); + } + }); + + return diagnosticsMap; + } + + private static Map getDiagnosticConfiguration( + ObjectMapper mapper, + JsonNode diagnosticConfig + ) { + Map diagnosticConfiguration; + try { + JavaType type = mapper.getTypeFactory().constructType(new TypeReference>() {}); + diagnosticConfiguration = mapper.readValue(mapper.treeAsTokens(diagnosticConfig), type); + } catch (IOException e) { + LOGGER.error("Can't deserialize diagnostic configuration", e); + return null; + } + return diagnosticConfiguration; + } + +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java index 31eb9c99ea3..60852b5d45d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java @@ -21,7 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; -import com.github._1c_syntax.bsl.languageserver.configuration.ComputeDiagnosticsSkipSupport; +import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.SkipSupport; import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.context.FileType; @@ -68,7 +68,7 @@ public > Optional getDiagnosticInstances(DocumentContext documentContext) { - var configuredSkipSupport = configuration.getComputeDiagnosticsSkipSupport(); + var configuredSkipSupport = configuration.getDiagnosticsOptions().getSkipSupport(); if (needToComputeDiagnostics(documentContext, configuredSkipSupport)) { FileType fileType = documentContext.getFileType(); @@ -94,7 +94,7 @@ public List getDiagnosticInstances(DocumentContext documentContex } public BSLDiagnostic getDiagnosticInstance(Class diagnosticClass) { - DiagnosticInfo info = new DiagnosticInfo(diagnosticClass, configuration.getDiagnosticLanguage()); + DiagnosticInfo info = new DiagnosticInfo(diagnosticClass, configuration.getDiagnosticsOptions().getLanguage()); BSLDiagnostic diagnosticInstance = createDiagnosticInstance(info); configureDiagnostic(diagnosticInstance); @@ -110,12 +110,12 @@ private BSLDiagnostic createDiagnosticInstance(DiagnosticInfo diagnosticInfo) { } private DiagnosticInfo createDiagnosticInfo(Class diagnosticClass) { - return new DiagnosticInfo(diagnosticClass, configuration.getDiagnosticLanguage()); + return new DiagnosticInfo(diagnosticClass, configuration.getDiagnosticsOptions().getLanguage()); } private void configureDiagnostic(BSLDiagnostic diagnostic) { Either> diagnosticConfiguration = - configuration.getDiagnostics().get(diagnostic.getInfo().getCode().getStringValue()); + configuration.getDiagnosticsOptions().getRules().get(diagnostic.getInfo().getCode().getStringValue()); if (diagnosticConfiguration != null && diagnosticConfiguration.isRight()) { diagnostic.configure(diagnosticConfiguration.getRight()); @@ -128,7 +128,7 @@ private boolean isEnabled(DiagnosticInfo diagnosticInfo) { } Either> diagnosticConfiguration = - configuration.getDiagnostics().get(diagnosticInfo.getCode().getStringValue()); + configuration.getDiagnosticsOptions().getRules().get(diagnosticInfo.getCode().getStringValue()); boolean activatedByDefault = diagnosticConfiguration == null && diagnosticInfo.isActivatedByDefault(); boolean hasCustomConfiguration = diagnosticConfiguration != null && diagnosticConfiguration.isRight(); @@ -192,9 +192,9 @@ private static boolean passedCompatibilityMode( private static boolean needToComputeDiagnostics( DocumentContext documentContext, - ComputeDiagnosticsSkipSupport configuredSkipSupport + SkipSupport configuredSkipSupport ) { - if (configuredSkipSupport == ComputeDiagnosticsSkipSupport.NEVER) { + if (configuredSkipSupport == SkipSupport.NEVER) { return true; } @@ -207,11 +207,11 @@ private static boolean needToComputeDiagnostics( return true; } - if (configuredSkipSupport == ComputeDiagnosticsSkipSupport.WITH_SUPPORT_LOCKED) { + if (configuredSkipSupport == SkipSupport.WITH_SUPPORT_LOCKED) { return moduleSupportVariant != SupportVariant.NOT_EDITABLE; } - return configuredSkipSupport != ComputeDiagnosticsSkipSupport.WITH_SUPPORT; + return configuredSkipSupport != SkipSupport.WITH_SUPPORT; } @SuppressWarnings("unchecked") diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java index aeafee2ec08..f2abcdb78d9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java @@ -21,8 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics.metadata; -import com.github._1c_syntax.bsl.languageserver.configuration.DiagnosticLanguage; -import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; +import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language; import com.github._1c_syntax.bsl.languageserver.diagnostics.BSLDiagnostic; import com.github._1c_syntax.bsl.languageserver.utils.UTF8Control; import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; @@ -42,6 +41,8 @@ import java.util.ResourceBundle; import java.util.stream.Collectors; +import static com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language.DEFAULT_LANGUAGE; + @Slf4j public class DiagnosticInfo { @@ -49,15 +50,15 @@ public class DiagnosticInfo { = createSeverityToLSPSeverityMap(); private final Class diagnosticClass; - private final DiagnosticLanguage diagnosticLanguage; + private final Language language; private final DiagnosticCode diagnosticCode; private final DiagnosticMetadata diagnosticMetadata; private final List diagnosticParameters; - public DiagnosticInfo(Class diagnosticClass, DiagnosticLanguage diagnosticLanguage) { + public DiagnosticInfo(Class diagnosticClass, Language language) { this.diagnosticClass = diagnosticClass; - this.diagnosticLanguage = diagnosticLanguage; + this.language = language; diagnosticCode = createDiagnosticCode(); diagnosticMetadata = diagnosticClass.getAnnotation(DiagnosticMetadata.class); @@ -65,7 +66,7 @@ public DiagnosticInfo(Class diagnosticClass, Diagnostic } public DiagnosticInfo(Class diagnosticClass) { - this(diagnosticClass, LanguageServerConfiguration.DEFAULT_DIAGNOSTIC_LANGUAGE); + this(diagnosticClass, DEFAULT_LANGUAGE); } public Class getDiagnosticClass() { @@ -81,7 +82,7 @@ public String getName() { } public String getDescription() { - String langCode = diagnosticLanguage.getLanguageCode(); + String langCode = language.getLanguageCode(); String resourceName = langCode + "/" + diagnosticCode.getStringValue() + ".md"; InputStream descriptionStream = diagnosticClass.getResourceAsStream(resourceName); @@ -108,7 +109,7 @@ public String getMessage(Object... args) { } public String getResourceString(String key) { - String languageCode = diagnosticLanguage.getLanguageCode(); + String languageCode = language.getLanguageCode(); Locale locale = Locale.forLanguageTag(languageCode); return ResourceBundle.getBundle(diagnosticClass.getName(), locale, new UTF8Control()).getString(key).intern(); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericIssueReport.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericIssueReport.java index 8ddb97aca14..1d75e6d8957 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericIssueReport.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericIssueReport.java @@ -141,7 +141,7 @@ public GenericIssueEntry(String fileName, Diagnostic diagnostic) { Optional> diagnosticClass = diagnosticSupplier.getDiagnosticClass(diagnostic.getCode()); if (diagnosticClass.isPresent()) { - DiagnosticInfo info = new DiagnosticInfo(diagnosticClass.get(), configuration.getDiagnosticLanguage()); + DiagnosticInfo info = new DiagnosticInfo(diagnosticClass.get(), configuration.getDiagnosticsOptions().getLanguage()); effortMinutes = info.getMinutesToFix(); } else { effortMinutes = 0; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeLensProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeLensProvider.java index d531b19d6ab..8acdaaeb5e2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeLensProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeLensProvider.java @@ -49,7 +49,7 @@ public List getCodeLens(DocumentContext documentContext) { private List getCognitiveComplexityCodeLenses(DocumentContext documentContext) { List codeLenses = new ArrayList<>(); - if (configuration.isShowCognitiveComplexityCodeLens()) { + if (configuration.getCodeLensOptions().isShowCognitiveComplexity()) { Map methodsComplexity = documentContext.getCognitiveComplexityData() .getMethodsComplexity(); @@ -72,7 +72,7 @@ private List getCognitiveComplexityCodeLenses(DocumentContext document private List getCyclomaticComplexityCodeLenses(DocumentContext documentContext) { List codeLenses = new ArrayList<>(); - if (configuration.isShowCyclomaticComplexityCodeLens()) { + if (configuration.getCodeLensOptions().isShowCyclomaticComplexity()) { Map methodsComplexity = documentContext.getCyclomaticComplexityData() .getMethodsComplexity(); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java index 74b92647c3d..5dc538510b0 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java @@ -21,6 +21,8 @@ */ package com.github._1c_syntax.bsl.languageserver.configuration; +import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.DiagnosticsOptions; +import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language; import com.github._1c_syntax.utils.Absolute; import org.eclipse.lsp4j.jsonrpc.messages.Either; import org.junit.jupiter.api.BeforeEach; @@ -34,7 +36,7 @@ import java.nio.file.Paths; import java.util.Map; -import static com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration.DEFAULT_DIAGNOSTIC_LANGUAGE; +import static com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language.DEFAULT_LANGUAGE; import static org.assertj.core.api.Assertions.assertThat; class LanguageServerConfigurationTest { @@ -58,8 +60,8 @@ void createDefault() { LanguageServerConfiguration configuration = LanguageServerConfiguration.create(); // then - assertThat(configuration.getDiagnosticLanguage()).isEqualTo(DiagnosticLanguage.RU); - assertThat(configuration.getDiagnostics()).isEmpty(); + assertThat(configuration.getDiagnosticsOptions().getLanguage()).isEqualTo(com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language.RU); + assertThat(configuration.getDiagnosticsOptions().getRules()).isEmpty(); } @Test @@ -72,10 +74,11 @@ void createFromFile() { LanguageServerConfiguration configuration = LanguageServerConfiguration.create(configurationFile); // then - DiagnosticLanguage diagnosticLanguage = configuration.getDiagnosticLanguage(); - Map>> diagnostics = configuration.getDiagnostics(); + DiagnosticsOptions diagnosticsOptions = configuration.getDiagnosticsOptions(); + Language language = diagnosticsOptions.getLanguage(); + Map>> diagnostics = diagnosticsOptions.getRules(); - assertThat(diagnosticLanguage).isEqualTo(DiagnosticLanguage.EN); + assertThat(language).isEqualTo(Language.EN); assertThat(diagnostics).hasSize(2); Either> lineLength = diagnostics.get("LineLength"); @@ -104,11 +107,12 @@ void createFromEmptyFile() { LanguageServerConfiguration configuration = LanguageServerConfiguration.create(configurationFile); // then - DiagnosticLanguage diagnosticLanguage = configuration.getDiagnosticLanguage(); - Map>> diagnostics = configuration.getDiagnostics(); + DiagnosticsOptions diagnosticsOptions = configuration.getDiagnosticsOptions(); + Language language = diagnosticsOptions.getLanguage(); + Map>> rules = diagnosticsOptions.getRules(); - assertThat(diagnosticLanguage).isEqualTo(DEFAULT_DIAGNOSTIC_LANGUAGE); - assertThat(diagnostics).isEmpty(); + assertThat(language).isEqualTo(DEFAULT_LANGUAGE); + assertThat(rules).isEmpty(); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java index c6f27e23d80..d6964ef00c4 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java @@ -21,8 +21,8 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; -import com.github._1c_syntax.bsl.languageserver.configuration.ComputeDiagnosticsSkipSupport; -import com.github._1c_syntax.bsl.languageserver.configuration.DiagnosticLanguage; +import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language; +import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.SkipSupport; import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.bsl.languageserver.context.FileType; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; @@ -236,7 +236,7 @@ void testSkipSupport() { var supportConfiguration = mock(SupportConfiguration.class); // when-then pairs ComputeDiagnosticsSkipSupport.NEVER - lsConfiguration.setComputeDiagnosticsSkipSupport(ComputeDiagnosticsSkipSupport.NEVER); + lsConfiguration.getDiagnosticsOptions().setSkipSupport(SkipSupport.NEVER); when(documentContext.getSupportVariants()).thenReturn(Collections.emptyMap()); assertThat(diagnosticSupplier.getDiagnosticInstances(documentContext)) .isNotEmpty(); @@ -258,7 +258,7 @@ void testSkipSupport() { .isNotEmpty(); // when-then pairs ComputeDiagnosticsSkipSupport.WITHSUPPORTLOCKED - lsConfiguration.setComputeDiagnosticsSkipSupport(ComputeDiagnosticsSkipSupport.WITH_SUPPORT_LOCKED); + lsConfiguration.getDiagnosticsOptions().setSkipSupport(SkipSupport.WITH_SUPPORT_LOCKED); when(documentContext.getSupportVariants()).thenReturn(Collections.emptyMap()); assertThat(diagnosticSupplier.getDiagnosticInstances(documentContext)) .isNotEmpty(); @@ -280,7 +280,7 @@ void testSkipSupport() { .isEmpty(); // when-then pairs ComputeDiagnosticsSkipSupport.WITHSUPPORT - lsConfiguration.setComputeDiagnosticsSkipSupport(ComputeDiagnosticsSkipSupport.WITH_SUPPORT); + lsConfiguration.getDiagnosticsOptions().setSkipSupport(SkipSupport.WITH_SUPPORT); when(documentContext.getSupportVariants()).thenReturn(Collections.emptyMap()); assertThat(diagnosticSupplier.getDiagnosticInstances(documentContext)) .isNotEmpty(); @@ -304,15 +304,15 @@ void testSkipSupport() { @Test void TestAllParametersHaveResourcesRU() { - allParametersHaveResources(DiagnosticLanguage.RU); + allParametersHaveResources(Language.RU); } @Test void TestAllParametersHaveResourcesEN() { - allParametersHaveResources(DiagnosticLanguage.EN); + allParametersHaveResources(com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language.EN); } - void allParametersHaveResources(DiagnosticLanguage language) { + void allParametersHaveResources(Language language) { // when List> diagnosticClasses = DiagnosticSupplier.getDiagnosticClasses(); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SmokyTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SmokyTest.java index f6b8fa41d04..0854e7f3ba1 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SmokyTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SmokyTest.java @@ -101,7 +101,7 @@ void testIAllDiagnostics() { // создадим новый конфиг, в котором включим все диагностики var configuration = LanguageServerConfiguration.create(); - configuration.setDiagnostics(diagnostics); + configuration.getDiagnosticsOptions().setRules(diagnostics); var diagnosticSupplier = new DiagnosticSupplier(configuration); // для каждой фикстуры расчитаем диагностики diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfoTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfoTest.java index d420c101df0..bffc629fb7c 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfoTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfoTest.java @@ -21,7 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics.metadata; -import com.github._1c_syntax.bsl.languageserver.configuration.DiagnosticLanguage; +import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language; import com.github._1c_syntax.bsl.languageserver.diagnostics.EmptyCodeBlockDiagnostic; import org.assertj.core.api.Assertions; import org.eclipse.lsp4j.jsonrpc.messages.Either; @@ -74,7 +74,7 @@ void testParameter() { @Test void testParameterEn() { - DiagnosticInfo diagnosticEnInfo = new DiagnosticInfo(EmptyCodeBlockDiagnostic.class, DiagnosticLanguage.EN); + DiagnosticInfo diagnosticEnInfo = new DiagnosticInfo(EmptyCodeBlockDiagnostic.class, Language.EN); assertThat(diagnosticEnInfo.getParameters().get(0).getDescription()) .isEqualTo("Comment as code"); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeActionProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeActionProviderTest.java index 243d03d179c..21fc4136fe0 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeActionProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeActionProviderTest.java @@ -62,7 +62,7 @@ void testGetCodeActions() throws IOException { DiagnosticProvider diagnosticProvider = new DiagnosticProvider(diagnosticSupplier); List diagnostics = diagnosticProvider.computeDiagnostics(documentContext).stream() .filter(diagnostic -> { - DiagnosticInfo diagnosticInfo = new DiagnosticInfo(CanonicalSpellingKeywordsDiagnostic.class, configuration.getDiagnosticLanguage()); + DiagnosticInfo diagnosticInfo = new DiagnosticInfo(CanonicalSpellingKeywordsDiagnostic.class, configuration.getDiagnosticsOptions().getLanguage()); DiagnosticCode diagnosticCode = diagnosticInfo.getCode(); return diagnostic.getCode().equals(diagnosticCode); }) diff --git a/src/test/resources/.bsl-language-server.json b/src/test/resources/.bsl-language-server.json index 3434bcb7ad7..6c4f92b2808 100644 --- a/src/test/resources/.bsl-language-server.json +++ b/src/test/resources/.bsl-language-server.json @@ -1,15 +1,19 @@ { - "diagnosticLanguage": "en", - "showCognitiveComplexityCodeLens": true, - "showCyclomaticComplexityCodeLens": true, - "computeDiagnosticsTrigger": "onType", - "computeDiagnosticsSkipSupport": "withSupportLocked", - "traceLog": "build/.trace.log", - "configurationRoot": "src/test/resources/metadata", + "codeLens": { + "showCognitiveComplexity": true, + "showCyclomaticComplexity": true + }, "diagnostics": { - "LineLength": { - "maxLineLength": 140 - }, - "MethodSize": false - } + "language": "en", + "computeTrigger": "onType", + "skipSupport": "withSupportLocked", + "rules": { + "LineLength": { + "maxLineLength": 140 + }, + "MethodSize": false + } + }, + "traceLog": "build/.trace.log", + "configurationRoot": "src/test/resources/metadata" } From 8111a3d8f1a1250e28079b125e2257780a432a4f Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Thu, 9 Apr 2020 22:11:58 +0300 Subject: [PATCH 097/444] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D0=BE=D1=82=D0=BE?= =?UTF-8?q?=D0=B2=D0=BA=D0=B0=20=D0=BF=D0=BE=D0=B4=20DiagnosticMode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../configuration/diagnostics/Mode.java | 30 +++++++++++++++++++ src/test/resources/.bsl-language-server.json | 1 + 2 files changed, 31 insertions(+) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java new file mode 100644 index 00000000000..8905050ce03 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java @@ -0,0 +1,30 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.configuration.diagnostics; + +public enum Mode { + OFF, + ON, + EXCEPT, + ONLY, + ALL +} diff --git a/src/test/resources/.bsl-language-server.json b/src/test/resources/.bsl-language-server.json index 6c4f92b2808..6d960a0dd56 100644 --- a/src/test/resources/.bsl-language-server.json +++ b/src/test/resources/.bsl-language-server.json @@ -7,6 +7,7 @@ "language": "en", "computeTrigger": "onType", "skipSupport": "withSupportLocked", + "mode": "only", "rules": { "LineLength": { "maxLineLength": 140 From 1e1dc318590a5369d6ca45e5e44e1a26a28b9f5a Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Thu, 9 Apr 2020 23:08:49 +0300 Subject: [PATCH 098/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=20=D1=83=D1=87=D0=B5=D1=82=20=D1=80=D0=B5=D0=B6?= =?UTF-8?q?=D0=B8=D0=BC=D0=B0=20=D0=B8=D1=81=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D1=8F=20=D0=B4=D0=B8=D0=B0=D0=B3?= =?UTF-8?q?=D0=BD=D0=BE=D1=81=D1=82=D0=B8=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/DiagnosticSupplier.java | 40 +++++-- .../diagnostics/DiagnosticSupplierTest.java | 103 +++++++++++++++++- 2 files changed, 134 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java index 60852b5d45d..dfd16450f1e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java @@ -21,6 +21,8 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.DiagnosticsOptions; +import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Mode; import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.SkipSupport; import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; @@ -68,9 +70,9 @@ public > Optional getDiagnosticInstances(DocumentContext documentContext) { - var configuredSkipSupport = configuration.getDiagnosticsOptions().getSkipSupport(); + DiagnosticsOptions diagnosticsOptions = configuration.getDiagnosticsOptions(); - if (needToComputeDiagnostics(documentContext, configuredSkipSupport)) { + if (needToComputeDiagnostics(documentContext, diagnosticsOptions)) { FileType fileType = documentContext.getFileType(); CompatibilityMode compatibilityMode = documentContext .getServerContext() @@ -80,7 +82,7 @@ public List getDiagnosticInstances(DocumentContext documentContex return diagnosticClasses.stream() .map(this::createDiagnosticInfo) - .filter(this::isEnabled) + .filter(diagnosticInfo -> isEnabled(diagnosticInfo, diagnosticsOptions)) .filter(info -> inScope(info, fileType)) .filter(info -> correctModuleType(info, moduleType, fileType)) .filter(info -> passedCompatibilityMode(info, compatibilityMode)) @@ -122,11 +124,16 @@ private void configureDiagnostic(BSLDiagnostic diagnostic) { } } - private boolean isEnabled(DiagnosticInfo diagnosticInfo) { + private boolean isEnabled(DiagnosticInfo diagnosticInfo, DiagnosticsOptions diagnosticsOptions) { if (diagnosticInfo == null) { return false; } + var mode = diagnosticsOptions.getMode(); + if (mode == Mode.OFF) { + return false; + } + Either> diagnosticConfiguration = configuration.getDiagnosticsOptions().getRules().get(diagnosticInfo.getCode().getStringValue()); @@ -135,10 +142,19 @@ private boolean isEnabled(DiagnosticInfo diagnosticInfo) { boolean enabledDirectly = diagnosticConfiguration != null && diagnosticConfiguration.isLeft() && diagnosticConfiguration.getLeft(); + boolean hasDefinedSetting = enabledDirectly || hasCustomConfiguration; + + boolean passedAllMode = mode == Mode.ALL; + boolean passedOnlyMode = mode == Mode.ONLY && hasDefinedSetting; + boolean passedExcept = mode == Mode.EXCEPT && !hasDefinedSetting; + boolean passedOn = mode == Mode.ON && (activatedByDefault || hasDefinedSetting); + + return passedOn + || passedAllMode + || passedOnlyMode + || passedExcept + ; - return activatedByDefault - || hasCustomConfiguration - || enabledDirectly; } private static boolean inScope(DiagnosticInfo diagnosticInfo, FileType fileType) { @@ -192,8 +208,16 @@ private static boolean passedCompatibilityMode( private static boolean needToComputeDiagnostics( DocumentContext documentContext, - SkipSupport configuredSkipSupport + DiagnosticsOptions diagnosticsOptions ) { + var configuredMode = diagnosticsOptions.getMode(); + + if (configuredMode == Mode.OFF) { + return false; + } + + var configuredSkipSupport = diagnosticsOptions.getSkipSupport(); + if (configuredSkipSupport == SkipSupport.NEVER) { return true; } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java index d6964ef00c4..6edb6586ad6 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java @@ -21,9 +21,10 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language; +import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Mode; import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.SkipSupport; -import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.bsl.languageserver.context.FileType; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; @@ -33,10 +34,12 @@ import com.github._1c_syntax.mdclasses.metadata.additional.CompatibilityMode; import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; import com.github._1c_syntax.mdclasses.metadata.additional.SupportVariant; +import org.eclipse.lsp4j.jsonrpc.messages.Either; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.MissingResourceException; @@ -307,6 +310,104 @@ void TestAllParametersHaveResourcesRU() { allParametersHaveResources(Language.RU); } + @Test + void testDiagnosticModeOff() { + // given + var lsConfiguration = LanguageServerConfiguration.create(); + var documentContext = TestUtils.getDocumentContext(""); + diagnosticSupplier = new DiagnosticSupplier(lsConfiguration); + + // when-then pairs + lsConfiguration.getDiagnosticsOptions().setMode(Mode.OFF); + List diagnostics = diagnosticSupplier.getDiagnosticInstances(documentContext); + + assertThat(diagnostics).isEmpty(); + } + + @Test + void testDiagnosticModeOn() { + // given + var lsConfiguration = LanguageServerConfiguration.create(); + var documentContext = TestUtils.getDocumentContext(""); + diagnosticSupplier = new DiagnosticSupplier(lsConfiguration); + + // when + lsConfiguration.getDiagnosticsOptions().setMode(Mode.ON); + List diagnostics = diagnosticSupplier.getDiagnosticInstances(documentContext); + + assertThat(diagnostics) + .hasSizeGreaterThan(10) + .flatExtracting(Object::getClass) + .doesNotContain(TooManyReturnsDiagnostic.class); + } + + @Test + void testDiagnosticModeAll() { + // given + var lsConfiguration = LanguageServerConfiguration.create(); + var documentContext = TestUtils.getDocumentContext(""); + diagnosticSupplier = new DiagnosticSupplier(lsConfiguration); + + // when + lsConfiguration.getDiagnosticsOptions().setMode(Mode.ALL); + List diagnostics = diagnosticSupplier.getDiagnosticInstances(documentContext); + + assertThat(diagnostics) + .hasSizeGreaterThan(10) + .flatExtracting(Object::getClass) + .contains(TooManyReturnsDiagnostic.class); + } + + @Test + void testDiagnosticModeOnly() { + // given + var lsConfiguration = LanguageServerConfiguration.create(); + var documentContext = TestUtils.getDocumentContext(""); + diagnosticSupplier = new DiagnosticSupplier(lsConfiguration); + + // when + lsConfiguration.getDiagnosticsOptions().setMode(Mode.ONLY); + Map>> rules = new HashMap<>(); + rules.put("Typo", Either.forLeft(true)); + rules.put("TooManyReturns", Either.forLeft(true)); + + lsConfiguration.getDiagnosticsOptions().setRules(rules); + List diagnostics = diagnosticSupplier.getDiagnosticInstances(documentContext); + + assertThat(diagnostics) + .hasSize(2) + .flatExtracting(Object::getClass) + .contains(TypoDiagnostic.class) + .contains(TooManyReturnsDiagnostic.class) + ; + } + + @Test + void testDiagnosticModeExcept() { + // given + var lsConfiguration = LanguageServerConfiguration.create(); + var documentContext = TestUtils.getDocumentContext(""); + diagnosticSupplier = new DiagnosticSupplier(lsConfiguration); + + // when + lsConfiguration.getDiagnosticsOptions().setMode(Mode.EXCEPT); + Map>> rules = new HashMap<>(); + rules.put("Typo", Either.forLeft(true)); + rules.put("TooManyReturns", Either.forLeft(true)); + + lsConfiguration.getDiagnosticsOptions().setRules(rules); + List diagnostics = diagnosticSupplier.getDiagnosticInstances(documentContext); + + assertThat(diagnostics) + .hasSizeGreaterThan(10) + .flatExtracting(Object::getClass) + .doesNotContain(TypoDiagnostic.class) + .doesNotContain(TooManyReturnsDiagnostic.class) + .contains(TernaryOperatorUsageDiagnostic.class) + .contains(EmptyRegionDiagnostic.class) + ; + } + @Test void TestAllParametersHaveResourcesEN() { allParametersHaveResources(com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language.EN); From b792b0952c3a1641227e0273f18d984829072bdb Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Thu, 9 Apr 2020 23:12:02 +0300 Subject: [PATCH 099/444] Fix QF --- .../databind/RulesDeserializer.java | 21 +++++++++++++++++++ .../reporter/GenericIssueReport.java | 4 +++- .../LanguageServerConfigurationTest.java | 2 +- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/RulesDeserializer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/RulesDeserializer.java index 3d2384ab800..b8b91412013 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/RulesDeserializer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/RulesDeserializer.java @@ -1,3 +1,24 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.configuration.diagnostics.databind; import com.fasterxml.jackson.core.JsonParser; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericIssueReport.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericIssueReport.java index 1d75e6d8957..4b44d12bbdf 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericIssueReport.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericIssueReport.java @@ -141,7 +141,9 @@ public GenericIssueEntry(String fileName, Diagnostic diagnostic) { Optional> diagnosticClass = diagnosticSupplier.getDiagnosticClass(diagnostic.getCode()); if (diagnosticClass.isPresent()) { - DiagnosticInfo info = new DiagnosticInfo(diagnosticClass.get(), configuration.getDiagnosticsOptions().getLanguage()); + DiagnosticInfo info = new DiagnosticInfo( + diagnosticClass.get(), configuration.getDiagnosticsOptions().getLanguage() + ); effortMinutes = info.getMinutesToFix(); } else { effortMinutes = 0; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java index 5dc538510b0..9375dc627cb 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java @@ -60,7 +60,7 @@ void createDefault() { LanguageServerConfiguration configuration = LanguageServerConfiguration.create(); // then - assertThat(configuration.getDiagnosticsOptions().getLanguage()).isEqualTo(com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language.RU); + assertThat(configuration.getDiagnosticsOptions().getLanguage()).isEqualTo(Language.RU); assertThat(configuration.getDiagnosticsOptions().getRules()).isEmpty(); } From 805fc51b91015f1f260e8fc6f5862ba20e3b20d1 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Sat, 11 Apr 2020 21:32:43 +0300 Subject: [PATCH 100/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20javadoc=20=D0=B4=D0=BB=D1=8F=20=D0=BF=D0=B0=D0=BA?= =?UTF-8?q?=D0=B5=D1=82=D0=B0=20configuration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../LanguageServerConfiguration.java | 13 +++++++-- .../codelens/CodeLensOptions.java | 3 ++ .../configuration/codelens/package-info.java | 26 +++++++++++++++++ .../diagnostics/ComputeTrigger.java | 14 ++++++++++ .../diagnostics/DiagnosticsOptions.java | 3 ++ .../configuration/diagnostics/Language.java | 20 +++++++++++++ .../configuration/diagnostics/Mode.java | 28 +++++++++++++++++++ .../diagnostics/SkipSupport.java | 14 ++++++++++ .../databind/RulesDeserializer.java | 6 ++++ .../diagnostics/package-info.java | 25 +++++++++++++++++ .../configuration/package-info.java | 9 ++++++ 11 files changed, 159 insertions(+), 2 deletions(-) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/package-info.java create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/package-info.java diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java index a57ee35516c..4c65916fd39 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java @@ -46,6 +46,12 @@ import static com.fasterxml.jackson.databind.MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS; +/** + * Корневой класс конфигурации BSL Language Server. + *

+ * В обычном режиме работы провайдеры и прочие классы могут расчитывать на единственность объекта конфигурации + * и безопасно сохранять ссылку на конфигурацию или ее части. + */ @Data @AllArgsConstructor(onConstructor = @__({@JsonCreator(mode = JsonCreator.Mode.DISABLED)})) @Slf4j @@ -55,11 +61,14 @@ public final class LanguageServerConfiguration { private static final Pattern searchConfiguration = Pattern.compile("Configuration\\.(xml|mdo)$"); @JsonProperty("diagnostics") - private DiagnosticsOptions diagnosticsOptions; + private final DiagnosticsOptions diagnosticsOptions; + @JsonProperty("codeLens") - private CodeLensOptions codeLensOptions; + private final CodeLensOptions codeLensOptions; + @Nullable private File traceLog; + @Nullable private Path configurationRoot; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/CodeLensOptions.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/CodeLensOptions.java index f1e718b527e..7b0eab8ee15 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/CodeLensOptions.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/CodeLensOptions.java @@ -26,6 +26,9 @@ import lombok.Data; import lombok.NoArgsConstructor; +/** + * Корневой класс для настройки {@link com.github._1c_syntax.bsl.languageserver.providers.CodeLensProvider} + */ @Data @AllArgsConstructor @NoArgsConstructor diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/package-info.java new file mode 100644 index 00000000000..8648ddebe11 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/package-info.java @@ -0,0 +1,26 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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. + */ + +/** + * Пакет содержит настройки {@link com.github._1c_syntax.bsl.languageserver.providers.CodeLensProvider} + */ +package com.github._1c_syntax.bsl.languageserver.configuration.codelens; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/ComputeTrigger.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/ComputeTrigger.java index ddd9171d145..10e1ab8f05e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/ComputeTrigger.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/ComputeTrigger.java @@ -21,8 +21,22 @@ */ package com.github._1c_syntax.bsl.languageserver.configuration.diagnostics; +/** + * Триггер для запуска процедуры расчета диагностик. + */ public enum ComputeTrigger { + /** + * При редактировании файла + */ ONTYPE, + + /** + * При сохранении файла + */ ONSAVE, + + /** + * Никогда + */ NEVER } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java index f33404b2c2f..8ff9defbde9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java @@ -32,6 +32,9 @@ import java.util.HashMap; import java.util.Map; +/** + * Корневой класс для настройки {@link com.github._1c_syntax.bsl.languageserver.providers.DiagnosticProvider} + */ @Data @AllArgsConstructor @NoArgsConstructor diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Language.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Language.java index 2cb62faa95f..23843bedad5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Language.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Language.java @@ -21,18 +21,38 @@ */ package com.github._1c_syntax.bsl.languageserver.configuration.diagnostics; +/** + * Язык для имен, сообщеий и прочих ресурсов диагностик. + */ public enum Language { + + /** + * Русский + */ RU("ru"), + + /** + * Английский + */ EN("en"); + /** + * Язык по умолчанию + */ public static final Language DEFAULT_LANGUAGE = RU; private final String languageCode; + /** + * @param languageCode код языка в соответствии с {@link java.util.Locale#getLanguage()} + */ Language(String languageCode) { this.languageCode = languageCode; } + /** + * @return код языка в соответствии с {@link java.util.Locale#getLanguage()} + */ public String getLanguageCode() { return languageCode; } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java index 8905050ce03..45658504dc5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java @@ -21,10 +21,38 @@ */ package com.github._1c_syntax.bsl.languageserver.configuration.diagnostics; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; + +/** + * Режим для учета настроек правил. + *

+ * См. {@link DiagnosticsOptions#getRules()} + */ public enum Mode { + + /** + * Все диагностики считаются выключенными. + */ OFF, + + /** + * Все диагностики, включенные по умолчанию ({@link DiagnosticMetadata#activatedByDefault()}, считаются включенными. + * Остальные - в соответствии с конфигурацией настроек правил. + */ ON, + + /** + * Все диагностики, кроме указанных в конфигурации настроек правил, считаются включенными. + */ EXCEPT, + + /** + * Только диагностики, указанные в конфигурации настроек правил, считаются включенными. + */ ONLY, + + /** + * Все диагностики считаются включенными. + */ ALL } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/SkipSupport.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/SkipSupport.java index 3ab9bed9c69..b4aeb02bbc8 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/SkipSupport.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/SkipSupport.java @@ -23,11 +23,25 @@ import com.fasterxml.jackson.annotation.JsonProperty; +/** + * Режим пропуска подсчета диагностик в зависимости от режима поддержки модуля + */ public enum SkipSupport { + /** + * Пропуск файлов на поддержке без возможности изменения. + */ @JsonProperty("withSupportLocked") WITH_SUPPORT_LOCKED, + + /** + * Пропуск файлов на поддержке без возможности изменения и с возможностью изменения с сохранением поддержки. + */ @JsonProperty("withSupport") WITH_SUPPORT, + + /** + * Никогда не пропускать файлы. + */ @JsonProperty("never") NEVER } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/RulesDeserializer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/RulesDeserializer.java index b8b91412013..32725eb8518 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/RulesDeserializer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/RulesDeserializer.java @@ -37,8 +37,14 @@ import java.util.Iterator; import java.util.Map; +/** + * Служебный класс-десериализатор для коллекции настроек диагностик. + *

+ * См. {@link com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.DiagnosticsOptions#getRules()} + */ @Slf4j public class RulesDeserializer extends JsonDeserializer>>> { + @Override public Map>> deserialize( JsonParser p, diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/package-info.java new file mode 100644 index 00000000000..551a8d4fb84 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/package-info.java @@ -0,0 +1,25 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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. + */ +/** + * Пакет содержит настройки для работы {@link com.github._1c_syntax.bsl.languageserver.providers.DiagnosticProvider} + */ +package com.github._1c_syntax.bsl.languageserver.configuration.diagnostics; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/package-info.java index 6073c9c265f..f1f647eb85c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/package-info.java @@ -19,4 +19,13 @@ * You should have received a copy of the GNU Lesser General Public * License along with BSL Language Server. */ + +/** + * В пакете содержатся классы для конфигурирования BSL Language Server. + *

+ * Корневой пакет содержит корневой класс конфигурации + * {@link com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration} + * , настройки верхнего уровня и дополнительные пакеты для настроек в разрезе провайдеров + * (диагностики, code lens, и т.д.) + */ package com.github._1c_syntax.bsl.languageserver.configuration; From bb6ccbd0004c21a9b2a8c7864f535d6d87d4318a Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Sat, 11 Apr 2020 21:55:18 +0300 Subject: [PATCH 101/444] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B3=D0=B5=D0=BD=D0=B5=D1=80=D0=B8?= =?UTF-8?q?=D0=BB=D0=BA=D0=B8=20json-=D1=81=D1=85=D0=B5=D0=BC=D1=8B=20?= =?UTF-8?q?=D0=BF=D0=BE=D0=B4=20=D0=BD=D0=BE=D0=B2=D1=83=D1=8E=20=D1=81?= =?UTF-8?q?=D1=82=D1=80=D1=83=D0=BA=D1=82=D1=83=D1=80=D1=83=20=D0=BA=D0=BB?= =?UTF-8?q?=D0=B0=D1=81=D1=81=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gradle/developer-tools.gradle.kts | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/gradle/developer-tools.gradle.kts b/gradle/developer-tools.gradle.kts index ce9e392a296..b8e116cde21 100644 --- a/gradle/developer-tools.gradle.kts +++ b/gradle/developer-tools.gradle.kts @@ -55,11 +55,21 @@ open class DeveloperTools @javax.inject.Inject constructor(objects: ObjectFactor private fun createDiagnosticSupplier(lang: String, classLoader: ClassLoader) : Any { val languageServerConfigurationClass = classLoader.loadClass("com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration") - val diagnosticLanguageClass = classLoader.loadClass("com.github._1c_syntax.bsl.languageserver.configuration.DiagnosticLanguage") - val lsConfiguration = languageServerConfigurationClass.getDeclaredMethod("create", diagnosticLanguageClass) - .invoke(languageServerConfigurationClass, - diagnosticLanguageClass.getMethod("valueOf", classLoader.loadClass("java.lang.String")) - .invoke(diagnosticLanguageClass, lang.toUpperCase())) + val diagnosticsOptionsClass = classLoader.loadClass("com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.DiagnosticsOptions") + val languageClass = classLoader.loadClass("com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language") + + val lsConfiguration = languageServerConfigurationClass + .getDeclaredMethod("create") + .invoke(languageServerConfigurationClass) + val language = languageClass.getMethod("valueOf", classLoader.loadClass("java.lang.String")) + .invoke(languageClass, lang.toUpperCase()) + val diagnosticOptions = languageServerConfigurationClass + .getDeclaredMethod("getDiagnosticsOptions") + .invoke(lsConfiguration) + + diagnosticsOptionsClass.getDeclaredMethod("setLanguage", languageClass) + .invoke(diagnosticOptions, language) + return classLoader.loadClass("com.github._1c_syntax.bsl.languageserver.diagnostics.DiagnosticSupplier").declaredConstructors[0].newInstance(lsConfiguration) } From 185293cf6fd07a863a66919a0fdd09140a81f12a Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Mon, 13 Apr 2020 11:27:24 +0300 Subject: [PATCH 102/444] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=BD=D0=BE?= =?UTF-8?q?=D1=81=20language=20=D0=B8=D0=B7=20DiagnosticOptions=20=D0=B2?= =?UTF-8?q?=20=D0=BE=D1=81=D0=BD=D0=BE=D0=B2=D0=BD=D0=BE=D0=B9=20=D0=BA?= =?UTF-8?q?=D0=BE=D0=BD=D1=84=D0=B8=D0=B3=20bsl=20ls?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Language перестал быть только языком диагностик - он используется для квик-фиксов, возможно скоро начнет использоваться и в codelens. Теперь это общий язык для взаимодействия бсл лс с пользователем --- gradle/developer-tools.gradle.kts | 10 +++------- .../configuration/{diagnostics => }/Language.java | 5 +++-- .../configuration/LanguageServerConfiguration.java | 3 +++ .../configuration/diagnostics/DiagnosticsOptions.java | 1 - .../languageserver/diagnostics/DiagnosticSupplier.java | 4 ++-- .../diagnostics/metadata/DiagnosticInfo.java | 4 ++-- .../diagnostics/reporter/GenericIssueReport.java | 2 +- .../configuration/LanguageServerConfigurationTest.java | 9 ++++----- .../diagnostics/DiagnosticSupplierTest.java | 4 ++-- .../diagnostics/metadata/DiagnosticInfoTest.java | 2 +- .../providers/CodeActionProviderTest.java | 5 ++++- src/test/resources/.bsl-language-server.json | 2 +- 12 files changed, 26 insertions(+), 25 deletions(-) rename src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/{diagnostics => }/Language.java (86%) diff --git a/gradle/developer-tools.gradle.kts b/gradle/developer-tools.gradle.kts index b8e116cde21..9edc83a1fec 100644 --- a/gradle/developer-tools.gradle.kts +++ b/gradle/developer-tools.gradle.kts @@ -55,20 +55,16 @@ open class DeveloperTools @javax.inject.Inject constructor(objects: ObjectFactor private fun createDiagnosticSupplier(lang: String, classLoader: ClassLoader) : Any { val languageServerConfigurationClass = classLoader.loadClass("com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration") - val diagnosticsOptionsClass = classLoader.loadClass("com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.DiagnosticsOptions") - val languageClass = classLoader.loadClass("com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language") + val languageClass = classLoader.loadClass("com.github._1c_syntax.bsl.languageserver.configuration.Language") val lsConfiguration = languageServerConfigurationClass .getDeclaredMethod("create") .invoke(languageServerConfigurationClass) val language = languageClass.getMethod("valueOf", classLoader.loadClass("java.lang.String")) .invoke(languageClass, lang.toUpperCase()) - val diagnosticOptions = languageServerConfigurationClass - .getDeclaredMethod("getDiagnosticsOptions") - .invoke(lsConfiguration) - diagnosticsOptionsClass.getDeclaredMethod("setLanguage", languageClass) - .invoke(diagnosticOptions, language) + languageServerConfigurationClass.getDeclaredMethod("setLanguage", languageClass) + .invoke(lsConfiguration, language) return classLoader.loadClass("com.github._1c_syntax.bsl.languageserver.diagnostics.DiagnosticSupplier").declaredConstructors[0].newInstance(lsConfiguration) } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Language.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/Language.java similarity index 86% rename from src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Language.java rename to src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/Language.java index 23843bedad5..fea03dbdaee 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Language.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/Language.java @@ -19,10 +19,11 @@ * 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.configuration.diagnostics; +package com.github._1c_syntax.bsl.languageserver.configuration; /** - * Язык для имен, сообщеий и прочих ресурсов диагностик. + * Язык для сообщений, ресурсов и прочих взаимододействий между + * BSL Language Server и пользователем. */ public enum Language { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java index 4c65916fd39..ca9aa5ee0d8 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java @@ -60,6 +60,8 @@ public final class LanguageServerConfiguration { private static final Pattern searchConfiguration = Pattern.compile("Configuration\\.(xml|mdo)$"); + private Language language; + @JsonProperty("diagnostics") private final DiagnosticsOptions diagnosticsOptions; @@ -74,6 +76,7 @@ public final class LanguageServerConfiguration { private LanguageServerConfiguration() { this( + Language.DEFAULT_LANGUAGE, new DiagnosticsOptions(), new CodeLensOptions(), null, diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java index 8ff9defbde9..3f53dec9e38 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java @@ -40,7 +40,6 @@ @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class DiagnosticsOptions { - private Language language = Language.RU; private ComputeTrigger computeTrigger = ComputeTrigger.ONSAVE; private SkipSupport skipSupport = SkipSupport.NEVER; private Mode mode = Mode.ON; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java index dfd16450f1e..5413ca5e49f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java @@ -96,7 +96,7 @@ public List getDiagnosticInstances(DocumentContext documentContex } public BSLDiagnostic getDiagnosticInstance(Class diagnosticClass) { - DiagnosticInfo info = new DiagnosticInfo(diagnosticClass, configuration.getDiagnosticsOptions().getLanguage()); + DiagnosticInfo info = new DiagnosticInfo(diagnosticClass, configuration.getLanguage()); BSLDiagnostic diagnosticInstance = createDiagnosticInstance(info); configureDiagnostic(diagnosticInstance); @@ -112,7 +112,7 @@ private BSLDiagnostic createDiagnosticInstance(DiagnosticInfo diagnosticInfo) { } private DiagnosticInfo createDiagnosticInfo(Class diagnosticClass) { - return new DiagnosticInfo(diagnosticClass, configuration.getDiagnosticsOptions().getLanguage()); + return new DiagnosticInfo(diagnosticClass, configuration.getLanguage()); } private void configureDiagnostic(BSLDiagnostic diagnostic) { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java index f2abcdb78d9..5e9ecbe2977 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java @@ -21,7 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics.metadata; -import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language; +import com.github._1c_syntax.bsl.languageserver.configuration.Language; import com.github._1c_syntax.bsl.languageserver.diagnostics.BSLDiagnostic; import com.github._1c_syntax.bsl.languageserver.utils.UTF8Control; import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; @@ -41,7 +41,7 @@ import java.util.ResourceBundle; import java.util.stream.Collectors; -import static com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language.DEFAULT_LANGUAGE; +import static com.github._1c_syntax.bsl.languageserver.configuration.Language.DEFAULT_LANGUAGE; @Slf4j public class DiagnosticInfo { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericIssueReport.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericIssueReport.java index 4b44d12bbdf..d842176d88f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericIssueReport.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericIssueReport.java @@ -142,7 +142,7 @@ public GenericIssueEntry(String fileName, Diagnostic diagnostic) { diagnosticSupplier.getDiagnosticClass(diagnostic.getCode()); if (diagnosticClass.isPresent()) { DiagnosticInfo info = new DiagnosticInfo( - diagnosticClass.get(), configuration.getDiagnosticsOptions().getLanguage() + diagnosticClass.get(), configuration.getLanguage() ); effortMinutes = info.getMinutesToFix(); } else { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java index 9375dc627cb..c353f518c58 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java @@ -22,7 +22,6 @@ package com.github._1c_syntax.bsl.languageserver.configuration; import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.DiagnosticsOptions; -import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language; import com.github._1c_syntax.utils.Absolute; import org.eclipse.lsp4j.jsonrpc.messages.Either; import org.junit.jupiter.api.BeforeEach; @@ -36,7 +35,7 @@ import java.nio.file.Paths; import java.util.Map; -import static com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language.DEFAULT_LANGUAGE; +import static com.github._1c_syntax.bsl.languageserver.configuration.Language.DEFAULT_LANGUAGE; import static org.assertj.core.api.Assertions.assertThat; class LanguageServerConfigurationTest { @@ -60,7 +59,7 @@ void createDefault() { LanguageServerConfiguration configuration = LanguageServerConfiguration.create(); // then - assertThat(configuration.getDiagnosticsOptions().getLanguage()).isEqualTo(Language.RU); + assertThat(configuration.getLanguage()).isEqualTo(Language.RU); assertThat(configuration.getDiagnosticsOptions().getRules()).isEmpty(); } @@ -75,7 +74,7 @@ void createFromFile() { // then DiagnosticsOptions diagnosticsOptions = configuration.getDiagnosticsOptions(); - Language language = diagnosticsOptions.getLanguage(); + Language language = configuration.getLanguage(); Map>> diagnostics = diagnosticsOptions.getRules(); assertThat(language).isEqualTo(Language.EN); @@ -108,7 +107,7 @@ void createFromEmptyFile() { // then DiagnosticsOptions diagnosticsOptions = configuration.getDiagnosticsOptions(); - Language language = diagnosticsOptions.getLanguage(); + Language language = configuration.getLanguage(); Map>> rules = diagnosticsOptions.getRules(); assertThat(language).isEqualTo(DEFAULT_LANGUAGE); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java index 6edb6586ad6..4d0c6802d28 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java @@ -22,7 +22,7 @@ package com.github._1c_syntax.bsl.languageserver.diagnostics; import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; -import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language; +import com.github._1c_syntax.bsl.languageserver.configuration.Language; import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Mode; import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.SkipSupport; import com.github._1c_syntax.bsl.languageserver.context.FileType; @@ -410,7 +410,7 @@ void testDiagnosticModeExcept() { @Test void TestAllParametersHaveResourcesEN() { - allParametersHaveResources(com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language.EN); + allParametersHaveResources(Language.EN); } void allParametersHaveResources(Language language) { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfoTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfoTest.java index bffc629fb7c..e2d4f0895bc 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfoTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfoTest.java @@ -21,7 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics.metadata; -import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Language; +import com.github._1c_syntax.bsl.languageserver.configuration.Language; import com.github._1c_syntax.bsl.languageserver.diagnostics.EmptyCodeBlockDiagnostic; import org.assertj.core.api.Assertions; import org.eclipse.lsp4j.jsonrpc.messages.Either; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeActionProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeActionProviderTest.java index 21fc4136fe0..e7a2a864830 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeActionProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeActionProviderTest.java @@ -62,7 +62,10 @@ void testGetCodeActions() throws IOException { DiagnosticProvider diagnosticProvider = new DiagnosticProvider(diagnosticSupplier); List diagnostics = diagnosticProvider.computeDiagnostics(documentContext).stream() .filter(diagnostic -> { - DiagnosticInfo diagnosticInfo = new DiagnosticInfo(CanonicalSpellingKeywordsDiagnostic.class, configuration.getDiagnosticsOptions().getLanguage()); + DiagnosticInfo diagnosticInfo = new DiagnosticInfo( + CanonicalSpellingKeywordsDiagnostic.class, + configuration.getLanguage() + ); DiagnosticCode diagnosticCode = diagnosticInfo.getCode(); return diagnostic.getCode().equals(diagnosticCode); }) diff --git a/src/test/resources/.bsl-language-server.json b/src/test/resources/.bsl-language-server.json index 6d960a0dd56..fb1ecdff4a6 100644 --- a/src/test/resources/.bsl-language-server.json +++ b/src/test/resources/.bsl-language-server.json @@ -1,10 +1,10 @@ { + "language": "en", "codeLens": { "showCognitiveComplexity": true, "showCyclomaticComplexity": true }, "diagnostics": { - "language": "en", "computeTrigger": "onType", "skipSupport": "withSupportLocked", "mode": "only", From bee702e8f8ba786d7e770403039c479b45d3fe0e Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Mon, 13 Apr 2020 12:30:11 +0300 Subject: [PATCH 103/444] rules -> parameters --- .../diagnostics/DiagnosticsOptions.java | 6 +++--- .../configuration/diagnostics/Mode.java | 2 +- ...serializer.java => ParametersDeserializer.java} | 4 ++-- .../diagnostics/DiagnosticSupplier.java | 4 ++-- .../LanguageServerConfigurationTest.java | 14 +++++++------- .../diagnostics/DiagnosticSupplierTest.java | 4 ++-- .../bsl/languageserver/diagnostics/SmokyTest.java | 2 +- src/test/resources/.bsl-language-server.json | 2 +- 8 files changed, 19 insertions(+), 19 deletions(-) rename src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/{RulesDeserializer.java => ParametersDeserializer.java} (95%) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java index 3f53dec9e38..2cbee0dde56 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java @@ -23,7 +23,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.databind.RulesDeserializer; +import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.databind.ParametersDeserializer; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -44,6 +44,6 @@ public class DiagnosticsOptions { private SkipSupport skipSupport = SkipSupport.NEVER; private Mode mode = Mode.ON; - @JsonDeserialize(using = RulesDeserializer.class) - private Map>> rules = new HashMap<>(); + @JsonDeserialize(using = ParametersDeserializer.class) + private Map>> parameters = new HashMap<>(); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java index 45658504dc5..7e2ab869aea 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java @@ -26,7 +26,7 @@ /** * Режим для учета настроек правил. *

- * См. {@link DiagnosticsOptions#getRules()} + * См. {@link DiagnosticsOptions#getParameters()} */ public enum Mode { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/RulesDeserializer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/ParametersDeserializer.java similarity index 95% rename from src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/RulesDeserializer.java rename to src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/ParametersDeserializer.java index 32725eb8518..1ff23ece5a7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/RulesDeserializer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/databind/ParametersDeserializer.java @@ -40,10 +40,10 @@ /** * Служебный класс-десериализатор для коллекции настроек диагностик. *

- * См. {@link com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.DiagnosticsOptions#getRules()} + * См. {@link com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.DiagnosticsOptions#getParameters()} */ @Slf4j -public class RulesDeserializer extends JsonDeserializer>>> { +public class ParametersDeserializer extends JsonDeserializer>>> { @Override public Map>> deserialize( diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java index 5413ca5e49f..02058ea6ce1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java @@ -117,7 +117,7 @@ private DiagnosticInfo createDiagnosticInfo(Class diagn private void configureDiagnostic(BSLDiagnostic diagnostic) { Either> diagnosticConfiguration = - configuration.getDiagnosticsOptions().getRules().get(diagnostic.getInfo().getCode().getStringValue()); + configuration.getDiagnosticsOptions().getParameters().get(diagnostic.getInfo().getCode().getStringValue()); if (diagnosticConfiguration != null && diagnosticConfiguration.isRight()) { diagnostic.configure(diagnosticConfiguration.getRight()); @@ -135,7 +135,7 @@ private boolean isEnabled(DiagnosticInfo diagnosticInfo, DiagnosticsOptions diag } Either> diagnosticConfiguration = - configuration.getDiagnosticsOptions().getRules().get(diagnosticInfo.getCode().getStringValue()); + configuration.getDiagnosticsOptions().getParameters().get(diagnosticInfo.getCode().getStringValue()); boolean activatedByDefault = diagnosticConfiguration == null && diagnosticInfo.isActivatedByDefault(); boolean hasCustomConfiguration = diagnosticConfiguration != null && diagnosticConfiguration.isRight(); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java index c353f518c58..b903401b556 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java @@ -60,7 +60,7 @@ void createDefault() { // then assertThat(configuration.getLanguage()).isEqualTo(Language.RU); - assertThat(configuration.getDiagnosticsOptions().getRules()).isEmpty(); + assertThat(configuration.getDiagnosticsOptions().getParameters()).isEmpty(); } @Test @@ -75,19 +75,19 @@ void createFromFile() { // then DiagnosticsOptions diagnosticsOptions = configuration.getDiagnosticsOptions(); Language language = configuration.getLanguage(); - Map>> diagnostics = diagnosticsOptions.getRules(); + Map>> parameters = diagnosticsOptions.getParameters(); assertThat(language).isEqualTo(Language.EN); - assertThat(diagnostics).hasSize(2); + assertThat(parameters).hasSize(2); - Either> lineLength = diagnostics.get("LineLength"); + Either> lineLength = parameters.get("LineLength"); assertThat(lineLength.isRight()).isTrue(); assertThat(lineLength.getRight()).isInstanceOfAny(Map.class); assertThat(lineLength.getRight()) .extracting(stringObjectMap -> stringObjectMap.get("maxLineLength")) .isEqualTo(140); - Either> methodSize = diagnostics.get("MethodSize"); + Either> methodSize = parameters.get("MethodSize"); assertThat(methodSize.isLeft()).isTrue(); assertThat(methodSize.getLeft()).isEqualTo(false); @@ -108,10 +108,10 @@ void createFromEmptyFile() { // then DiagnosticsOptions diagnosticsOptions = configuration.getDiagnosticsOptions(); Language language = configuration.getLanguage(); - Map>> rules = diagnosticsOptions.getRules(); + Map>> parameters = diagnosticsOptions.getParameters(); assertThat(language).isEqualTo(DEFAULT_LANGUAGE); - assertThat(rules).isEmpty(); + assertThat(parameters).isEmpty(); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java index 4d0c6802d28..ab3dc740032 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java @@ -371,7 +371,7 @@ void testDiagnosticModeOnly() { rules.put("Typo", Either.forLeft(true)); rules.put("TooManyReturns", Either.forLeft(true)); - lsConfiguration.getDiagnosticsOptions().setRules(rules); + lsConfiguration.getDiagnosticsOptions().setParameters(rules); List diagnostics = diagnosticSupplier.getDiagnosticInstances(documentContext); assertThat(diagnostics) @@ -395,7 +395,7 @@ void testDiagnosticModeExcept() { rules.put("Typo", Either.forLeft(true)); rules.put("TooManyReturns", Either.forLeft(true)); - lsConfiguration.getDiagnosticsOptions().setRules(rules); + lsConfiguration.getDiagnosticsOptions().setParameters(rules); List diagnostics = diagnosticSupplier.getDiagnosticInstances(documentContext); assertThat(diagnostics) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SmokyTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SmokyTest.java index 0854e7f3ba1..d819c29cbfe 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SmokyTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SmokyTest.java @@ -101,7 +101,7 @@ void testIAllDiagnostics() { // создадим новый конфиг, в котором включим все диагностики var configuration = LanguageServerConfiguration.create(); - configuration.getDiagnosticsOptions().setRules(diagnostics); + configuration.getDiagnosticsOptions().setParameters(diagnostics); var diagnosticSupplier = new DiagnosticSupplier(configuration); // для каждой фикстуры расчитаем диагностики diff --git a/src/test/resources/.bsl-language-server.json b/src/test/resources/.bsl-language-server.json index fb1ecdff4a6..b06e9d59b29 100644 --- a/src/test/resources/.bsl-language-server.json +++ b/src/test/resources/.bsl-language-server.json @@ -8,7 +8,7 @@ "computeTrigger": "onType", "skipSupport": "withSupportLocked", "mode": "only", - "rules": { + "parameters": { "LineLength": { "maxLineLength": 140 }, From c72c26cee6c6bfd7de59b2911324b3311b055935 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Mon, 13 Apr 2020 22:38:59 +0300 Subject: [PATCH 104/444] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20json-schema?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...ics-schema.json => parameters-schema.json} | 4 +- .../languageserver/configuration/schema.json | 400 ++++++++++-------- 2 files changed, 229 insertions(+), 175 deletions(-) rename src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/{diagnostics-schema.json => parameters-schema.json} (99%) diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json similarity index 99% rename from src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json rename to src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index eaebb43623e..1820ff1f817 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -1,8 +1,8 @@ { "$schema": "http://json-schema.org/draft-07/schema", - "$id": "http://example.com/root.json", + "$id": "https://1c-syntax.github.io/bsl-language-server/configuration/parameters-schema.json", "type": "object", - "title": "BSL Language Server Configuration File. Diagnostic definition part", + "title": "BSL Language Server Configuration File. Parameters definition part", "definitions": { "BeginTransactionBeforeTryCatch": { "description": "Violating transaction rules for the 'BeginTransaction' method", diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 6123c084a4b..4f1a26da95a 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -1,383 +1,437 @@ { "$schema": "http://json-schema.org/draft-07/schema", - "$id": "http://example.com/root.json", + "$id": "https://1c-syntax.github.io/bsl-language-server/configuration/schema.json", "type": "object", "title": "BSL Language Server Configuration File.", + "additionalItems": false, "definitions": { - "Diagnostic": { - "$id": "#/definitions/Diagnostic", + "parameter": { + "$id": "#/definitions/parameter", "type": [ "boolean", "object" ], - "title": "Concrete diagnostic configuration.\nCan be boolean for turning on/off or object.", + "title": "Concrete diagnostic parameters' configuration.\nCan be boolean for turning on/off or object.", "default": true - } - }, - "properties": { - "diagnosticLanguage": { - "$id": "#/properties/diagnosticLanguage", - "type": "string", - "oneOf": [ - { - "const": "en", - "description": "English" - }, - { - "const": "ru", - "description": "\u0420\u0443\u0441\u0441\u043a\u0438\u0439 (russian)" - } - ], - "title": "Diagnostics text language.", - "default": "ru" - }, - "showCognitiveComplexityCodeLens": { - "$id": "#/properties/showCognitiveComplexityCodeLens", - "type": "boolean", - "title": "Show cognitive complexity score above method definition (codeLens).", - "default": true - }, - "showCyclomaticComplexityCodeLens": { - "$id": "#/properties/showCyclomaticComplexityCodeLens", - "type": "boolean", - "title": "Show cyclomatic complexity score above method definition (codeLens).", - "default": true - }, - "computeDiagnosticsTrigger": { - "$id": "#/properties/computeDiagnosticsTrigger", - "type": "string", - "oneOf": [ - { - "const": "onSave", - "description": "Compute on save" - }, - { - "const": "onType", - "description": "Compute on type (edit file)" - }, - { - "const": "never", - "description": "Never compute" - } - ], - "title": "Trigger for the computation of diagnostics.", - "default": "onSave" - }, - "computeDiagnosticsSkipSupport": { - "$id": "#/properties/computeDiagnosticsSkipSupport", - "type": "string", - "oneOf": [ - { - "const": "withSupport", - "description": "Skip computing diagnostics on modules with any kind of support." - }, - { - "const": "withSupportLocked", - "description": "Skip computing diagnostics on modules with `not editable` support mode." - }, - { - "const": "never", - "description": "Never skip computing." - } - ], - "title": "Analyze module support variant and skip all diagnostics if necessary.", - "default": "never" - }, - "traceLog": { - "$id": "#/properties/traceLog", - "type": "string", - "title": "Path to file to log all inbound and outbound requests between BSL Language Server and Language Client from used IDE.\nCan be absolute or relative (to the project root). If set *significantly slows down* communication speed between server and client.", - "default": "", - "examples": [ - ".trace.log" - ] }, - "diagnostics": { - "$id": "#/properties/diagnostics", + "parameters": { + "$id": "#/definitions/parameters", "type": "object", - "title": "Diagnostics configuration.\nKey-value object, where key is a diagnosticCode, and value is boolean or object with concrete diagnostic configuration.", + "title": "Diagnostics parameters configuration.\nKey-value object, where key is a diagnosticCode, and value is boolean or object with concrete diagnostic configuration.", "default": null, "additionalProperties": { - "$ref": "#/definitions/Diagnostic" + "$ref": "#/definitions/parameter" }, "properties": { "BeginTransactionBeforeTryCatch": { - "$ref": "diagnostics-schema.json#/definitions/BeginTransactionBeforeTryCatch" + "$ref": "parameters-schema.json#/definitions/BeginTransactionBeforeTryCatch" }, "CanonicalSpellingKeywords": { - "$ref": "diagnostics-schema.json#/definitions/CanonicalSpellingKeywords" + "$ref": "parameters-schema.json#/definitions/CanonicalSpellingKeywords" }, "CodeBlockBeforeSub": { - "$ref": "diagnostics-schema.json#/definitions/CodeBlockBeforeSub" + "$ref": "parameters-schema.json#/definitions/CodeBlockBeforeSub" }, "CodeOutOfRegion": { - "$ref": "diagnostics-schema.json#/definitions/CodeOutOfRegion" + "$ref": "parameters-schema.json#/definitions/CodeOutOfRegion" }, "CognitiveComplexity": { - "$ref": "diagnostics-schema.json#/definitions/CognitiveComplexity" + "$ref": "parameters-schema.json#/definitions/CognitiveComplexity" }, "CommentedCode": { - "$ref": "diagnostics-schema.json#/definitions/CommentedCode" + "$ref": "parameters-schema.json#/definitions/CommentedCode" }, "CommitTransactionOutsideTryCatch": { - "$ref": "diagnostics-schema.json#/definitions/CommitTransactionOutsideTryCatch" + "$ref": "parameters-schema.json#/definitions/CommitTransactionOutsideTryCatch" }, "CommonModuleAssign": { "$ref": "diagnostics-schema.json#/definitions/CommonModuleAssign" }, "CompilationDirectiveLost": { - "$ref": "diagnostics-schema.json#/definitions/CompilationDirectiveLost" + "$ref": "parameters-schema.json#/definitions/CompilationDirectiveLost" }, "CompilationDirectiveNeedLess": { - "$ref": "diagnostics-schema.json#/definitions/CompilationDirectiveNeedLess" + "$ref": "parameters-schema.json#/definitions/CompilationDirectiveNeedLess" }, "ConsecutiveEmptyLines": { "$ref": "diagnostics-schema.json#/definitions/ConsecutiveEmptyLines" }, "CreateQueryInCycle": { - "$ref": "diagnostics-schema.json#/definitions/CreateQueryInCycle" + "$ref": "parameters-schema.json#/definitions/CreateQueryInCycle" }, "CyclomaticComplexity": { - "$ref": "diagnostics-schema.json#/definitions/CyclomaticComplexity" + "$ref": "parameters-schema.json#/definitions/CyclomaticComplexity" }, "DataExchangeLoading": { "$ref": "diagnostics-schema.json#/definitions/DataExchangeLoading" }, "DeletingCollectionItem": { - "$ref": "diagnostics-schema.json#/definitions/DeletingCollectionItem" + "$ref": "parameters-schema.json#/definitions/DeletingCollectionItem" }, "DeprecatedCurrentDate": { - "$ref": "diagnostics-schema.json#/definitions/DeprecatedCurrentDate" + "$ref": "parameters-schema.json#/definitions/DeprecatedCurrentDate" }, "DeprecatedFind": { - "$ref": "diagnostics-schema.json#/definitions/DeprecatedFind" + "$ref": "parameters-schema.json#/definitions/DeprecatedFind" }, "DeprecatedMessage": { - "$ref": "diagnostics-schema.json#/definitions/DeprecatedMessage" + "$ref": "parameters-schema.json#/definitions/DeprecatedMessage" }, "DeprecatedTypeManagedForm": { - "$ref": "diagnostics-schema.json#/definitions/DeprecatedTypeManagedForm" + "$ref": "parameters-schema.json#/definitions/DeprecatedTypeManagedForm" }, "DuplicateRegion": { - "$ref": "diagnostics-schema.json#/definitions/DuplicateRegion" + "$ref": "parameters-schema.json#/definitions/DuplicateRegion" }, "EmptyCodeBlock": { - "$ref": "diagnostics-schema.json#/definitions/EmptyCodeBlock" + "$ref": "parameters-schema.json#/definitions/EmptyCodeBlock" }, "EmptyRegion": { - "$ref": "diagnostics-schema.json#/definitions/EmptyRegion" + "$ref": "parameters-schema.json#/definitions/EmptyRegion" }, "EmptyStatement": { - "$ref": "diagnostics-schema.json#/definitions/EmptyStatement" + "$ref": "parameters-schema.json#/definitions/EmptyStatement" }, "ExcessiveAutoTestCheck": { "$ref": "diagnostics-schema.json#/definitions/ExcessiveAutoTestCheck" }, "ExtraCommas": { - "$ref": "diagnostics-schema.json#/definitions/ExtraCommas" + "$ref": "parameters-schema.json#/definitions/ExtraCommas" }, "FormDataToValue": { - "$ref": "diagnostics-schema.json#/definitions/FormDataToValue" + "$ref": "parameters-schema.json#/definitions/FormDataToValue" }, "FunctionNameStartsWithGet": { - "$ref": "diagnostics-schema.json#/definitions/FunctionNameStartsWithGet" + "$ref": "parameters-schema.json#/definitions/FunctionNameStartsWithGet" }, "FunctionShouldHaveReturn": { - "$ref": "diagnostics-schema.json#/definitions/FunctionShouldHaveReturn" + "$ref": "parameters-schema.json#/definitions/FunctionShouldHaveReturn" }, "GetFormMethod": { - "$ref": "diagnostics-schema.json#/definitions/GetFormMethod" + "$ref": "parameters-schema.json#/definitions/GetFormMethod" }, "IdenticalExpressions": { - "$ref": "diagnostics-schema.json#/definitions/IdenticalExpressions" + "$ref": "parameters-schema.json#/definitions/IdenticalExpressions" }, "IfConditionComplexity": { - "$ref": "diagnostics-schema.json#/definitions/IfConditionComplexity" + "$ref": "parameters-schema.json#/definitions/IfConditionComplexity" }, "IfElseDuplicatedCodeBlock": { - "$ref": "diagnostics-schema.json#/definitions/IfElseDuplicatedCodeBlock" + "$ref": "parameters-schema.json#/definitions/IfElseDuplicatedCodeBlock" }, "IfElseDuplicatedCondition": { - "$ref": "diagnostics-schema.json#/definitions/IfElseDuplicatedCondition" + "$ref": "parameters-schema.json#/definitions/IfElseDuplicatedCondition" }, "IfElseIfEndsWithElse": { - "$ref": "diagnostics-schema.json#/definitions/IfElseIfEndsWithElse" + "$ref": "parameters-schema.json#/definitions/IfElseIfEndsWithElse" }, "InvalidCharacterInFile": { - "$ref": "diagnostics-schema.json#/definitions/InvalidCharacterInFile" + "$ref": "parameters-schema.json#/definitions/InvalidCharacterInFile" }, "LineLength": { - "$ref": "diagnostics-schema.json#/definitions/LineLength" + "$ref": "parameters-schema.json#/definitions/LineLength" }, "MagicNumber": { - "$ref": "diagnostics-schema.json#/definitions/MagicNumber" + "$ref": "parameters-schema.json#/definitions/MagicNumber" }, "MethodSize": { - "$ref": "diagnostics-schema.json#/definitions/MethodSize" + "$ref": "parameters-schema.json#/definitions/MethodSize" }, "MissingCodeTryCatchEx": { - "$ref": "diagnostics-schema.json#/definitions/MissingCodeTryCatchEx" + "$ref": "parameters-schema.json#/definitions/MissingCodeTryCatchEx" }, "MissingSpace": { - "$ref": "diagnostics-schema.json#/definitions/MissingSpace" + "$ref": "parameters-schema.json#/definitions/MissingSpace" }, "MissingTemporaryFileDeletion": { - "$ref": "diagnostics-schema.json#/definitions/MissingTemporaryFileDeletion" + "$ref": "parameters-schema.json#/definitions/MissingTemporaryFileDeletion" }, "MissingVariablesDescription": { "$ref": "diagnostics-schema.json#/definitions/MissingVariablesDescription" }, "MultilingualStringHasAllDeclaredLanguages": { - "$ref": "diagnostics-schema.json#/definitions/MultilingualStringHasAllDeclaredLanguages" + "$ref": "parameters-schema.json#/definitions/MultilingualStringHasAllDeclaredLanguages" }, "MultilingualStringUsingWithTemplate": { - "$ref": "diagnostics-schema.json#/definitions/MultilingualStringUsingWithTemplate" + "$ref": "parameters-schema.json#/definitions/MultilingualStringUsingWithTemplate" }, "NestedConstructorsInStructureDeclaration": { - "$ref": "diagnostics-schema.json#/definitions/NestedConstructorsInStructureDeclaration" + "$ref": "parameters-schema.json#/definitions/NestedConstructorsInStructureDeclaration" }, "NestedFunctionInParameters": { - "$ref": "diagnostics-schema.json#/definitions/NestedFunctionInParameters" + "$ref": "parameters-schema.json#/definitions/NestedFunctionInParameters" }, "NestedStatements": { - "$ref": "diagnostics-schema.json#/definitions/NestedStatements" + "$ref": "parameters-schema.json#/definitions/NestedStatements" }, "NestedTernaryOperator": { - "$ref": "diagnostics-schema.json#/definitions/NestedTernaryOperator" + "$ref": "parameters-schema.json#/definitions/NestedTernaryOperator" }, "NonExportMethodsInApiRegion": { - "$ref": "diagnostics-schema.json#/definitions/NonExportMethodsInApiRegion" + "$ref": "parameters-schema.json#/definitions/NonExportMethodsInApiRegion" }, "NonStandardRegion": { - "$ref": "diagnostics-schema.json#/definitions/NonStandardRegion" + "$ref": "parameters-schema.json#/definitions/NonStandardRegion" }, "NumberOfOptionalParams": { - "$ref": "diagnostics-schema.json#/definitions/NumberOfOptionalParams" + "$ref": "parameters-schema.json#/definitions/NumberOfOptionalParams" }, "NumberOfParams": { - "$ref": "diagnostics-schema.json#/definitions/NumberOfParams" + "$ref": "parameters-schema.json#/definitions/NumberOfParams" }, "NumberOfValuesInStructureConstructor": { - "$ref": "diagnostics-schema.json#/definitions/NumberOfValuesInStructureConstructor" + "$ref": "parameters-schema.json#/definitions/NumberOfValuesInStructureConstructor" }, "OSUsersMethod": { - "$ref": "diagnostics-schema.json#/definitions/OSUsersMethod" + "$ref": "parameters-schema.json#/definitions/OSUsersMethod" }, "OneStatementPerLine": { - "$ref": "diagnostics-schema.json#/definitions/OneStatementPerLine" + "$ref": "parameters-schema.json#/definitions/OneStatementPerLine" }, "OrderOfParams": { - "$ref": "diagnostics-schema.json#/definitions/OrderOfParams" + "$ref": "parameters-schema.json#/definitions/OrderOfParams" }, "PairingBrokenTransaction": { - "$ref": "diagnostics-schema.json#/definitions/PairingBrokenTransaction" + "$ref": "parameters-schema.json#/definitions/PairingBrokenTransaction" }, "ParseError": { - "$ref": "diagnostics-schema.json#/definitions/ParseError" + "$ref": "parameters-schema.json#/definitions/ParseError" }, "ProcedureReturnsValue": { - "$ref": "diagnostics-schema.json#/definitions/ProcedureReturnsValue" + "$ref": "parameters-schema.json#/definitions/ProcedureReturnsValue" }, "PublicMethodsDescription": { - "$ref": "diagnostics-schema.json#/definitions/PublicMethodsDescription" + "$ref": "parameters-schema.json#/definitions/PublicMethodsDescription" }, "SelfAssign": { - "$ref": "diagnostics-schema.json#/definitions/SelfAssign" + "$ref": "parameters-schema.json#/definitions/SelfAssign" }, "SelfInsertion": { - "$ref": "diagnostics-schema.json#/definitions/SelfInsertion" + "$ref": "parameters-schema.json#/definitions/SelfInsertion" }, "SemicolonPresence": { - "$ref": "diagnostics-schema.json#/definitions/SemicolonPresence" + "$ref": "parameters-schema.json#/definitions/SemicolonPresence" }, "SeveralCompilerDirectives": { - "$ref": "diagnostics-schema.json#/definitions/SeveralCompilerDirectives" + "$ref": "parameters-schema.json#/definitions/SeveralCompilerDirectives" }, "SpaceAtStartComment": { - "$ref": "diagnostics-schema.json#/definitions/SpaceAtStartComment" + "$ref": "parameters-schema.json#/definitions/SpaceAtStartComment" }, "TempFilesDir": { - "$ref": "diagnostics-schema.json#/definitions/TempFilesDir" + "$ref": "parameters-schema.json#/definitions/TempFilesDir" }, "TernaryOperatorUsage": { - "$ref": "diagnostics-schema.json#/definitions/TernaryOperatorUsage" + "$ref": "parameters-schema.json#/definitions/TernaryOperatorUsage" }, "ThisObjectAssign": { "$ref": "diagnostics-schema.json#/definitions/ThisObjectAssign" }, "TimeoutsInExternalResources": { - "$ref": "diagnostics-schema.json#/definitions/TimeoutsInExternalResources" + "$ref": "parameters-schema.json#/definitions/TimeoutsInExternalResources" }, "TooManyReturns": { - "$ref": "diagnostics-schema.json#/definitions/TooManyReturns" + "$ref": "parameters-schema.json#/definitions/TooManyReturns" }, "TryNumber": { - "$ref": "diagnostics-schema.json#/definitions/TryNumber" + "$ref": "parameters-schema.json#/definitions/TryNumber" }, "Typo": { - "$ref": "diagnostics-schema.json#/definitions/Typo" + "$ref": "parameters-schema.json#/definitions/Typo" }, "UnaryPlusInConcatenation": { - "$ref": "diagnostics-schema.json#/definitions/UnaryPlusInConcatenation" + "$ref": "parameters-schema.json#/definitions/UnaryPlusInConcatenation" }, "UnknownPreprocessorSymbol": { - "$ref": "diagnostics-schema.json#/definitions/UnknownPreprocessorSymbol" + "$ref": "parameters-schema.json#/definitions/UnknownPreprocessorSymbol" }, "UnreachableCode": { - "$ref": "diagnostics-schema.json#/definitions/UnreachableCode" + "$ref": "parameters-schema.json#/definitions/UnreachableCode" }, "UnusedLocalMethod": { - "$ref": "diagnostics-schema.json#/definitions/UnusedLocalMethod" + "$ref": "parameters-schema.json#/definitions/UnusedLocalMethod" }, "UnusedParameters": { - "$ref": "diagnostics-schema.json#/definitions/UnusedParameters" + "$ref": "parameters-schema.json#/definitions/UnusedParameters" }, "UseLessForEach": { - "$ref": "diagnostics-schema.json#/definitions/UseLessForEach" + "$ref": "parameters-schema.json#/definitions/UseLessForEach" }, "UsingCancelParameter": { - "$ref": "diagnostics-schema.json#/definitions/UsingCancelParameter" + "$ref": "parameters-schema.json#/definitions/UsingCancelParameter" }, "UsingExternalCodeTools": { - "$ref": "diagnostics-schema.json#/definitions/UsingExternalCodeTools" + "$ref": "parameters-schema.json#/definitions/UsingExternalCodeTools" }, "UsingFindElementByString": { - "$ref": "diagnostics-schema.json#/definitions/UsingFindElementByString" + "$ref": "parameters-schema.json#/definitions/UsingFindElementByString" }, "UsingGoto": { - "$ref": "diagnostics-schema.json#/definitions/UsingGoto" + "$ref": "parameters-schema.json#/definitions/UsingGoto" }, "UsingHardcodeNetworkAddress": { - "$ref": "diagnostics-schema.json#/definitions/UsingHardcodeNetworkAddress" + "$ref": "parameters-schema.json#/definitions/UsingHardcodeNetworkAddress" }, "UsingHardcodePath": { - "$ref": "diagnostics-schema.json#/definitions/UsingHardcodePath" + "$ref": "parameters-schema.json#/definitions/UsingHardcodePath" }, "UsingHardcodeSecretInformation": { - "$ref": "diagnostics-schema.json#/definitions/UsingHardcodeSecretInformation" + "$ref": "parameters-schema.json#/definitions/UsingHardcodeSecretInformation" }, "UsingModalWindows": { - "$ref": "diagnostics-schema.json#/definitions/UsingModalWindows" + "$ref": "parameters-schema.json#/definitions/UsingModalWindows" }, "UsingObjectNotAvailableUnix": { - "$ref": "diagnostics-schema.json#/definitions/UsingObjectNotAvailableUnix" + "$ref": "parameters-schema.json#/definitions/UsingObjectNotAvailableUnix" }, "UsingServiceTag": { - "$ref": "diagnostics-schema.json#/definitions/UsingServiceTag" + "$ref": "parameters-schema.json#/definitions/UsingServiceTag" }, "UsingSynchronousCalls": { - "$ref": "diagnostics-schema.json#/definitions/UsingSynchronousCalls" + "$ref": "parameters-schema.json#/definitions/UsingSynchronousCalls" }, "UsingThisForm": { - "$ref": "diagnostics-schema.json#/definitions/UsingThisForm" + "$ref": "parameters-schema.json#/definitions/UsingThisForm" }, "WrongUseOfRollbackTransactionMethod": { - "$ref": "diagnostics-schema.json#/definitions/WrongUseOfRollbackTransactionMethod" + "$ref": "parameters-schema.json#/definitions/WrongUseOfRollbackTransactionMethod" }, "YoLetterUsage": { - "$ref": "diagnostics-schema.json#/definitions/YoLetterUsage" + "$ref": "parameters-schema.json#/definitions/YoLetterUsage" } } } + }, + "properties": { + "language": { + "$id": "#/properties/language", + "type": "string", + "oneOf": [ + { + "const": "en", + "description": "English" + }, + { + "const": "ru", + "description": "\u0420\u0443\u0441\u0441\u043a\u0438\u0439 (russian)" + } + ], + "title": "Language of messages, resources and all communications between BLS LS and user.", + "default": "ru" + }, + "codeLens": { + "$id": "#/properties/codeLens", + "type": "object", + "title": "Code Lens configuration.", + "default": null, + "properties": { + "showCognitiveComplexity": { + "$id": "#/properties/showCognitiveComplexity", + "type": "boolean", + "title": "Show cognitive complexity score above method definition.", + "default": true + }, + "showCyclomaticComplexity": { + "$id": "#/properties/showCyclomaticComplexity", + "type": "boolean", + "title": "Show cyclomatic complexity score above method definition.", + "default": true + } + } + }, + "diagnostics": { + "$id": "#/properties/diagnostics", + "type": "object", + "title": "Diagnostics configuration.", + "default": null, + "properties": { + "parameters": { + "$ref": "#/definitions/parameters" + }, + "computeTrigger": { + "$id": "#/properties/computeTrigger", + "type": "string", + "oneOf": [ + { + "const": "onSave", + "description": "Compute on save" + }, + { + "const": "onType", + "description": "Compute on type (edit file)" + }, + { + "const": "never", + "description": "Never compute" + } + ], + "title": "Trigger for the computation of diagnostics.", + "default": "onSave" + }, + "skipSupport": { + "$id": "#/properties/skipSupport", + "type": "string", + "oneOf": [ + { + "const": "withSupport", + "description": "Skip computing diagnostics on modules with any kind of support." + }, + { + "const": "withSupportLocked", + "description": "Skip computing diagnostics on modules with `not editable` support mode." + }, + { + "const": "never", + "description": "Never skip computing." + } + ], + "title": "Analyze module support variant and skip all diagnostics if necessary.", + "default": "never" + }, + "mode": { + "$id": "#/properties/mode", + "type": "string", + "oneOf": [ + { + "const": "on", + "description": "All diagnostics activated by default are enabled." + }, + { + "const": "off", + "description": "All diagnostics are disabled" + }, + { + "const": "except", + "description": "All diagnostics except defined in 'parameters' section are disabled." + }, + { + "const": "only", + "description": "Only diagnostics defined in 'parameters' section are enabled." + }, + { + "const": "all", + "description": "All diagnostics are enabled." + } + ], + "title": "Diagnostics enabling/disabling mode.", + "default": "on" + } + } + }, + "traceLog": { + "$id": "#/properties/traceLog", + "type": "string", + "title": "Path to file to log all inbound and outbound requests between BSL Language Server and Language Client from used IDE.\nCan be absolute or relative (to the project root). If set *significantly slows down* communication speed between server and client.", + "default": "", + "examples": [ + ".trace.log" + ] + }, + "configurationRoot": { + "$id": "#/properties/configurationRoot", + "type": "string", + "title": "Path to root directory of configuration files.", + "default": null + } } } \ No newline at end of file From 2af7087610b9d1459ed2146e0f1e090df71b843f Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Tue, 14 Apr 2020 13:13:03 +0300 Subject: [PATCH 105/444] =?UTF-8?q?=D0=A1=D0=BA=D0=BE=D1=80=D1=80=D0=B5?= =?UTF-8?q?=D0=BA=D1=82=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=20=D1=81=D0=BA?= =?UTF-8?q?=D1=80=D0=B8=D0=BF=D1=82=20=D0=B4=D0=BB=D1=8F=20=D0=BD=D0=BE?= =?UTF-8?q?=D0=B2=D0=BE=D0=B9=20=D1=81=D1=85=D0=B5=D0=BC=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gradle/developer-tools.gradle.kts | 65 ++++++++++++++++--------------- 1 file changed, 34 insertions(+), 31 deletions(-) diff --git a/gradle/developer-tools.gradle.kts b/gradle/developer-tools.gradle.kts index 9edc83a1fec..8b6be96d8ad 100644 --- a/gradle/developer-tools.gradle.kts +++ b/gradle/developer-tools.gradle.kts @@ -8,7 +8,7 @@ open class DeveloperTools @javax.inject.Inject constructor(objects: ObjectFactor val outputDir: DirectoryProperty = objects.directoryProperty() private var schemaPath = "src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json" - private var diagnosticSchemaPath = "src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json" + private var diagnosticSchemaPath = "src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json" private var templateDocHeader = "# ()\n\n\n" + "\n" @@ -53,7 +53,7 @@ open class DeveloperTools @javax.inject.Inject constructor(objects: ObjectFactor "String" to "Строка", "Float" to "Число с плавающей точкой") - private fun createDiagnosticSupplier(lang: String, classLoader: ClassLoader) : Any { + private fun createDiagnosticSupplier(lang: String, classLoader: ClassLoader): Any { val languageServerConfigurationClass = classLoader.loadClass("com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration") val languageClass = classLoader.loadClass("com.github._1c_syntax.bsl.languageserver.configuration.Language") @@ -81,7 +81,8 @@ open class DeveloperTools @javax.inject.Inject constructor(objects: ObjectFactor val urlsParent: ArrayList = ArrayList() project.configurations.getByName("runtimeClasspath").files.forEach { - urlsParent.add(it.toURI().toURL())} + urlsParent.add(it.toURI().toURL()) + } val parentCL = URLClassLoader(urlsParent.toTypedArray()) return URLClassLoader(urls.toTypedArray(), parentCL) } @@ -97,16 +98,18 @@ open class DeveloperTools @javax.inject.Inject constructor(objects: ObjectFactor val result = hashMapOf>() File(project.buildDir, "classes/java/main/com/github/_1c_syntax/bsl/languageserver/diagnostics") .walkTopDown() - .filter{it.name.endsWith("Diagnostic.class") - && !it.name.startsWith("Abstract")} + .filter { + it.name.endsWith("Diagnostic.class") + && !it.name.startsWith("Abstract") + } .forEach { val diagnosticClass = classLoader.loadClass("com.github._1c_syntax.bsl.languageserver.diagnostics.${it.nameWithoutExtension}") - if(!diagnosticClass.toString().startsWith("interface")){ + if (!diagnosticClass.toString().startsWith("interface")) { val diagnosticInstanceRU = diagnosticSupplierClass.getDeclaredMethod("getDiagnosticInstance", diagnosticClass.javaClass).invoke(diagnosticSupplierRU, diagnosticClass) val diagnosticInstanceEN = diagnosticSupplierClass.getDeclaredMethod("getDiagnosticInstance", diagnosticClass.javaClass).invoke(diagnosticSupplierEN, diagnosticClass) val metadata = getDiagnosticMetadata(diagnosticClass, diagnosticInstanceRU, diagnosticInstanceEN, classLoader) - if(metadata.isNotEmpty() && metadata["key"] is String) { + if (metadata.isNotEmpty() && metadata["key"] is String) { result[metadata["key"] as String] = metadata } } @@ -139,8 +142,8 @@ open class DeveloperTools @javax.inject.Inject constructor(objects: ObjectFactor val params = arrayListOf>() val parameters = diagnosticInfoClass.getMethod("getParameters").invoke(infoRU) - if(parameters is ArrayList<*>) { - for(parameter in parameters) { + if (parameters is ArrayList<*>) { + for (parameter in parameters) { val oneParameter = hashMapOf() val parameterName = diagnosticParameterInfoClass.getMethod("getName").invoke(parameter).toString() oneParameter["name"] = parameterName @@ -162,7 +165,7 @@ open class DeveloperTools @javax.inject.Inject constructor(objects: ObjectFactor @TaskAction fun execTask() { val diagnosticsMetadata = getDiagnosticsMetadata() - if(taskName == "Update diagnostic docs") { + if (taskName == "Update diagnostic docs") { logger.quiet("Update diagnostic docs") diagnosticsMetadata.forEach { updateDocFile("ru", @@ -173,12 +176,12 @@ open class DeveloperTools @javax.inject.Inject constructor(objects: ObjectFactor it.key, it.value) } - } else if(taskName == "Update diagnostics index") { + } else if (taskName == "Update diagnostics index") { logger.quiet("Update diagnostics index") val diagnosticsMetadataSort = diagnosticsMetadata.toSortedMap() updateDiagnosticIndex("ru", diagnosticsMetadataSort) updateDiagnosticIndex("en", diagnosticsMetadataSort) - } else if(taskName == "Update json schema") { + } else if (taskName == "Update json schema") { val diagnosticMeta = transformMetadata(diagnosticsMetadata) var schemaJson = groovy.json.JsonSlurper().parseText(File(outputDir.get().asFile.path, diagnosticSchemaPath).readText(charset("UTF-8"))) if (schemaJson is Map<*, *>) { @@ -191,16 +194,16 @@ open class DeveloperTools @javax.inject.Inject constructor(objects: ObjectFactor schemaJson = groovy.json.JsonSlurper().parseText(File(outputDir.get().asFile.path, schemaPath).readText(charset("UTF-8"))) if (schemaJson is Map<*, *>) { val schema = schemaJson.toMap().toMutableMap() - val schemaProperties = schema["properties"] - if (schemaProperties != null && schemaProperties is Map<*, *>) { - val schProp = schemaProperties.toMap().toMutableMap() - val schemaPropertiesDiagnostics = schProp["diagnostics"] - if (schemaPropertiesDiagnostics != null && schemaPropertiesDiagnostics is Map<*, *>) { - val schPropDiag = schemaPropertiesDiagnostics.toMap().toMutableMap() - schPropDiag["properties"] = diagnosticMeta["diagnosticsKeys"] - schProp["diagnostics"] = schPropDiag + val schemaDefinitions = schema["definitions"] + if (schemaDefinitions != null && schemaDefinitions is Map<*, *>) { + val schemaDefinitionInner = schemaDefinitions.toMap().toMutableMap() + val schemaParameters = schemaDefinitionInner["parameters"] + if (schemaParameters != null && schemaParameters is Map<*, *>) { + val schemaParametersInner = schemaParameters.toMap().toMutableMap() + schemaParametersInner["properties"] = diagnosticMeta["diagnosticsKeys"] + schemaDefinitionInner["parameters"] = schemaParametersInner } - schema["properties"] = schProp + schema["definitions"] = schemaDefinitionInner } val resultString = groovy.json.JsonBuilder(schema).toPrettyString() @@ -214,8 +217,8 @@ open class DeveloperTools @javax.inject.Inject constructor(objects: ObjectFactor val diagnostics = sortedMapOf() val diagnosticsKeys = sortedMapOf>() - diagnosticsMetadata.forEach {itd -> - diagnosticsKeys[itd.key] = hashMapOf("\$ref" to "diagnostics-schema.json#/definitions/${itd.key}") + diagnosticsMetadata.forEach { itd -> + diagnosticsKeys[itd.key] = hashMapOf("\$ref" to "parameters-schema.json#/definitions/${itd.key}") val diagnostic = hashMapOf("\$id" to "#/definitions/${itd.key}", "type" to arrayListOf("boolean", "object"), "title" to itd.value.getOrDefault("description_en", "").toString(), @@ -276,7 +279,7 @@ open class DeveloperTools @javax.inject.Inject constructor(objects: ObjectFactor .replace("[", "`") .replace("]", "`") .replace(", ", "`
`") - if(lang == "ru") { + if (lang == "ru") { typeString = typeRuMap.getOrDefault(metadata.getOrDefault("type", ""), "") indexText += templateIndexLine .replace("", it.key) @@ -299,7 +302,7 @@ open class DeveloperTools @javax.inject.Inject constructor(objects: ObjectFactor typeCount[typeString] = typeCount.getOrDefault(typeString, 0) + 1 } - val indexPath = if(lang == "ru") { + val indexPath = if (lang == "ru") { File(outputDir.get().asFile.path, "docs/diagnostics/index.md") } else { File(outputDir.get().asFile.path, "docs/en/diagnostics/index.md") @@ -327,7 +330,7 @@ open class DeveloperTools @javax.inject.Inject constructor(objects: ObjectFactor } private fun updateDocFile(lang: String, key: String, metadata: HashMap) { - val docPath = if(lang == "ru") { + val docPath = if (lang == "ru") { File(outputDir.get().asFile.path, "docs/diagnostics/${key}.md") } else { File(outputDir.get().asFile.path, "docs/en/diagnostics/${key}.md") @@ -465,7 +468,7 @@ open class DeveloperTools @javax.inject.Inject constructor(objects: ObjectFactor private fun makeDiagnosticConfigExample(metadata: HashMap): String { val params = metadata.getOrDefault("parameters", arrayListOf>()) - if(params is ArrayList<*>) { + if (params is ArrayList<*>) { if (params.isEmpty()) { return "false" @@ -475,7 +478,7 @@ open class DeveloperTools @javax.inject.Inject constructor(objects: ObjectFactor var configDelimiter = "" params.forEach { if (it is HashMap<*, *>) { - val qoutes = if(it.getOrDefault("type", "") == "Boolean" + val qoutes = if (it.getOrDefault("type", "") == "Boolean" || it.getOrDefault("type", "") == "Integer" || it.getOrDefault("type", "") == "Float") "" else "\"" configBody += "$configDelimiter \"${it.getOrDefault("name", "")}\": " + @@ -498,7 +501,7 @@ tasks.register("updateDiagnosticDocs") { description = "Updates diagnostic docs after changes" outputDir.set(project.layout.projectDirectory) taskName = "Update diagnostic docs" - outputs.upToDateWhen {false} + outputs.upToDateWhen { false } } tasks.register("updateDiagnosticsIndex") { @@ -507,7 +510,7 @@ tasks.register("updateDiagnosticsIndex") { description = "Update diagnostics index after changes" outputDir.set(project.layout.projectDirectory) taskName = "Update diagnostics index" - outputs.upToDateWhen {false} + outputs.upToDateWhen { false } } tasks.register("updateJsonSchema") { @@ -516,5 +519,5 @@ tasks.register("updateJsonSchema") { description = "Update json schema" outputDir.set(project.layout.projectDirectory) taskName = "Update json schema" - outputs.upToDateWhen {false} + outputs.upToDateWhen { false } } From 5cff3da35d007beded8d00af1dc1435a13ce96a8 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Tue, 14 Apr 2020 13:40:55 +0300 Subject: [PATCH 106/444] =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=B7=D0=B0=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=B7=D0=BD=D0=B0=D1=87=D0=B5=D0=BD=D0=B8=D1=8F=20?= =?UTF-8?q?=D0=BF=D0=BE=20=D1=83=D0=BC=D0=BE=D0=BB=D1=87=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gradle/developer-tools.gradle.kts | 2 +- .../configuration/parameters-schema.json | 172 +++++++++--------- 2 files changed, 87 insertions(+), 87 deletions(-) diff --git a/gradle/developer-tools.gradle.kts b/gradle/developer-tools.gradle.kts index 8b6be96d8ad..753b9d34602 100644 --- a/gradle/developer-tools.gradle.kts +++ b/gradle/developer-tools.gradle.kts @@ -223,7 +223,7 @@ open class DeveloperTools @javax.inject.Inject constructor(objects: ObjectFactor "type" to arrayListOf("boolean", "object"), "title" to itd.value.getOrDefault("description_en", "").toString(), "description" to itd.value.getOrDefault("description_en", "").toString(), - "default" to null) + "default" to itd.value.getOrDefault("activatedByDefault", "false").toString().toBoolean()) val params = HashMap() val parameters = itd.value.getOrDefault("parameters", arrayListOf>()) as ArrayList<*> diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index 1820ff1f817..cbe9edd2495 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -6,7 +6,7 @@ "definitions": { "BeginTransactionBeforeTryCatch": { "description": "Violating transaction rules for the 'BeginTransaction' method", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -16,7 +16,7 @@ }, "CanonicalSpellingKeywords": { "description": "Canonical keyword writing", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -26,7 +26,7 @@ }, "CodeBlockBeforeSub": { "description": "Method definitions must be placed before the module body operators", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -36,7 +36,7 @@ }, "CodeOutOfRegion": { "description": "Code out of region", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -46,7 +46,7 @@ }, "CognitiveComplexity": { "description": "Cognitive complexity", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -70,7 +70,7 @@ }, "CommentedCode": { "description": "Commented out code", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -88,7 +88,7 @@ }, "CommitTransactionOutsideTryCatch": { "description": "Violating transaction rules for the 'CommitTransaction' method", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -108,7 +108,7 @@ }, "CompilationDirectiveLost": { "description": "Methods compilation directive", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -118,7 +118,7 @@ }, "CompilationDirectiveNeedLess": { "description": "Needless compilation directive", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -146,7 +146,7 @@ }, "CreateQueryInCycle": { "description": "Execution query on cycle", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -156,7 +156,7 @@ }, "CyclomaticComplexity": { "description": "Cyclomatic complexity", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -198,7 +198,7 @@ }, "DeletingCollectionItem": { "description": "Deleting an item when iterating through collection using the operator \"For each ... In ... Do\"", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -208,7 +208,7 @@ }, "DeprecatedCurrentDate": { "description": "Using of the deprecated method \"CurrentDate\"", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -218,7 +218,7 @@ }, "DeprecatedFind": { "description": "Using of the deprecated method \"Find\"", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -228,7 +228,7 @@ }, "DeprecatedMessage": { "description": "Restriction on the use of deprecated \"Message\" method", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -238,7 +238,7 @@ }, "DeprecatedTypeManagedForm": { "description": "Deprecated ManagedForm type", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -248,7 +248,7 @@ }, "DuplicateRegion": { "description": "Duplicate regions", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -258,7 +258,7 @@ }, "EmptyCodeBlock": { "description": "Empty code block", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -276,7 +276,7 @@ }, "EmptyRegion": { "description": "The region should not be empty", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -286,7 +286,7 @@ }, "EmptyStatement": { "description": "Empty statement", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -306,7 +306,7 @@ }, "ExtraCommas": { "description": "Commas without a parameter at the end of a method call", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -316,7 +316,7 @@ }, "FormDataToValue": { "description": "FormDataToValue method call", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -326,7 +326,7 @@ }, "FunctionNameStartsWithGet": { "description": "Function name shouldn't start with \"\u041f\u043e\u043b\u0443\u0447\u0438\u0442\u044c\"", - "default": null, + "default": false, "type": [ "boolean", "object" @@ -336,7 +336,7 @@ }, "FunctionShouldHaveReturn": { "description": "The function should have return", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -346,7 +346,7 @@ }, "GetFormMethod": { "description": "GetForm method call", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -356,7 +356,7 @@ }, "IdenticalExpressions": { "description": "There are identical sub-expressions to the left and to the right of the \"foo\" operator", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -366,7 +366,7 @@ }, "IfConditionComplexity": { "description": "Usage of complex expressions in the \"If\" condition", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -384,7 +384,7 @@ }, "IfElseDuplicatedCodeBlock": { "description": "Duplicated code blocks in If...Then...ElseIf... statements", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -394,7 +394,7 @@ }, "IfElseDuplicatedCondition": { "description": "Duplicated conditions in If...Then...ElseIf... statements", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -404,7 +404,7 @@ }, "IfElseIfEndsWithElse": { "description": "Else...The...ElseIf... statement should end with Else branch", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -414,7 +414,7 @@ }, "InvalidCharacterInFile": { "description": "Invalid character", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -424,7 +424,7 @@ }, "LineLength": { "description": "Line Length limit", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -442,7 +442,7 @@ }, "MagicNumber": { "description": "Magic numbers", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -466,7 +466,7 @@ }, "MethodSize": { "description": "Method size", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -484,7 +484,7 @@ }, "MissingCodeTryCatchEx": { "description": "Missing code in Raise block in \"Try ... Raise ... EndTry\"", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -502,7 +502,7 @@ }, "MissingSpace": { "description": "Missing spaces to the left or right of operators + - * / = % < > <> <= >=, and also to the right of , and ;", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -544,7 +544,7 @@ }, "MissingTemporaryFileDeletion": { "description": "Missing temporary file deletion after using", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -572,7 +572,7 @@ }, "MultilingualStringHasAllDeclaredLanguages": { "description": "There is a localized text for all languages declared in the configuration", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -590,7 +590,7 @@ }, "MultilingualStringUsingWithTemplate": { "description": "Partially localized text is used in the StrTemplate function", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -608,7 +608,7 @@ }, "NestedConstructorsInStructureDeclaration": { "description": "Nested constructors with parameters in structure declaration", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -618,7 +618,7 @@ }, "NestedFunctionInParameters": { "description": "Initialization of method and constructor parameters by calling nested methods", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -628,7 +628,7 @@ }, "NestedStatements": { "description": "Control flow statements should not be nested too deep", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -646,7 +646,7 @@ }, "NestedTernaryOperator": { "description": "Nested ternary operator", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -656,7 +656,7 @@ }, "NonExportMethodsInApiRegion": { "description": "Non export methods in API regions", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -666,7 +666,7 @@ }, "NonStandardRegion": { "description": "Non-standard region of module", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -676,7 +676,7 @@ }, "NumberOfOptionalParams": { "description": "Limit number of optional parameters in method", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -694,7 +694,7 @@ }, "NumberOfParams": { "description": "Number of parameters in method", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -712,7 +712,7 @@ }, "NumberOfValuesInStructureConstructor": { "description": "Limit on the number of property values passed to the structure constructor", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -730,7 +730,7 @@ }, "OSUsersMethod": { "description": "Using method OSUsers", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -740,7 +740,7 @@ }, "OneStatementPerLine": { "description": "One statement per line", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -750,7 +750,7 @@ }, "OrderOfParams": { "description": "Order of Parameters in method", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -760,7 +760,7 @@ }, "PairingBrokenTransaction": { "description": "Violation of pairing using methods \"BeginTransaction()\" & \"CommitTransaction()\" / \"RollbackTransaction()\"", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -770,7 +770,7 @@ }, "ParseError": { "description": "Source code parse error", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -780,7 +780,7 @@ }, "ProcedureReturnsValue": { "description": "Procedure should not return Value", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -790,7 +790,7 @@ }, "PublicMethodsDescription": { "description": "All public methods must have a description", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -808,7 +808,7 @@ }, "SelfAssign": { "description": "Variable is assigned to itself", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -818,7 +818,7 @@ }, "SelfInsertion": { "description": "Insert a collection into itself", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -828,7 +828,7 @@ }, "SemicolonPresence": { "description": "Statement should end with semicolon symbol \";\"", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -838,7 +838,7 @@ }, "SeveralCompilerDirectives": { "description": "Erroneous indication of several compilation directives", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -848,7 +848,7 @@ }, "SpaceAtStartComment": { "description": "Space at the beginning of the comment", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -866,7 +866,7 @@ }, "TempFilesDir": { "description": "TempFilesDir() method call", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -876,7 +876,7 @@ }, "TernaryOperatorUsage": { "description": "Ternary operator usage", - "default": null, + "default": false, "type": [ "boolean", "object" @@ -896,7 +896,7 @@ }, "TimeoutsInExternalResources": { "description": "Timeouts working with external resources", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -914,7 +914,7 @@ }, "TooManyReturns": { "description": "Methods should not have too many return statements", - "default": null, + "default": false, "type": [ "boolean", "object" @@ -932,7 +932,7 @@ }, "TryNumber": { "description": "Cast to number of try catch block", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -942,7 +942,7 @@ }, "Typo": { "description": "Typo", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -966,7 +966,7 @@ }, "UnaryPlusInConcatenation": { "description": "Unary Plus sign in string concatenation", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -976,7 +976,7 @@ }, "UnknownPreprocessorSymbol": { "description": "Unknown preprocessor symbol", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -986,7 +986,7 @@ }, "UnreachableCode": { "description": "Unreachable Code", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -996,7 +996,7 @@ }, "UnusedLocalMethod": { "description": "Unused local method", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -1006,7 +1006,7 @@ }, "UnusedParameters": { "description": "Unused parameter", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -1016,7 +1016,7 @@ }, "UseLessForEach": { "description": "Useless collection iteration", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -1026,7 +1026,7 @@ }, "UsingCancelParameter": { "description": "Using parameter \"Cancel\"", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -1036,7 +1036,7 @@ }, "UsingExternalCodeTools": { "description": "Using external code tools", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -1046,7 +1046,7 @@ }, "UsingFindElementByString": { "description": "Using FindByName and FindByCode", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -1056,7 +1056,7 @@ }, "UsingGoto": { "description": "\"goto\" statement should not be used", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -1066,7 +1066,7 @@ }, "UsingHardcodeNetworkAddress": { "description": "Using hardcode ip addresses in code", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -1084,7 +1084,7 @@ }, "UsingHardcodePath": { "description": "Using hardcode file paths in code", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -1102,7 +1102,7 @@ }, "UsingHardcodeSecretInformation": { "description": "Storing confidential information in code", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -1120,7 +1120,7 @@ }, "UsingModalWindows": { "description": "Using modal windows", - "default": null, + "default": false, "type": [ "boolean", "object" @@ -1130,7 +1130,7 @@ }, "UsingObjectNotAvailableUnix": { "description": "Using unavailable in Unix objects", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -1140,7 +1140,7 @@ }, "UsingServiceTag": { "description": "Using service tags", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -1158,7 +1158,7 @@ }, "UsingSynchronousCalls": { "description": "Using synchronous calls", - "default": null, + "default": false, "type": [ "boolean", "object" @@ -1168,7 +1168,7 @@ }, "UsingThisForm": { "description": "Using deprecated property \"ThisForm\"", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -1178,7 +1178,7 @@ }, "WrongUseOfRollbackTransactionMethod": { "description": "Not recommended using of RollbackTransaction method", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -1188,7 +1188,7 @@ }, "YoLetterUsage": { "description": "Using Russian character \"yo\" (\"\u0451\") in code", - "default": null, + "default": true, "type": [ "boolean", "object" From cf65e7fdee3196de9d846361c604cc8ca2ebf148 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Tue, 21 Apr 2020 23:25:45 +0300 Subject: [PATCH 107/444] precommit --- docs/diagnostics/ConsecutiveEmptyLines.md | 3 +-- docs/en/diagnostics/ConsecutiveEmptyLines.md | 3 +-- .../configuration/parameters-schema.json | 12 ++++++------ .../bsl/languageserver/configuration/schema.json | 12 ++++++------ 4 files changed, 14 insertions(+), 16 deletions(-) diff --git a/docs/diagnostics/ConsecutiveEmptyLines.md b/docs/diagnostics/ConsecutiveEmptyLines.md index 870d6df000d..bbe63ac8e54 100644 --- a/docs/diagnostics/ConsecutiveEmptyLines.md +++ b/docs/diagnostics/ConsecutiveEmptyLines.md @@ -32,7 +32,6 @@ ```json "ConsecutiveEmptyLines": { - "allowedEmptyLinesCount": 1 + "allowedEmptyLinesCount": 1 } ``` - diff --git a/docs/en/diagnostics/ConsecutiveEmptyLines.md b/docs/en/diagnostics/ConsecutiveEmptyLines.md index d4ee1307f9a..7cfb5033d72 100644 --- a/docs/en/diagnostics/ConsecutiveEmptyLines.md +++ b/docs/en/diagnostics/ConsecutiveEmptyLines.md @@ -14,7 +14,6 @@ ## Description - ## Snippets @@ -29,6 +28,6 @@ ```json "ConsecutiveEmptyLines": { - "allowedEmptyLinesCount": 1 + "allowedEmptyLinesCount": 1 } ``` diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index cbe9edd2495..6eb3492e4b4 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -98,7 +98,7 @@ }, "CommonModuleAssign": { "description": "CommonModuleAssign", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -128,7 +128,7 @@ }, "ConsecutiveEmptyLines": { "description": "Consecutive empty lines", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -180,7 +180,7 @@ }, "DataExchangeLoading": { "description": "There is no check for the attribute DataExchange.Load in the object's event handler", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -296,7 +296,7 @@ }, "ExcessiveAutoTestCheck": { "description": "Excessive AutoTest Check", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -562,7 +562,7 @@ }, "MissingVariablesDescription": { "description": "All variables declarations must have a description", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -886,7 +886,7 @@ }, "ThisObjectAssign": { "description": "ThisObject assign", - "default": null, + "default": true, "type": [ "boolean", "object" diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 4f1a26da95a..aa01b50a23f 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -45,7 +45,7 @@ "$ref": "parameters-schema.json#/definitions/CommitTransactionOutsideTryCatch" }, "CommonModuleAssign": { - "$ref": "diagnostics-schema.json#/definitions/CommonModuleAssign" + "$ref": "parameters-schema.json#/definitions/CommonModuleAssign" }, "CompilationDirectiveLost": { "$ref": "parameters-schema.json#/definitions/CompilationDirectiveLost" @@ -54,7 +54,7 @@ "$ref": "parameters-schema.json#/definitions/CompilationDirectiveNeedLess" }, "ConsecutiveEmptyLines": { - "$ref": "diagnostics-schema.json#/definitions/ConsecutiveEmptyLines" + "$ref": "parameters-schema.json#/definitions/ConsecutiveEmptyLines" }, "CreateQueryInCycle": { "$ref": "parameters-schema.json#/definitions/CreateQueryInCycle" @@ -63,7 +63,7 @@ "$ref": "parameters-schema.json#/definitions/CyclomaticComplexity" }, "DataExchangeLoading": { - "$ref": "diagnostics-schema.json#/definitions/DataExchangeLoading" + "$ref": "parameters-schema.json#/definitions/DataExchangeLoading" }, "DeletingCollectionItem": { "$ref": "parameters-schema.json#/definitions/DeletingCollectionItem" @@ -93,7 +93,7 @@ "$ref": "parameters-schema.json#/definitions/EmptyStatement" }, "ExcessiveAutoTestCheck": { - "$ref": "diagnostics-schema.json#/definitions/ExcessiveAutoTestCheck" + "$ref": "parameters-schema.json#/definitions/ExcessiveAutoTestCheck" }, "ExtraCommas": { "$ref": "parameters-schema.json#/definitions/ExtraCommas" @@ -147,7 +147,7 @@ "$ref": "parameters-schema.json#/definitions/MissingTemporaryFileDeletion" }, "MissingVariablesDescription": { - "$ref": "diagnostics-schema.json#/definitions/MissingVariablesDescription" + "$ref": "parameters-schema.json#/definitions/MissingVariablesDescription" }, "MultilingualStringHasAllDeclaredLanguages": { "$ref": "parameters-schema.json#/definitions/MultilingualStringHasAllDeclaredLanguages" @@ -225,7 +225,7 @@ "$ref": "parameters-schema.json#/definitions/TernaryOperatorUsage" }, "ThisObjectAssign": { - "$ref": "diagnostics-schema.json#/definitions/ThisObjectAssign" + "$ref": "parameters-schema.json#/definitions/ThisObjectAssign" }, "TimeoutsInExternalResources": { "$ref": "parameters-schema.json#/definitions/TimeoutsInExternalResources" From 0316abf234db9491d2483566794bb4e356db9f9c Mon Sep 17 00:00:00 2001 From: Yuri Goncharuk Date: Tue, 21 Apr 2020 23:41:02 +0300 Subject: [PATCH 108/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D0=B2=D0=BE=D0=B7=D0=BC=D0=BE=D0=B6=D0=BD?= =?UTF-8?q?=D0=BE=D1=81=D1=82=D1=8C=20=D0=BF=D0=BE=20=D0=B2=D1=8B=D0=B2?= =?UTF-8?q?=D0=BE=D0=B4=D1=83=20=D0=B2=20=D0=BE=D1=82=D1=87=D0=B5=D1=82=20?= =?UTF-8?q?=D1=81=D1=82=D1=80=D0=BE=D0=BA=20=D1=82=D1=80=D0=B5=D0=B1=D1=83?= =?UTF-8?q?=D1=8E=D1=89=D0=B8=D1=85=20=D0=BF=D0=BE=D0=BA=D1=80=D1=8B=D1=82?= =?UTF-8?q?=D0=B8=D1=8F=20=D0=B2=20=D1=84=D0=BE=D1=80=D0=BC=D0=B0=D1=82?= =?UTF-8?q?=D0=B5=20GenericCoverage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../reporter/GenericCoverageReport.java | 109 ++++++++++++++++++ .../reporter/GenericCoverageReporter.java | 62 ++++++++++ .../reporter/ReportersAggregator.java | 1 + .../reporter/GenericCoverageTest.java | 85 ++++++++++++++ 4 files changed, 257 insertions(+) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageReport.java create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageReporter.java create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageTest.java diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageReport.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageReport.java new file mode 100644 index 00000000000..7c95a477e91 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageReport.java @@ -0,0 +1,109 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics.reporter; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; +import com.github._1c_syntax.bsl.languageserver.diagnostics.FileInfo; +import lombok.Getter; +import lombok.Value; + +import java.util.ArrayList; +import java.util.List; + +@JacksonXmlRootElement(localName = "coverage") +public class GenericCoverageReport { + + @JacksonXmlProperty(isAttribute = true) + @Getter + public final String version; + + @JacksonXmlElementWrapper(useWrapping = false) + @Getter + public final List file; + + public GenericCoverageReport(AnalysisInfo analysisInfo) { + + version = "1"; + file = new ArrayList<>(); + + for (FileInfo fileInfo : analysisInfo.getFileinfos()) { + file.add(new GenericCoverageReportEntry(fileInfo)); + } + } + + public GenericCoverageReport( + @JsonProperty("version") String version, + @JsonProperty("file") List file + ) { + + this.version = version; + this.file = new ArrayList<>(file); + } + + @Value + static class GenericCoverageReportEntry { + + @JacksonXmlProperty(isAttribute = true) + public String path; + + @JacksonXmlElementWrapper(useWrapping = false) + public List lineToCover; + + public GenericCoverageReportEntry(FileInfo fileInfo) { + this.path = fileInfo.getPath().toString(); + this.lineToCover = new ArrayList<>(); + + for (int lineToCover : fileInfo.getMetrics().getCovlocData()) { + this.lineToCover.add(new LineToCoverEntry(lineToCover, false)); + } + } + + public GenericCoverageReportEntry( + @JsonProperty("path") String path, + @JsonProperty("version") List lineToCover + ) { + this.path = path; + this.lineToCover = new ArrayList<>(); + } + } + + @Value + static class LineToCoverEntry { + + @JacksonXmlProperty(isAttribute = true) + public int lineNumber; + + @JacksonXmlProperty(isAttribute = true) + public boolean covered; + + public LineToCoverEntry( + @JsonProperty("lineNumber") int lineNumber, + @JsonProperty("covered") boolean covered + ) { + this.covered = covered; + this.lineNumber = lineNumber; + } + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageReporter.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageReporter.java new file mode 100644 index 00000000000..3bf8d3cb920 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageReporter.java @@ -0,0 +1,62 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics.reporter; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import lombok.extern.slf4j.Slf4j; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; + +@Slf4j +public class GenericCoverageReporter extends AbstractDiagnosticReporter { + + public static final String KEY = "genericCoverage"; + + public GenericCoverageReporter() { + super(); + } + + public GenericCoverageReporter(Path outputDir) { + super(outputDir); + } + + @Override + public void report(AnalysisInfo analysisInfo) { + + GenericCoverageReport report = new GenericCoverageReport(analysisInfo); + + ObjectMapper mapper = new XmlMapper(); + mapper.enable(SerializationFeature.INDENT_OUTPUT); + + try { + File reportFile = new File(outputDir.toFile(), "genericCoverage.xml"); + mapper.writeValue(reportFile, report); + LOGGER.info("Generic coverage report saved to {}", reportFile.getCanonicalPath()); + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/ReportersAggregator.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/ReportersAggregator.java index b916481fb58..21d6f1e8f05 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/ReportersAggregator.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/ReportersAggregator.java @@ -69,6 +69,7 @@ private static Map reporterMap() { map.put(JUnitReporter.KEY, JUnitReporter.class); map.put(TSLintReporter.KEY, TSLintReporter.class); map.put(GenericIssueReporter.KEY, GenericIssueReporter.class); + map.put(GenericCoverageReporter.KEY, GenericCoverageReporter.class); return map; } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageTest.java new file mode 100644 index 00000000000..30676b1da76 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageTest.java @@ -0,0 +1,85 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics.reporter; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.diagnostics.FileInfo; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import org.apache.commons.io.FileUtils; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.io.IOException; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GenericCoverageTest { + + private final File file = new File("./genericCoverage.xml"); + + @BeforeEach + void setUp() { + FileUtils.deleteQuietly(file); + } + + @AfterEach + void tearDown() { + FileUtils.deleteQuietly(file); + } + + @Test + void report() throws IOException { + + // given + String sourceDir = "."; + String filePath = "./src/test/resources/context/DocumentContextLocForCoverTest.bsl"; + + // when + DocumentContext documentContext = TestUtils.getDocumentContextFromFile(filePath); + FileInfo fileInfo = new FileInfo(sourceDir, documentContext, new ArrayList<>()); + AnalysisInfo analysisInfo = new AnalysisInfo(LocalDateTime.now(), Collections.singletonList(fileInfo), sourceDir); + + AbstractDiagnosticReporter reporter = new GenericCoverageReporter(); + reporter.report(analysisInfo); + + // then + ObjectMapper mapper = new XmlMapper(); + GenericCoverageReport report = mapper.readValue(file, GenericCoverageReport.class); + + assertThat(report).isNotNull(); + assertThat(report.version).isEqualTo("1"); + assertThat(report.file.size()).isEqualTo(1); + + GenericCoverageReport.GenericCoverageReportEntry fileEntry = report.file.get(0); + + assertThat(fileEntry.getPath()).isEqualTo(fileInfo.getPath().toString()); + } +} From 7caf3b04a49315c3900fadd39ab6791ff0d6cb1a Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Fri, 17 Apr 2020 12:10:38 +0300 Subject: [PATCH 109/444] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4=20=D0=BD=D0=B0=20picocli?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle.kts | 4 + .../bsl/languageserver/BSLLSPLauncher.java | 200 +++++++----------- .../languageserver/cli/AnalyzeCommand.java | 90 ++++++-- .../bsl/languageserver/cli/Command.java | 32 --- .../bsl/languageserver/cli/FormatCommand.java | 39 +++- .../bsl/languageserver/cli/HelpCommand.java | 54 ----- .../cli/LanguageServerStartCommand.java | 108 ---------- .../cli/ParseExceptionCommand.java | 54 ----- ...rsionCommand.java => VersionProvider.java} | 25 +-- .../languageserver/BSLLSPLauncherTest.java | 30 +-- .../cli/AnalyzeCommandTest.java | 66 ------ .../languageserver/cli/FormatCommandTest.java | 49 ----- .../languageserver/cli/HelpCommandTest.java | 38 ---- .../cli/LanguageServerStartCommandTest.java | 66 ------ .../cli/ParseExceptionCommandTest.java | 38 ---- .../cli/VersionCommandTest.java | 37 ---- 16 files changed, 202 insertions(+), 728 deletions(-) delete mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/Command.java delete mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/HelpCommand.java delete mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java delete mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/ParseExceptionCommand.java rename src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/{VersionCommand.java => VersionProvider.java} (72%) delete mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommandTest.java delete mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommandTest.java delete mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/HelpCommandTest.java delete mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommandTest.java delete mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/ParseExceptionCommandTest.java delete mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommandTest.java diff --git a/build.gradle.kts b/build.gradle.kts index 11e75582b2b..5311b31b78d 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -57,6 +57,10 @@ dependencies { // https://mvnrepository.com/artifact/commons-cli/commons-cli implementation("commons-cli", "commons-cli", "1.4") + + implementation("info.picocli", "picocli", "4.2.0") + annotationProcessor("info.picocli", "picocli", "4.2.0") + // https://mvnrepository.com/artifact/commons-io/commons-io implementation("commons-io", "commons-io", "2.6") implementation("org.apache.commons", "commons-lang3", "3.10") diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java index e8b394b2e04..3b8afbc16f7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java @@ -22,135 +22,97 @@ package com.github._1c_syntax.bsl.languageserver; import com.github._1c_syntax.bsl.languageserver.cli.AnalyzeCommand; -import com.github._1c_syntax.bsl.languageserver.cli.Command; import com.github._1c_syntax.bsl.languageserver.cli.FormatCommand; -import com.github._1c_syntax.bsl.languageserver.cli.HelpCommand; -import com.github._1c_syntax.bsl.languageserver.cli.LanguageServerStartCommand; -import com.github._1c_syntax.bsl.languageserver.cli.ParseExceptionCommand; -import com.github._1c_syntax.bsl.languageserver.cli.VersionCommand; -import com.google.common.annotations.VisibleForTesting; -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.CommandLineParser; -import org.apache.commons.cli.DefaultParser; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; +import com.github._1c_syntax.bsl.languageserver.cli.VersionProvider; +import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.lsp4j.jsonrpc.Launcher; +import org.eclipse.lsp4j.launch.LSPLauncher; +import org.eclipse.lsp4j.services.LanguageClient; +import org.eclipse.lsp4j.services.LanguageClientAware; +import org.eclipse.lsp4j.services.LanguageServer; +import picocli.CommandLine; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.Callable; + +@Slf4j +@picocli.CommandLine.Command( + name = "", + description = "BSL language server on LSP server mode", + mixinStandardHelpOptions = true, + versionProvider = VersionProvider.class, + subcommands = { + AnalyzeCommand.class, + FormatCommand.class + }, + usageHelpAutoWidth = true, + footer = "@|green Copyright(c) 2018-2020|@", + header = "@|green BSL language server|@") +public class BSLLSPLauncher implements Callable { + + @picocli.CommandLine.Option( + names = {"-c", "--configuration"}, + description = "Path to language server configuration file", + paramLabel = "", + defaultValue = "") + private String configurationOption; -public class BSLLSPLauncher { + public static void main(String[] args) { + + int result = new CommandLine(new BSLLSPLauncher()).execute(args); + if (result >= 0) { + System.exit(result); + } + } - public static final String APP_NAME = "BSL language server"; + public Integer call() { + File configurationFile = new File(configurationOption); - private static final Options options = createOptions(); + LanguageServerConfiguration configuration = LanguageServerConfiguration.create(configurationFile); + LanguageServer server = new BSLLanguageServer(configuration); - public static void main(String[] args) { - CommandLineParser parser = new DefaultParser(); + Launcher launcher = getLanguageClientLauncher(server, configuration); - Command command; - try { - CommandLine cmd = parser.parse(options, args); - - if (cmd.hasOption("help")) { - command = new HelpCommand(options); - } else if (cmd.hasOption("version")) { - command = new VersionCommand(); - } else if (cmd.hasOption("analyze")) { - command = new AnalyzeCommand(cmd); - } else if (cmd.hasOption("format")) { - command = new FormatCommand(cmd); - } else { - command = new LanguageServerStartCommand(cmd); - } + LanguageClient client = launcher.getRemoteProxy(); + ((LanguageClientAware) server).connect(client); + + launcher.startListening(); + return -1; + } + + private static Launcher getLanguageClientLauncher( + LanguageServer server, + LanguageServerConfiguration configuration + ) { + InputStream in = System.in; + OutputStream out = System.out; - } catch (ParseException e) { - command = new ParseExceptionCommand(options, e); + File logFile = configuration.getTraceLog(); + if (logFile == null) { + return LSPLauncher.createServerLauncher(server, in, out); } - int result = command.execute(); - if (result >= 0) { - System.exit(result); + Launcher launcher; + + try { + PrintWriter printWriter = new PrintWriter(logFile, StandardCharsets.UTF_8.name()); + launcher = LSPLauncher.createServerLauncher(server, in, out, false, printWriter); + } catch (FileNotFoundException | UnsupportedEncodingException e) { + LOGGER.error("Can't create LSP trace file", e); + if (logFile.isDirectory()) { + LOGGER.error("Trace log setting must lead to file, not directory! {}", logFile.getAbsolutePath()); + } + + launcher = LSPLauncher.createServerLauncher(server, in, out); } - } - @VisibleForTesting - public static Options createOptions() { - Options createdOptions = new Options(); - - Option configurationOption = new Option( - "c", - "configuration", - true, - "Path to language server configuration file" - ); - configurationOption.setRequired(false); - - Option help = new Option( - "h", - "help", - false, - "Show help." - ); - - Option analyze = new Option( - "a", - "analyze", - false, - "Run analysis and get diagnostic info" - ); - - Option format = new Option( - "f", - "format", - false, - "Format files in source directory" - ); - - Option srcDir = new Option( - "s", - "srcDir", - true, - "Source directory" - ); - - Option reporter = new Option( - "r", - "reporter", - true, - "Reporter key" - ); - - Option outputDir = new Option( - "o", - "outputDir", - true, - "Output report directory" - ); - - Option version = new Option( - "v", - "version", - false, - "Show version." - ); - - Option silentMode = new Option( - "q", - "silent", - false, - "Silent mode" - ); - - createdOptions.addOption(analyze); - createdOptions.addOption(format); - createdOptions.addOption(srcDir); - createdOptions.addOption(outputDir); - createdOptions.addOption(reporter); - createdOptions.addOption(silentMode); - - createdOptions.addOption(configurationOption); - createdOptions.addOption(help); - createdOptions.addOption(version); - - return createdOptions; + return launcher; } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java index 638ef5c6334..ef04f4417dc 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java @@ -28,12 +28,17 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.DiagnosticSupplier; import com.github._1c_syntax.bsl.languageserver.diagnostics.FileInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.reporter.AnalysisInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.reporter.ConsoleReporter; +import com.github._1c_syntax.bsl.languageserver.diagnostics.reporter.GenericIssueReporter; +import com.github._1c_syntax.bsl.languageserver.diagnostics.reporter.JUnitReporter; +import com.github._1c_syntax.bsl.languageserver.diagnostics.reporter.JsonReporter; import com.github._1c_syntax.bsl.languageserver.diagnostics.reporter.ReportersAggregator; +import com.github._1c_syntax.bsl.languageserver.diagnostics.reporter.TSLintReporter; import com.github._1c_syntax.bsl.languageserver.providers.DiagnosticProvider; import com.github._1c_syntax.utils.Absolute; +import lombok.extern.slf4j.Slf4j; import me.tongfei.progressbar.ProgressBar; import me.tongfei.progressbar.ProgressBarStyle; -import org.apache.commons.cli.CommandLine; import org.apache.commons.io.FileUtils; import org.eclipse.lsp4j.Diagnostic; @@ -42,9 +47,12 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Optional; +import java.util.concurrent.Callable; import java.util.stream.Collectors; /** @@ -68,27 +76,74 @@ * Выводимая информация: * Выполняет анализ каталога исходных файлов и генерацию файлов отчета. Для каждого указанного ключа "Репортера" * создается отдельный файл (каталог файлов). Реализованные "репортеры" находятся в пакете "reporter". - */ -public class AnalyzeCommand implements Command { + **/ +@Slf4j +@picocli.CommandLine.Command( + name = "analyze", + aliases = {"-a", "--analyze"}, + description = "Run analysis and get diagnostic info", + mixinStandardHelpOptions = true, + usageHelpAutoWidth = true, + footer = "@|green Copyright(c) 2018-2020|@") +public class AnalyzeCommand implements Callable { + + private static class ReportersKeys extends ArrayList { + ReportersKeys() { + super(Arrays.asList( + ConsoleReporter.KEY, + JsonReporter.KEY, + JUnitReporter.KEY, + TSLintReporter.KEY, + GenericIssueReporter.KEY + )); + } + } + + @picocli.CommandLine.Option( + names = {"-s", "--srcDir"}, + description = "Source directory", + paramLabel = "", + defaultValue = "") + private String srcDirOption; + + @picocli.CommandLine.Option( + names = {"-o", "--outputDir"}, + description = "Output report directory", + paramLabel = "", + defaultValue = "") + private String outputDirOption; + + @picocli.CommandLine.Option( + names = {"-c", "--configuration"}, + description = "Path to language server configuration file", + paramLabel = "", + defaultValue = "") + private String configurationOption; + + @picocli.CommandLine.Option( + names = {"-r", "--reporter"}, + paramLabel = "", + completionCandidates = ReportersKeys.class, + description = "Reporter key (${COMPLETION-CANDIDATES})") + private String[] reportersOptions; + + @picocli.CommandLine.Option( + names = {"-q", "--silent"}, + description = "Silent mode") + private boolean silentMode; - private final CommandLine cmd; private DiagnosticProvider diagnosticProvider; private ServerContext context; - public AnalyzeCommand(CommandLine cmd) { - this.cmd = cmd; - } - - @Override - public int execute() { - String srcDirOption = cmd.getOptionValue("srcDir", ""); - String outputDirOption = cmd.getOptionValue("outputDir", ""); - String configurationOption = cmd.getOptionValue("configuration", ""); - boolean silentMode = cmd.hasOption("silent"); + public Integer call() { Path srcDir = Absolute.path(srcDirOption); - File configurationFile = new File(configurationOption); + if (!srcDir.toFile().exists()) { + LOGGER.error("Source dir `{}` is not exists", srcDir.toString()); + return 1; + } + File configurationFile = new File(configurationOption); LanguageServerConfiguration configuration = LanguageServerConfiguration.create(configurationFile); Path configurationPath = LanguageServerConfiguration.getCustomConfigurationRoot(configuration, srcDir); @@ -114,9 +169,9 @@ public int execute() { } } - AnalysisInfo analysisInfo = new AnalysisInfo(LocalDateTime.now(), fileInfos, srcDirOption); + AnalysisInfo analysisInfo = new AnalysisInfo(LocalDateTime.now(), fileInfos, srcDir.toString()); Path outputDir = Absolute.path(outputDirOption); - String[] reporters = Optional.ofNullable(cmd.getOptionValues("reporter")).orElse(new String[0]); + var reporters = Optional.ofNullable(reportersOptions).orElse(new String[0]); ReportersAggregator aggregator = new ReportersAggregator(outputDir, reporters); aggregator.report(analysisInfo); return 0; @@ -144,5 +199,4 @@ private FileInfo getFileInfoFromFile(Path srcDir, File file) { return fileInfo; } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/Command.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/Command.java deleted file mode 100644 index b235fd2b766..00000000000 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/Command.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * This file is a part of BSL Language Server. - * - * Copyright © 2018-2020 - * Alexey Sosnoviy , Nikita Gryzlov 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.cli; - -public interface Command { - - /** - * Execute given command. - * - * @return Result code. 0 - if success, >0 in case of error, <0 in case of pending multithreaded task. - */ - int execute(); -} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java index 99d6cc4e31d..c2aaa364e18 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java @@ -26,9 +26,9 @@ import com.github._1c_syntax.bsl.languageserver.providers.FormatProvider; import com.github._1c_syntax.utils.Absolute; import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; import me.tongfei.progressbar.ProgressBar; import me.tongfei.progressbar.ProgressBarStyle; -import org.apache.commons.cli.CommandLine; import org.apache.commons.io.FileUtils; import org.eclipse.lsp4j.DocumentFormattingParams; import org.eclipse.lsp4j.FormattingOptions; @@ -40,6 +40,7 @@ import java.nio.file.Path; import java.util.Collection; import java.util.List; +import java.util.concurrent.Callable; /** * Форматирование кода в исходниках @@ -54,24 +55,42 @@ * Выполняет форматирование исходного кода в файлах каталога. Для форматирования используются правила и настройки * "форматтера" FormatProvider, т.е. пользователь никак не может овлиять на результат. */ -public class FormatCommand implements Command { +@Slf4j +@picocli.CommandLine.Command( + name = "format", + aliases = {"-f", "--format"}, + description = "Format files in source directory", + mixinStandardHelpOptions = true, + usageHelpAutoWidth = true, + footer = "@|green Copyright(c) 2018-2020|@") +public class FormatCommand implements Callable { - private final CommandLine cmd; private final ServerContext serverContext; - public FormatCommand(CommandLine cmd) { - this.cmd = cmd; + @picocli.CommandLine.Option( + names = {"-s", "--srcDir"}, + description = "Source directory", + paramLabel = "", + defaultValue = "") + private String srcDirOption; + + @picocli.CommandLine.Option( + names = {"-q", "--silent"}, + description = "Silent mode") + private boolean silentMode; + + public FormatCommand() { this.serverContext = new ServerContext(); } - @Override - public int execute() { + public Integer call() { serverContext.clear(); - String srcDirOption = cmd.getOptionValue("srcDir", ""); - boolean silentMode = cmd.hasOption("silent"); - Path srcDir = Absolute.path(srcDirOption); + if (!srcDir.toFile().exists()) { + LOGGER.error("Source dir `{}` is not exists", srcDir.toString()); + return 1; + } Collection files = FileUtils.listFiles(srcDir.toFile(), new String[]{"bsl", "os"}, true); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/HelpCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/HelpCommand.java deleted file mode 100644 index 305af224e64..00000000000 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/HelpCommand.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * This file is a part of BSL Language Server. - * - * Copyright © 2018-2020 - * Alexey Sosnoviy , Nikita Gryzlov 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.cli; - -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Options; - -import static com.github._1c_syntax.bsl.languageserver.BSLLSPLauncher.APP_NAME; - -/** - * Вывод справки - * Ключ команды: - * -h, (--help) - * Параметры: - * Без параметров - * Выводимая информация: - * Выводит справку консольного приложения - * - */ -public class HelpCommand implements Command { - - private final Options options; - - public HelpCommand(Options options) { - this.options = options; - } - - @Override - public int execute() { - HelpFormatter formatter = new HelpFormatter(); - - formatter.printHelp(APP_NAME, options, true); - return 0; - } -} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java deleted file mode 100644 index d75ada08096..00000000000 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * This file is a part of BSL Language Server. - * - * Copyright © 2018-2020 - * Alexey Sosnoviy , Nikita Gryzlov 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.cli; - -import com.github._1c_syntax.bsl.languageserver.BSLLanguageServer; -import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.cli.CommandLine; -import org.eclipse.lsp4j.jsonrpc.Launcher; -import org.eclipse.lsp4j.launch.LSPLauncher; -import org.eclipse.lsp4j.services.LanguageClient; -import org.eclipse.lsp4j.services.LanguageClientAware; -import org.eclipse.lsp4j.services.LanguageServer; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; - -/** - * Запускает приложение в режиме Language Server - * Ключ команды: - * без ключа - * Параметры: - * -c, (--configuration) <arg> - Путь к конфигурационному файлу BSL Language Server (.bsl-language-server.json). - * Возможно указывать как в абсолютном, так и относительном виде. Если параметр опущен, - * то будут использованы настройки по умолчанию. - * Выводимая информация: - * Данный режим используется для взаимодействия с клиентом по протоколу LSP. - */ -@Slf4j -public class LanguageServerStartCommand implements Command { - - private final CommandLine cmd; - - public LanguageServerStartCommand(CommandLine cmd) { - this.cmd = cmd; - } - - @Override - public int execute() { - - String configurationOption = cmd.getOptionValue("configuration", ""); - File configurationFile = new File(configurationOption); - - LanguageServerConfiguration configuration = LanguageServerConfiguration.create(configurationFile); - LanguageServer server = new BSLLanguageServer(configuration); - - Launcher launcher = getLanguageClientLauncher(server, configuration); - - LanguageClient client = launcher.getRemoteProxy(); - ((LanguageClientAware) server).connect(client); - - launcher.startListening(); - return -1; - } - - private static Launcher getLanguageClientLauncher( - LanguageServer server, - LanguageServerConfiguration configuration - ) { - InputStream in = System.in; - OutputStream out = System.out; - - File logFile = configuration.getTraceLog(); - if (logFile == null) { - return LSPLauncher.createServerLauncher(server, in, out); - } - - Launcher launcher; - - try { - PrintWriter printWriter = new PrintWriter(logFile, StandardCharsets.UTF_8.name()); - launcher = LSPLauncher.createServerLauncher(server, in, out, false, printWriter); - } catch (FileNotFoundException | UnsupportedEncodingException e) { - LOGGER.error("Can't create LSP trace file", e); - if (logFile.isDirectory()) { - LOGGER.error("Trace log setting must lead to file, not directory! {}", logFile.getAbsolutePath()); - } - - launcher = LSPLauncher.createServerLauncher(server, in, out); - } - - return launcher; - } -} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/ParseExceptionCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/ParseExceptionCommand.java deleted file mode 100644 index 6896ed6d245..00000000000 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/ParseExceptionCommand.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * This file is a part of BSL Language Server. - * - * Copyright © 2018-2020 - * Alexey Sosnoviy , Nikita Gryzlov 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.cli; - -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; - -import static com.github._1c_syntax.bsl.languageserver.BSLLSPLauncher.APP_NAME; - -/** - * Служебный класс для обработки некорректных параметров командной строки - */ -@Slf4j -public class ParseExceptionCommand implements Command { - - private final Options options; - private final ParseException e; - - public ParseExceptionCommand(Options options, ParseException e) { - this.options = options; - this.e = e; - } - - @Override - public int execute() { - HelpFormatter formatter = new HelpFormatter(); - - LOGGER.error(e.getMessage()); - formatter.printHelp(APP_NAME, options, true); - - return 1; - } -} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionProvider.java similarity index 72% rename from src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java rename to src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionProvider.java index 3a5c4379deb..249813a7308 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionProvider.java @@ -22,6 +22,7 @@ package com.github._1c_syntax.bsl.languageserver.cli; import lombok.extern.slf4j.Slf4j; +import picocli.CommandLine; import java.io.IOException; import java.io.InputStream; @@ -29,20 +30,13 @@ import java.util.jar.Manifest; /** - * Вывод версии приложения - * Ключ команды: - * -v, (--version) - * Параметры: - * Без параметров - * Выводимая информация: - * Выводит версию приожения в консоль в формате "version: version_bslls" + * Читает версию из манифеста и формирует строку-версию приложения */ @Slf4j -public class VersionCommand implements Command { +public class VersionProvider implements CommandLine.IVersionProvider { @Override - public int execute() { - + public String[] getVersion() { final InputStream mfStream = Thread.currentThread() .getContextClassLoader() .getResourceAsStream("META-INF/MANIFEST.MF"); @@ -52,12 +46,13 @@ public int execute() { manifest.read(mfStream); } catch (IOException e) { LOGGER.error("Can't read manifest", e); + return new String[0]; } - System.out.print(String.format( - "version: %s%n", - manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION) - )); - return 0; + return new String[]{ + String.format( + "version: %s%n", + manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION) + )}; } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java index 317d30ce095..618cdb582ea 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java @@ -51,25 +51,7 @@ void restoreStreams() { } @Test - @ExpectSystemExitWithStatus(0) - void testHelp() { - // given - String[] args = new String[]{"--help"}; - - - // when - try { - BSLLSPLauncher.main(args); - } catch (RuntimeException ignored) { - // catch prevented system.exit call - } - - // then - assertThat(outContent.toString()).containsIgnoringCase("usage: "); - } - - @Test - @ExpectSystemExitWithStatus(1) + @ExpectSystemExitWithStatus(2) void testParseError() { // given String[] args = new String[]{"--error"}; @@ -82,14 +64,14 @@ void testParseError() { } // then - assertThat(errContent.toString()).containsIgnoringCase("Unrecognized option: --error"); + assertThat(errContent.toString()).containsIgnoringCase("Unknown option: '--error'"); } @Test @ExpectSystemExitWithStatus(0) void testAnalyze() { // given - String[] args = new String[]{"--analyze", "--srcDir", "./src/test/resources/cli"}; + String[] args = "--analyze --srcDir ./src/test/resources/cli".split(" "); // when try { @@ -109,7 +91,7 @@ void testAnalyze() { @ExpectSystemExitWithStatus(0) void testAnalyzeSilent() { // given - String[] args = new String[]{"--analyze", "--srcDir", "./src/test/resources/cli", "-q"}; + String[] args = "--analyze --srcDir ./src/test/resources/cli -q".split(" "); // when try { @@ -128,7 +110,7 @@ void testAnalyzeSilent() { @ExpectSystemExitWithStatus(0) void testFormat() { // given - String[] args = new String[]{"--format", "--srcDir", "./src/test/resources/cli"}; + String[] args = "--format --srcDir ./src/test/resources/cli".split(" "); // when try { @@ -148,7 +130,7 @@ void testFormat() { @ExpectSystemExitWithStatus(0) void testFormatSilent() { // given - String[] args = new String[]{"--format", "--srcDir", "./src/test/resources/cli", "-q"}; + String[] args = "--format --srcDir ./src/test/resources/cli -q".split(" "); // when try { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommandTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommandTest.java deleted file mode 100644 index 7b5da125798..00000000000 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommandTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * This file is a part of BSL Language Server. - * - * Copyright © 2018-2020 - * Alexey Sosnoviy , Nikita Gryzlov 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.cli; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.DefaultParser; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.junit.jupiter.api.Test; - -import static com.github._1c_syntax.bsl.languageserver.BSLLSPLauncher.createOptions; -import static org.assertj.core.api.Assertions.assertThat; - -class AnalyzeCommandTest { - - @Test - void testExecute() throws ParseException { - Options options = createOptions(); - - DefaultParser parser = new DefaultParser(); - CommandLine commandLine = parser.parse(options, new String[]{"-s", "./src/test/resources/cli"}); - - Command command = new AnalyzeCommand(commandLine); - - int result = command.execute(); - - assertThat(result).isEqualTo(0); - } - - @Test - void testExecuteWithMetadata() throws ParseException { - - Options options = createOptions(); - - DefaultParser parser = new DefaultParser(); - CommandLine commandLine = parser.parse( - options, new String[]{"-s", "./src/test/resources/metadata"}); - - Command command = new AnalyzeCommand(commandLine); - - int result = command.execute(); - - assertThat(result).isEqualTo(0); - - } - -} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommandTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommandTest.java deleted file mode 100644 index b06a39f8b1e..00000000000 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommandTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * This file is a part of BSL Language Server. - * - * Copyright © 2018-2020 - * Alexey Sosnoviy , Nikita Gryzlov 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.cli; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.DefaultParser; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.junit.jupiter.api.Test; - -import static com.github._1c_syntax.bsl.languageserver.BSLLSPLauncher.createOptions; -import static org.assertj.core.api.Assertions.assertThat; - -class FormatCommandTest { - - @Test - void testExecute() throws ParseException { - Options options = createOptions(); - - DefaultParser parser = new DefaultParser(); - CommandLine commandLine = parser.parse(options, new String[]{"-s", "./src/test/resources/cli"}); - - Command command = new FormatCommand(commandLine); - - int result = command.execute(); - - assertThat(result).isEqualTo(0); - } - -} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/HelpCommandTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/HelpCommandTest.java deleted file mode 100644 index 7e0f7f37280..00000000000 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/HelpCommandTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * This file is a part of BSL Language Server. - * - * Copyright © 2018-2020 - * Alexey Sosnoviy , Nikita Gryzlov 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.cli; - -import org.junit.jupiter.api.Test; - -import static com.github._1c_syntax.bsl.languageserver.BSLLSPLauncher.createOptions; -import static org.assertj.core.api.Assertions.assertThat; - -class HelpCommandTest { - - @Test - void testExecute() { - Command command = new HelpCommand(createOptions()); - int result = command.execute(); - - assertThat(result).isEqualTo(0); - } -} \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommandTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommandTest.java deleted file mode 100644 index 45962c1eef7..00000000000 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommandTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * This file is a part of BSL Language Server. - * - * Copyright © 2018-2020 - * Alexey Sosnoviy , Nikita Gryzlov 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.cli; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.DefaultParser; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; - -import static com.github._1c_syntax.bsl.languageserver.BSLLSPLauncher.createOptions; -import static org.assertj.core.api.Assertions.assertThat; - -class LanguageServerStartCommandTest { - - @BeforeEach - void startUp() throws IOException { - Files.deleteIfExists(Paths.get("build/.trace.log")); - } - - @Test - void testExecute() throws ParseException { - Options options = createOptions(); - DefaultParser parser = new DefaultParser(); - CommandLine commandLine = parser.parse(options, new String[]{}); - Command command = new LanguageServerStartCommand(commandLine); - - int result = command.execute(); - assertThat(result).isEqualTo(-1); - } - - @Test - void testExecuteWithConfigurationFile() throws ParseException { - Options options = createOptions(); - DefaultParser parser = new DefaultParser(); - CommandLine commandLine = parser.parse(options, new String[]{"-c", "src/test/resources/.bsl-language-server.json"}); - Command command = new LanguageServerStartCommand(commandLine); - - int result = command.execute(); - assertThat(result).isEqualTo(-1); - } -} \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/ParseExceptionCommandTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/ParseExceptionCommandTest.java deleted file mode 100644 index eba9e049f35..00000000000 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/ParseExceptionCommandTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * This file is a part of BSL Language Server. - * - * Copyright © 2018-2020 - * Alexey Sosnoviy , Nikita Gryzlov 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.cli; - -import org.apache.commons.cli.ParseException; -import org.junit.jupiter.api.Test; - -import static com.github._1c_syntax.bsl.languageserver.BSLLSPLauncher.createOptions; -import static org.assertj.core.api.Assertions.assertThat; - -class ParseExceptionCommandTest { - - @Test - void testExecute() { - Command command = new ParseExceptionCommand(createOptions(), new ParseException("")); - int result = command.execute(); - assertThat(result).isEqualTo(1); - } -} \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommandTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommandTest.java deleted file mode 100644 index 1b0ec2c7c47..00000000000 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommandTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * This file is a part of BSL Language Server. - * - * Copyright © 2018-2020 - * Alexey Sosnoviy , Nikita Gryzlov 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.cli; - -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -class VersionCommandTest { - - @Test - void testExecute() { - Command command = new VersionCommand(); - int result = command.execute(); - - assertThat(result).isEqualTo(0); - } -} \ No newline at end of file From 8957952db7241815b269d419ceaed82f48183ca2 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Fri, 17 Apr 2020 12:19:39 +0300 Subject: [PATCH 110/444] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D1=82=D0=B0=D1=86=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 59 +++++++++++++++++++++++++++++++++++------------- docs/en/index.md | 50 ++++++++++++++++++++++++++++++---------- docs/index.md | 49 ++++++++++++++++++++++++++++++---------- 3 files changed, 118 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index aea179d9510..cc07bb490f7 100644 --- a/README.md +++ b/README.md @@ -38,29 +38,43 @@ ```sh java -jar bsl-language-server.jar --help -usage: BSL language server [-a] [-c ] [-f] [-h] [-o ] [-r ] [-s ] - -a,--analyze Run analysis and get diagnostic info - -c,--configuration Path to language server configuration file - -f,--format Format files in source directory - -h,--help Show help. - -o,--outputDir Output report directory - -r,--reporter Reporter key - -s,--srcDir Source directory - -v,--version Version - -q,--silent Silent mode +BSL language server +Usage: [-hV] [-c=] [COMMAND] +BSL language server on LSP server mode + -c, --configuration= + Path to language server configuration file + -h, --help Show this help message and exit. + -V, --version Print version information and exit. +Commands: + analyze, -a, --analyze Run analysis and get diagnostic info + format, -f, --format Format files in source directory ``` -При запуске BSL Language Server в обычном режиме будет запущен сам Language Server, взаимодействующий по протоколу [LSP](https://microsoft.github.io/language-server-protocol/). Для взаимодействия используются stdin и stdout. +При запуске BSL Language Server в обычном режиме будет запущен сам Language Server, взаимодействующий по протоколу [LSP]([language server protocol](https://microsoft.github.io/language-server-protocol/)). Для взаимодействия используются stdin и stdout. По умолчанию тексты диагностик выдаются на русском языке. Для переключения языка сообщений от движка диагностик необходимо настроить параметр `diagnosticLanguage` в конфигурационном файле или вызвав событие `workspace/didChangeConfiguration`: + + ## Запуск в режиме анализатора -Для запуска в режиме анализа используется параметр `--analyze` (сокращенно `-a`). Для указания каталога расположения анализируемых исходников используется параметр `--srcDir` (сокращенно `-s`), за которым следует путь (относительный или абсолютный) к каталогу исходников. +Для запуска в режиме анализа используется параметр `--analyze` (сокращенно `-a`). -Для формирования отчета об анализе требуется указать один или "репортеров". Для указания репортера используется параметр `--reporter` (сокращенно `-r`), за которым следует ключ репортера. Допустимо указывать несколько репортеров. +```sh +Usage: analyze [-hqV] [-c=] [-o=] [-s=] [-r=]... +Run analysis and get diagnostic info + -c, --configuration= + Path to language server configuration file + -h, --help Show this help message and exit. + -o, --outputDir= Output report directory + -q, --silent Silent mode + -r, --reporter= Reporter key (console, json, junit, tslint, generic) + -s, --srcDir= Source directory + -V, --version Print version information and exit. +``` -Список и описания репортеров, диагностик, конфигурационного файла доступны [на сайте проекта](https://1c-syntax.github.io/bsl-language-server/). +Для указания каталога расположения анализируемых исходников используется параметр `--srcDir` (сокращенно `-s`), за которым следует путь (относительный или абсолютный) к каталогу исходников. +Для формирования отчета об анализе требуется указать один или "репортеров". Для указания репортера используется параметр `--reporter` (сокращенно `-r`), за которым следует ключ репортера. Допустимо указывать несколько репортеров. Список репортетов см. в разделе **Репортеры**. Пример строки запуска анализа: @@ -74,11 +88,24 @@ java -jar bsl-language-server.jar --analyze --srcDir ./src/cf --reporter json java -Xmx4g -jar bsl-language-server.jar ...остальные параметры ``` + + ## Запуск в режиме форматтера -Для запуска в режиме форматтера используется параметр `--format` (сокращенно `-f`). Для указания каталога расположения форматируемых исходников используется параметр `--srcDir` (сокращенно `-s`), за которым следует путь (относительный или абсолютный) к каталогу исходников. +Для запуска в режиме форматтера используется параметр `--format` (сокращенно `-f`). -Пример строки запуска анализа: +```sh +Usage: format [-hqV] [-s=] +Format files in source directory + -h, --help Show this help message and exit. + -q, --silent Silent mode + -s, --srcDir= Source directory + -V, --version Print version information and exit. +``` + +Для указания каталога расположения форматируемых исходников используется параметр `--srcDir` (сокращенно `-s`), за которым следует путь (относительный или абсолютный) к каталогу исходников. + +Пример строки запуска форматирования: ```sh java -jar bsl-language-server.jar --format --srcDir ./src/cf diff --git a/docs/en/index.md b/docs/en/index.md index 6d46285df71..2ae9bc07e1f 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -49,16 +49,16 @@ jar-files run through `java -jar path/to/file.jar`. ```sh java -jar bsl-language-server.jar --help -usage: BSL language server [-a] [-c ] [-f] [-h] [-o ] [-r ] [-s ] - -a,--analyze Run analysis and get diagnostic info - -c,--configuration Path to language server configuration file - -f,--format Format files in source directory - -h,--help Show help. - -o,--outputDir Output report directory - -r,--reporter Reporter key - -s,--srcDir Source directory - -v,--version Version - -q,--silent Silent mode +BSL language server +Usage: [-hV] [-c=] [COMMAND] +BSL language server on LSP server mode + -c, --configuration= + Path to language server configuration file + -h, --help Show this help message and exit. + -V, --version Print version information and exit. +Commands: + analyze, -a, --analyze Run analysis and get diagnostic info + format, -f, --format Format files in source directory ``` Starting BSL Language Server in standard mode will run the Language Server communicating via [LSP]([language server protocol](https://microsoft.github.io/language-server-protocol/)). stdin and stdout are used for communication. @@ -69,7 +69,22 @@ By default diagnostics texts are displayed in Russian. To switch the diagnostics ## Run in analyzer mode -To run in analyzer mode use parameter `--analyze` (short `-a`). To set source code folder for analysis use parameter `--srcDir` (short `-s`) followed by the path (relative or absolute) to the source code folder. +To run in analyzer mode use parameter `--analyze` (short `-a`). + +```sh +Usage: analyze [-hqV] [-c=] [-o=] [-s=] [-r=]... +Run analysis and get diagnostic info + -c, --configuration= + Path to language server configuration file + -h, --help Show this help message and exit. + -o, --outputDir= Output report directory + -q, --silent Silent mode + -r, --reporter= Reporter key (console, json, junit, tslint, generic) + -s, --srcDir= Source directory + -V, --version Print version information and exit. +``` + +To set source code folder for analysis use parameter `--srcDir` (short `-s`) followed by the path (relative or absolute) to the source code folder. To generate an analysis report you need to specify one or more reporters. To specify reporter use parameter `--reporter` or `-r`, followed by reporter key. You may specify several reporters. The list of reporters see in section **Reporters**. @@ -89,7 +104,18 @@ java -Xmx4g -jar bsl-language-server.jar ... other parameters ## Run in formatter mode -To run in formatter mode use parameter `--format` (short `-f`). To set source code folder for formatting use parameter `--srcDir` (short `-s`) followed by the path (relative or absolute) to the source code folder. +To run in formatter mode use parameter `--format` (short `-f`). + +```sh +Usage: format [-hqV] [-s=] +Format files in source directory + -h, --help Show this help message and exit. + -q, --silent Silent mode + -s, --srcDir= Source directory + -V, --version Print version information and exit. +``` + +To set source code folder for formatting use parameter `--srcDir` (short `-s`) followed by the path (relative or absolute) to the source code folder. Command line example to run formatting: diff --git a/docs/index.md b/docs/index.md index 20e94187313..1ea90b4c02f 100644 --- a/docs/index.md +++ b/docs/index.md @@ -49,16 +49,16 @@ ```sh java -jar bsl-language-server.jar --help -usage: BSL language server [-a] [-c ] [-f] [-h] [-o ] [-r ] [-s ] - -a,--analyze Run analysis and get diagnostic info - -c,--configuration Path to language server configuration file - -f,--format Format files in source directory - -h,--help Show help. - -o,--outputDir Output report directory - -r,--reporter Reporter key - -s,--srcDir Source directory - -v,--version Version - -q,--silent Silent mode +BSL language server +Usage: [-hV] [-c=] [COMMAND] +BSL language server on LSP server mode + -c, --configuration= + Path to language server configuration file + -h, --help Show this help message and exit. + -V, --version Print version information and exit. +Commands: + analyze, -a, --analyze Run analysis and get diagnostic info + format, -f, --format Format files in source directory ``` При запуске BSL Language Server в обычном режиме будет запущен сам Language Server, взаимодействующий по протоколу [LSP]([language server protocol](https://microsoft.github.io/language-server-protocol/)). Для взаимодействия используются stdin и stdout. @@ -69,8 +69,22 @@ usage: BSL language server [-a] [-c ] [-f] [-h] [-o ] [-r ] [-s < ## Запуск в режиме анализатора -Для запуска в режиме анализа используется параметр `--analyze` (сокращенно `-a`). Для указания каталога расположения анализируемых исходников используется параметр `--srcDir` (сокращенно `-s`), за которым следует путь (относительный или абсолютный) к каталогу исходников. +Для запуска в режиме анализа используется параметр `--analyze` (сокращенно `-a`). +```sh +Usage: analyze [-hqV] [-c=] [-o=] [-s=] [-r=]... +Run analysis and get diagnostic info + -c, --configuration= + Path to language server configuration file + -h, --help Show this help message and exit. + -o, --outputDir= Output report directory + -q, --silent Silent mode + -r, --reporter= Reporter key (console, json, junit, tslint, generic) + -s, --srcDir= Source directory + -V, --version Print version information and exit. +``` + +Для указания каталога расположения анализируемых исходников используется параметр `--srcDir` (сокращенно `-s`), за которым следует путь (относительный или абсолютный) к каталогу исходников. Для формирования отчета об анализе требуется указать один или "репортеров". Для указания репортера используется параметр `--reporter` (сокращенно `-r`), за которым следует ключ репортера. Допустимо указывать несколько репортеров. Список репортетов см. в разделе **Репортеры**. Пример строки запуска анализа: @@ -89,7 +103,18 @@ java -Xmx4g -jar bsl-language-server.jar ...остальные параметр ## Запуск в режиме форматтера -Для запуска в режиме форматтера используется параметр `--format` (сокращенно `-f`). Для указания каталога расположения форматируемых исходников используется параметр `--srcDir` (сокращенно `-s`), за которым следует путь (относительный или абсолютный) к каталогу исходников. +Для запуска в режиме форматтера используется параметр `--format` (сокращенно `-f`). + +```sh +Usage: format [-hqV] [-s=] +Format files in source directory + -h, --help Show this help message and exit. + -q, --silent Silent mode + -s, --srcDir= Source directory + -V, --version Print version information and exit. +``` + +Для указания каталога расположения форматируемых исходников используется параметр `--srcDir` (сокращенно `-s`), за которым следует путь (относительный или абсолютный) к каталогу исходников. Пример строки запуска форматирования: From 7f08faaefc2c6c2732c225f50114df0ed610b478 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Fri, 17 Apr 2020 13:32:26 +0300 Subject: [PATCH 111/444] =?UTF-8?q?=D0=94=D0=9E=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=B2=D0=B5=D1=80=D1=81=D0=B8=D1=8E=20=D0=BA=D0=B0?= =?UTF-8?q?=D0=BA=20=D1=81=D0=B0=D0=BC=D0=BE=D1=81=D1=82=D0=BE=D1=8F=D1=82?= =?UTF-8?q?=D0=B5=D0=BB=D1=8C=D0=BD=D1=83=D1=8E=20=D0=BA=D0=BE=D0=BC=D0=B0?= =?UTF-8?q?=D0=BD=D0=B4=D1=83=20=D0=B8=20=D0=BE=D1=82=D0=BA=D0=BB=D1=8E?= =?UTF-8?q?=D1=87=D0=B8=D0=BB=20=D0=B0=D0=B2=D1=82=D0=BE=D0=BC=D0=B0=D1=82?= =?UTF-8?q?=D0=B8=D1=87=D0=B5=D1=81=D0=BA=D0=BE=D0=B5=20=D0=B4=D0=BE=D0=B0?= =?UTF-8?q?=D0=B2=D0=B1=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B2=D1=81=D1=82?= =?UTF-8?q?=D1=80=D0=BE=D0=B5=D0=BD=D0=BD=D0=BE=D0=B9=20=D0=BA=D0=BE=D0=BC?= =?UTF-8?q?=D0=B0=D0=BD=D0=B4=D1=8B=20=D0=B2=D0=B5=D1=80=D1=81=D0=B8=D0=B8?= =?UTF-8?q?=20=D0=B4=D0=BB=D1=8F=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 23 +++++++++--------- docs/en/index.md | 23 +++++++++--------- docs/index.md | 23 +++++++++--------- .../bsl/languageserver/BSLLSPLauncher.java | 14 +++++++---- .../languageserver/cli/AnalyzeCommand.java | 10 ++++++-- .../bsl/languageserver/cli/FormatCommand.java | 9 +++++-- ...rsionProvider.java => VersionCommand.java} | 24 +++++++++++++------ .../languageserver/BSLLSPLauncherTest.java | 23 ++++++++++++++++-- 8 files changed, 96 insertions(+), 53 deletions(-) rename src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/{VersionProvider.java => VersionCommand.java} (76%) diff --git a/README.md b/README.md index cc07bb490f7..1ebd58b3e3c 100644 --- a/README.md +++ b/README.md @@ -39,15 +39,15 @@ java -jar bsl-language-server.jar --help BSL language server -Usage: [-hV] [-c=] [COMMAND] +Usage: [-h] [-c=] [COMMAND [ARGS]] BSL language server on LSP server mode -c, --configuration= - Path to language server configuration file - -h, --help Show this help message and exit. - -V, --version Print version information and exit. + Path to language server configuration file + -h, --help Show this help message and exit Commands: analyze, -a, --analyze Run analysis and get diagnostic info format, -f, --format Format files in source directory + version, -v, --version Print version ``` При запуске BSL Language Server в обычном режиме будет запущен сам Language Server, взаимодействующий по протоколу [LSP]([language server protocol](https://microsoft.github.io/language-server-protocol/)). Для взаимодействия используются stdin и stdout. @@ -61,16 +61,16 @@ Commands: Для запуска в режиме анализа используется параметр `--analyze` (сокращенно `-a`). ```sh -Usage: analyze [-hqV] [-c=] [-o=] [-s=] [-r=]... +Usage: analyze [-h] [--silent] [-c=] [-o=] [-s=] + [-r=]... Run analysis and get diagnostic info -c, --configuration= Path to language server configuration file - -h, --help Show this help message and exit. + -h, --help Show this help message and exit -o, --outputDir= Output report directory - -q, --silent Silent mode -r, --reporter= Reporter key (console, json, junit, tslint, generic) -s, --srcDir= Source directory - -V, --version Print version information and exit. + --silent Silent mode ``` Для указания каталога расположения анализируемых исходников используется параметр `--srcDir` (сокращенно `-s`), за которым следует путь (относительный или абсолютный) к каталогу исходников. @@ -95,12 +95,11 @@ java -Xmx4g -jar bsl-language-server.jar ...остальные параметр Для запуска в режиме форматтера используется параметр `--format` (сокращенно `-f`). ```sh -Usage: format [-hqV] [-s=] +Usage: format [-h] [--silent] [-s=] Format files in source directory - -h, --help Show this help message and exit. - -q, --silent Silent mode + -h, --help Show this help message and exit -s, --srcDir= Source directory - -V, --version Print version information and exit. + --silent Silent mode ``` Для указания каталога расположения форматируемых исходников используется параметр `--srcDir` (сокращенно `-s`), за которым следует путь (относительный или абсолютный) к каталогу исходников. diff --git a/docs/en/index.md b/docs/en/index.md index 2ae9bc07e1f..3e381864672 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -50,15 +50,15 @@ jar-files run through `java -jar path/to/file.jar`. java -jar bsl-language-server.jar --help BSL language server -Usage: [-hV] [-c=] [COMMAND] +Usage: [-h] [-c=] [COMMAND [ARGS]] BSL language server on LSP server mode -c, --configuration= - Path to language server configuration file - -h, --help Show this help message and exit. - -V, --version Print version information and exit. + Path to language server configuration file + -h, --help Show this help message and exit Commands: analyze, -a, --analyze Run analysis and get diagnostic info format, -f, --format Format files in source directory + version, -v, --version Print version ``` Starting BSL Language Server in standard mode will run the Language Server communicating via [LSP]([language server protocol](https://microsoft.github.io/language-server-protocol/)). stdin and stdout are used for communication. @@ -72,16 +72,16 @@ By default diagnostics texts are displayed in Russian. To switch the diagnostics To run in analyzer mode use parameter `--analyze` (short `-a`). ```sh -Usage: analyze [-hqV] [-c=] [-o=] [-s=] [-r=]... +Usage: analyze [-h] [--silent] [-c=] [-o=] [-s=] + [-r=]... Run analysis and get diagnostic info -c, --configuration= Path to language server configuration file - -h, --help Show this help message and exit. + -h, --help Show this help message and exit -o, --outputDir= Output report directory - -q, --silent Silent mode -r, --reporter= Reporter key (console, json, junit, tslint, generic) -s, --srcDir= Source directory - -V, --version Print version information and exit. + --silent Silent mode ``` To set source code folder for analysis use parameter `--srcDir` (short `-s`) followed by the path (relative or absolute) to the source code folder. @@ -107,12 +107,11 @@ java -Xmx4g -jar bsl-language-server.jar ... other parameters To run in formatter mode use parameter `--format` (short `-f`). ```sh -Usage: format [-hqV] [-s=] +Usage: format [-h] [--silent] [-s=] Format files in source directory - -h, --help Show this help message and exit. - -q, --silent Silent mode + -h, --help Show this help message and exit -s, --srcDir= Source directory - -V, --version Print version information and exit. + --silent Silent mode ``` To set source code folder for formatting use parameter `--srcDir` (short `-s`) followed by the path (relative or absolute) to the source code folder. diff --git a/docs/index.md b/docs/index.md index 1ea90b4c02f..f220196ce59 100644 --- a/docs/index.md +++ b/docs/index.md @@ -50,15 +50,15 @@ java -jar bsl-language-server.jar --help BSL language server -Usage: [-hV] [-c=] [COMMAND] +Usage: [-h] [-c=] [COMMAND [ARGS]] BSL language server on LSP server mode -c, --configuration= - Path to language server configuration file - -h, --help Show this help message and exit. - -V, --version Print version information and exit. + Path to language server configuration file + -h, --help Show this help message and exit Commands: analyze, -a, --analyze Run analysis and get diagnostic info format, -f, --format Format files in source directory + version, -v, --version Print version ``` При запуске BSL Language Server в обычном режиме будет запущен сам Language Server, взаимодействующий по протоколу [LSP]([language server protocol](https://microsoft.github.io/language-server-protocol/)). Для взаимодействия используются stdin и stdout. @@ -72,16 +72,16 @@ Commands: Для запуска в режиме анализа используется параметр `--analyze` (сокращенно `-a`). ```sh -Usage: analyze [-hqV] [-c=] [-o=] [-s=] [-r=]... +Usage: analyze [-h] [--silent] [-c=] [-o=] [-s=] + [-r=]... Run analysis and get diagnostic info -c, --configuration= Path to language server configuration file - -h, --help Show this help message and exit. + -h, --help Show this help message and exit -o, --outputDir= Output report directory - -q, --silent Silent mode -r, --reporter= Reporter key (console, json, junit, tslint, generic) -s, --srcDir= Source directory - -V, --version Print version information and exit. + --silent Silent mode ``` Для указания каталога расположения анализируемых исходников используется параметр `--srcDir` (сокращенно `-s`), за которым следует путь (относительный или абсолютный) к каталогу исходников. @@ -106,12 +106,11 @@ java -Xmx4g -jar bsl-language-server.jar ...остальные параметр Для запуска в режиме форматтера используется параметр `--format` (сокращенно `-f`). ```sh -Usage: format [-hqV] [-s=] +Usage: format [-h] [--silent] [-s=] Format files in source directory - -h, --help Show this help message and exit. - -q, --silent Silent mode + -h, --help Show this help message and exit -s, --srcDir= Source directory - -V, --version Print version information and exit. + --silent Silent mode ``` Для указания каталога расположения форматируемых исходников используется параметр `--srcDir` (сокращенно `-s`), за которым следует путь (относительный или абсолютный) к каталогу исходников. diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java index 3b8afbc16f7..843daeb03db 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java @@ -23,7 +23,7 @@ import com.github._1c_syntax.bsl.languageserver.cli.AnalyzeCommand; import com.github._1c_syntax.bsl.languageserver.cli.FormatCommand; -import com.github._1c_syntax.bsl.languageserver.cli.VersionProvider; +import com.github._1c_syntax.bsl.languageserver.cli.VersionCommand; import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import lombok.extern.slf4j.Slf4j; import org.eclipse.lsp4j.jsonrpc.Launcher; @@ -46,17 +46,23 @@ @picocli.CommandLine.Command( name = "", description = "BSL language server on LSP server mode", - mixinStandardHelpOptions = true, - versionProvider = VersionProvider.class, subcommands = { AnalyzeCommand.class, - FormatCommand.class + FormatCommand.class, + VersionCommand.class }, usageHelpAutoWidth = true, + synopsisSubcommandLabel = "[COMMAND [ARGS]]", footer = "@|green Copyright(c) 2018-2020|@", header = "@|green BSL language server|@") public class BSLLSPLauncher implements Callable { + @CommandLine.Option( + names = {"-h", "--help"}, + usageHelp = true, + description = "Show this help message and exit") + boolean usageHelpRequested; + @picocli.CommandLine.Option( names = {"-c", "--configuration"}, description = "Path to language server configuration file", diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java index ef04f4417dc..6636caa6bd0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java @@ -41,6 +41,7 @@ import me.tongfei.progressbar.ProgressBarStyle; import org.apache.commons.io.FileUtils; import org.eclipse.lsp4j.Diagnostic; +import picocli.CommandLine; import java.io.File; import java.io.IOException; @@ -82,7 +83,6 @@ name = "analyze", aliases = {"-a", "--analyze"}, description = "Run analysis and get diagnostic info", - mixinStandardHelpOptions = true, usageHelpAutoWidth = true, footer = "@|green Copyright(c) 2018-2020|@") public class AnalyzeCommand implements Callable { @@ -99,6 +99,12 @@ private static class ReportersKeys extends ArrayList { } } + @picocli.CommandLine.Option( + names = {"-h", "--help"}, + usageHelp = true, + description = "Show this help message and exit") + boolean usageHelpRequested; + @picocli.CommandLine.Option( names = {"-s", "--srcDir"}, description = "Source directory", @@ -128,7 +134,7 @@ private static class ReportersKeys extends ArrayList { private String[] reportersOptions; @picocli.CommandLine.Option( - names = {"-q", "--silent"}, + names = {"--silent"}, description = "Silent mode") private boolean silentMode; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java index c2aaa364e18..e36d4a1b67a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java @@ -60,13 +60,18 @@ name = "format", aliases = {"-f", "--format"}, description = "Format files in source directory", - mixinStandardHelpOptions = true, usageHelpAutoWidth = true, footer = "@|green Copyright(c) 2018-2020|@") public class FormatCommand implements Callable { private final ServerContext serverContext; + @picocli.CommandLine.Option( + names = {"-h", "--help"}, + usageHelp = true, + description = "Show this help message and exit") + boolean usageHelpRequested; + @picocli.CommandLine.Option( names = {"-s", "--srcDir"}, description = "Source directory", @@ -75,7 +80,7 @@ public class FormatCommand implements Callable { private String srcDirOption; @picocli.CommandLine.Option( - names = {"-q", "--silent"}, + names = {"--silent"}, description = "Silent mode") private boolean silentMode; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java similarity index 76% rename from src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionProvider.java rename to src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java index 249813a7308..e6c8f6d3b3a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java @@ -26,17 +26,25 @@ import java.io.IOException; import java.io.InputStream; +import java.util.concurrent.Callable; import java.util.jar.Attributes; import java.util.jar.Manifest; /** - * Читает версию из манифеста и формирует строку-версию приложения + * Выводит версию приложения + * Ключ команды: + * -v, (--version) */ @Slf4j -public class VersionProvider implements CommandLine.IVersionProvider { +@picocli.CommandLine.Command( + name = "version", + aliases = {"-v", "--version"}, + description = "Print version", + usageHelpAutoWidth = true, + footer = "@|green Copyright(c) 2018-2020|@") +public class VersionCommand implements Callable { - @Override - public String[] getVersion() { + public Integer call() { final InputStream mfStream = Thread.currentThread() .getContextClassLoader() .getResourceAsStream("META-INF/MANIFEST.MF"); @@ -46,13 +54,15 @@ public String[] getVersion() { manifest.read(mfStream); } catch (IOException e) { LOGGER.error("Can't read manifest", e); - return new String[0]; + return 1; } - return new String[]{ + System.out.print( String.format( "version: %s%n", manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION) - )}; + )); + + return 0; } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java index 618cdb582ea..72b5b961200 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java @@ -91,7 +91,7 @@ void testAnalyze() { @ExpectSystemExitWithStatus(0) void testAnalyzeSilent() { // given - String[] args = "--analyze --srcDir ./src/test/resources/cli -q".split(" "); + String[] args = "--analyze --srcDir ./src/test/resources/cli --silent".split(" "); // when try { @@ -130,7 +130,7 @@ void testFormat() { @ExpectSystemExitWithStatus(0) void testFormatSilent() { // given - String[] args = "--format --srcDir ./src/test/resources/cli -q".split(" "); + String[] args = "--format --srcDir ./src/test/resources/cli --silent".split(" "); // when try { @@ -145,6 +145,25 @@ void testFormatSilent() { assertThat(errContent.toString()).isEmpty(); } + @Test + @ExpectSystemExitWithStatus(0) + void testVersion() { + // given + String[] args = {"-v"}; + + // when + try { + BSLLSPLauncher.main(args); + } catch (RuntimeException ignored) { + // catch prevented system.exit call + } + + // then + // main-method should runs without exceptions + assertThat(outContent.toString()).startsWith("version:"); + assertThat(errContent.toString()).isEmpty(); + } + @Test void testWithoutParameters() { // given From 696ba96d99c404fea614814e6b426c2895326815 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Fri, 17 Apr 2020 15:38:44 +0300 Subject: [PATCH 112/444] =?UTF-8?q?=D1=83=D0=B4=D0=B0=D0=BB=D0=B8=D0=BB=20?= =?UTF-8?q?=D0=BD=D0=B5=20=D0=BD=D1=83=D0=B6=D0=BD=D1=83=D1=8E=20=D0=B1?= =?UTF-8?q?=D0=BE=D0=BB=D1=8C=D1=88=D0=B5=20=D0=B1=D0=B8=D0=B1=D0=B8=D0=BE?= =?UTF-8?q?=D1=82=D0=B5=D0=BA=D1=83=20=D0=B8=20=D0=BF=D0=BE=D0=BF=D1=80?= =?UTF-8?q?=D0=B0=D0=B2=D0=B8=D0=BB=20=D0=B0=D0=BD=D0=BD=D0=BE=D1=82=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle.kts | 3 --- .../bsl/languageserver/BSLLSPLauncher.java | 4 ++-- .../bsl/languageserver/cli/AnalyzeCommand.java | 14 +++++++------- .../bsl/languageserver/cli/FormatCommand.java | 9 +++++---- .../bsl/languageserver/cli/VersionCommand.java | 1 - 5 files changed, 14 insertions(+), 17 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 5311b31b78d..bc4fedf2b89 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -55,9 +55,6 @@ dependencies { // https://mvnrepository.com/artifact/org.languagetool/language-ru implementation("org.languagetool", "language-ru", "4.2") - // https://mvnrepository.com/artifact/commons-cli/commons-cli - implementation("commons-cli", "commons-cli", "1.4") - implementation("info.picocli", "picocli", "4.2.0") annotationProcessor("info.picocli", "picocli", "4.2.0") diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java index 843daeb03db..39d1d42d4d7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java @@ -43,7 +43,7 @@ import java.util.concurrent.Callable; @Slf4j -@picocli.CommandLine.Command( +@CommandLine.Command( name = "", description = "BSL language server on LSP server mode", subcommands = { @@ -63,7 +63,7 @@ public class BSLLSPLauncher implements Callable { description = "Show this help message and exit") boolean usageHelpRequested; - @picocli.CommandLine.Option( + @CommandLine.Option( names = {"-c", "--configuration"}, description = "Path to language server configuration file", paramLabel = "", diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java index 6636caa6bd0..11d8eacee71 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java @@ -79,7 +79,7 @@ * создается отдельный файл (каталог файлов). Реализованные "репортеры" находятся в пакете "reporter". **/ @Slf4j -@picocli.CommandLine.Command( +@CommandLine.Command( name = "analyze", aliases = {"-a", "--analyze"}, description = "Run analysis and get diagnostic info", @@ -99,41 +99,41 @@ private static class ReportersKeys extends ArrayList { } } - @picocli.CommandLine.Option( + @CommandLine.Option( names = {"-h", "--help"}, usageHelp = true, description = "Show this help message and exit") boolean usageHelpRequested; - @picocli.CommandLine.Option( + @CommandLine.Option( names = {"-s", "--srcDir"}, description = "Source directory", paramLabel = "", defaultValue = "") private String srcDirOption; - @picocli.CommandLine.Option( + @CommandLine.Option( names = {"-o", "--outputDir"}, description = "Output report directory", paramLabel = "", defaultValue = "") private String outputDirOption; - @picocli.CommandLine.Option( + @CommandLine.Option( names = {"-c", "--configuration"}, description = "Path to language server configuration file", paramLabel = "", defaultValue = "") private String configurationOption; - @picocli.CommandLine.Option( + @CommandLine.Option( names = {"-r", "--reporter"}, paramLabel = "", completionCandidates = ReportersKeys.class, description = "Reporter key (${COMPLETION-CANDIDATES})") private String[] reportersOptions; - @picocli.CommandLine.Option( + @CommandLine.Option( names = {"--silent"}, description = "Silent mode") private boolean silentMode; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java index e36d4a1b67a..f8590922695 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java @@ -33,6 +33,7 @@ import org.eclipse.lsp4j.DocumentFormattingParams; import org.eclipse.lsp4j.FormattingOptions; import org.eclipse.lsp4j.TextEdit; +import picocli.CommandLine; import java.io.File; import java.net.URI; @@ -56,7 +57,7 @@ * "форматтера" FormatProvider, т.е. пользователь никак не может овлиять на результат. */ @Slf4j -@picocli.CommandLine.Command( +@CommandLine.Command( name = "format", aliases = {"-f", "--format"}, description = "Format files in source directory", @@ -66,20 +67,20 @@ public class FormatCommand implements Callable { private final ServerContext serverContext; - @picocli.CommandLine.Option( + @CommandLine.Option( names = {"-h", "--help"}, usageHelp = true, description = "Show this help message and exit") boolean usageHelpRequested; - @picocli.CommandLine.Option( + @CommandLine.Option( names = {"-s", "--srcDir"}, description = "Source directory", paramLabel = "", defaultValue = "") private String srcDirOption; - @picocli.CommandLine.Option( + @CommandLine.Option( names = {"--silent"}, description = "Silent mode") private boolean silentMode; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java index e6c8f6d3b3a..f4b03416561 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java @@ -22,7 +22,6 @@ package com.github._1c_syntax.bsl.languageserver.cli; import lombok.extern.slf4j.Slf4j; -import picocli.CommandLine; import java.io.IOException; import java.io.InputStream; From 39771bf2fb5665720fe40443df941b4251b75336 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Fri, 17 Apr 2020 15:49:46 +0300 Subject: [PATCH 113/444] =?UTF-8?q?=D0=92=D1=8B=D0=BD=D0=B5=D1=81=20=D1=81?= =?UTF-8?q?=D1=82=D0=B0=D1=80=D1=82=D0=BE=D0=B2=D1=83=D1=8E=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=BC=D0=B0=D0=BD=D0=B4=D1=83=20=D0=BE=D1=82=D0=B4=D0=B5=D0=BB?= =?UTF-8?q?=D1=8C=D0=BD=D0=BE=20+=20=D1=81=D1=82=D0=B0=D1=82=D0=B8=D0=BA?= =?UTF-8?q?=20=D0=B8=D0=BC=D0=BF=D0=BE=D1=80=D1=82=D1=8B=20=D0=B4=D0=BB?= =?UTF-8?q?=D1=8F=20=D0=B0=D0=BD=D0=BE=D1=82=D0=B0=D1=86=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../bsl/languageserver/BSLLSPLauncher.java | 96 +------------ .../languageserver/cli/AnalyzeCommand.java | 18 +-- .../bsl/languageserver/cli/FormatCommand.java | 12 +- .../cli/LanguageServerStartCommand.java | 127 ++++++++++++++++++ .../languageserver/cli/VersionCommand.java | 3 +- 5 files changed, 149 insertions(+), 107 deletions(-) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java index 39d1d42d4d7..3228ea8ea50 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java @@ -21,104 +21,14 @@ */ package com.github._1c_syntax.bsl.languageserver; -import com.github._1c_syntax.bsl.languageserver.cli.AnalyzeCommand; -import com.github._1c_syntax.bsl.languageserver.cli.FormatCommand; -import com.github._1c_syntax.bsl.languageserver.cli.VersionCommand; -import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; -import lombok.extern.slf4j.Slf4j; -import org.eclipse.lsp4j.jsonrpc.Launcher; -import org.eclipse.lsp4j.launch.LSPLauncher; -import org.eclipse.lsp4j.services.LanguageClient; -import org.eclipse.lsp4j.services.LanguageClientAware; -import org.eclipse.lsp4j.services.LanguageServer; +import com.github._1c_syntax.bsl.languageserver.cli.LanguageServerStartCommand; import picocli.CommandLine; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; -import java.util.concurrent.Callable; - -@Slf4j -@CommandLine.Command( - name = "", - description = "BSL language server on LSP server mode", - subcommands = { - AnalyzeCommand.class, - FormatCommand.class, - VersionCommand.class - }, - usageHelpAutoWidth = true, - synopsisSubcommandLabel = "[COMMAND [ARGS]]", - footer = "@|green Copyright(c) 2018-2020|@", - header = "@|green BSL language server|@") -public class BSLLSPLauncher implements Callable { - - @CommandLine.Option( - names = {"-h", "--help"}, - usageHelp = true, - description = "Show this help message and exit") - boolean usageHelpRequested; - - @CommandLine.Option( - names = {"-c", "--configuration"}, - description = "Path to language server configuration file", - paramLabel = "", - defaultValue = "") - private String configurationOption; - +public class BSLLSPLauncher { public static void main(String[] args) { - - int result = new CommandLine(new BSLLSPLauncher()).execute(args); + int result = new CommandLine(new LanguageServerStartCommand()).execute(args); if (result >= 0) { System.exit(result); } } - - public Integer call() { - File configurationFile = new File(configurationOption); - - LanguageServerConfiguration configuration = LanguageServerConfiguration.create(configurationFile); - LanguageServer server = new BSLLanguageServer(configuration); - - Launcher launcher = getLanguageClientLauncher(server, configuration); - - LanguageClient client = launcher.getRemoteProxy(); - ((LanguageClientAware) server).connect(client); - - launcher.startListening(); - return -1; - } - - private static Launcher getLanguageClientLauncher( - LanguageServer server, - LanguageServerConfiguration configuration - ) { - InputStream in = System.in; - OutputStream out = System.out; - - File logFile = configuration.getTraceLog(); - if (logFile == null) { - return LSPLauncher.createServerLauncher(server, in, out); - } - - Launcher launcher; - - try { - PrintWriter printWriter = new PrintWriter(logFile, StandardCharsets.UTF_8.name()); - launcher = LSPLauncher.createServerLauncher(server, in, out, false, printWriter); - } catch (FileNotFoundException | UnsupportedEncodingException e) { - LOGGER.error("Can't create LSP trace file", e); - if (logFile.isDirectory()) { - LOGGER.error("Trace log setting must lead to file, not directory! {}", logFile.getAbsolutePath()); - } - - launcher = LSPLauncher.createServerLauncher(server, in, out); - } - - return launcher; - } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java index 11d8eacee71..f5a43a55d23 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java @@ -41,7 +41,7 @@ import me.tongfei.progressbar.ProgressBarStyle; import org.apache.commons.io.FileUtils; import org.eclipse.lsp4j.Diagnostic; -import picocli.CommandLine; +import picocli.CommandLine.Command; import java.io.File; import java.io.IOException; @@ -56,6 +56,8 @@ import java.util.concurrent.Callable; import java.util.stream.Collectors; +import static picocli.CommandLine.Option; + /** * Выполнение анализа * Ключ команды: @@ -79,7 +81,7 @@ * создается отдельный файл (каталог файлов). Реализованные "репортеры" находятся в пакете "reporter". **/ @Slf4j -@CommandLine.Command( +@Command( name = "analyze", aliases = {"-a", "--analyze"}, description = "Run analysis and get diagnostic info", @@ -99,41 +101,41 @@ private static class ReportersKeys extends ArrayList { } } - @CommandLine.Option( + @Option( names = {"-h", "--help"}, usageHelp = true, description = "Show this help message and exit") boolean usageHelpRequested; - @CommandLine.Option( + @Option( names = {"-s", "--srcDir"}, description = "Source directory", paramLabel = "", defaultValue = "") private String srcDirOption; - @CommandLine.Option( + @Option( names = {"-o", "--outputDir"}, description = "Output report directory", paramLabel = "", defaultValue = "") private String outputDirOption; - @CommandLine.Option( + @Option( names = {"-c", "--configuration"}, description = "Path to language server configuration file", paramLabel = "", defaultValue = "") private String configurationOption; - @CommandLine.Option( + @Option( names = {"-r", "--reporter"}, paramLabel = "", completionCandidates = ReportersKeys.class, description = "Reporter key (${COMPLETION-CANDIDATES})") private String[] reportersOptions; - @CommandLine.Option( + @Option( names = {"--silent"}, description = "Silent mode") private boolean silentMode; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java index f8590922695..5c690ca14e7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java @@ -33,7 +33,6 @@ import org.eclipse.lsp4j.DocumentFormattingParams; import org.eclipse.lsp4j.FormattingOptions; import org.eclipse.lsp4j.TextEdit; -import picocli.CommandLine; import java.io.File; import java.net.URI; @@ -43,6 +42,9 @@ import java.util.List; import java.util.concurrent.Callable; +import static picocli.CommandLine.Command; +import static picocli.CommandLine.Option; + /** * Форматирование кода в исходниках * Ключ команды: @@ -57,7 +59,7 @@ * "форматтера" FormatProvider, т.е. пользователь никак не может овлиять на результат. */ @Slf4j -@CommandLine.Command( +@Command( name = "format", aliases = {"-f", "--format"}, description = "Format files in source directory", @@ -67,20 +69,20 @@ public class FormatCommand implements Callable { private final ServerContext serverContext; - @CommandLine.Option( + @Option( names = {"-h", "--help"}, usageHelp = true, description = "Show this help message and exit") boolean usageHelpRequested; - @CommandLine.Option( + @Option( names = {"-s", "--srcDir"}, description = "Source directory", paramLabel = "", defaultValue = "") private String srcDirOption; - @CommandLine.Option( + @Option( names = {"--silent"}, description = "Silent mode") private boolean silentMode; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java new file mode 100644 index 00000000000..ba733dc8fb1 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java @@ -0,0 +1,127 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.cli; + +import com.github._1c_syntax.bsl.languageserver.BSLLanguageServer; +import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.lsp4j.jsonrpc.Launcher; +import org.eclipse.lsp4j.launch.LSPLauncher; +import org.eclipse.lsp4j.services.LanguageClient; +import org.eclipse.lsp4j.services.LanguageClientAware; +import org.eclipse.lsp4j.services.LanguageServer; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.Callable; + +import static picocli.CommandLine.Command; +import static picocli.CommandLine.Option; + +/** + * Запускает приложение в режиме Language Server + * Ключ команды: + * без ключа + * Параметры: + * -c, (--configuration) <arg> - Путь к конфигурационному файлу BSL Language Server (.bsl-language-server.json). + * Возможно указывать как в абсолютном, так и относительном виде. Если параметр опущен, + * то будут использованы настройки по умолчанию. + * Выводимая информация: + * Данный режим используется для взаимодействия с клиентом по протоколу LSP. + */ +@Slf4j +@Command( + name = "", + description = "BSL language server on LSP server mode", + subcommands = { + AnalyzeCommand.class, + FormatCommand.class, + VersionCommand.class + }, + usageHelpAutoWidth = true, + synopsisSubcommandLabel = "[COMMAND [ARGS]]", + footer = "@|green Copyright(c) 2018-2020|@", + header = "@|green BSL language server|@") +public class LanguageServerStartCommand implements Callable { + @Option( + names = {"-h", "--help"}, + usageHelp = true, + description = "Show this help message and exit") + boolean usageHelpRequested; + + @Option( + names = {"-c", "--configuration"}, + description = "Path to language server configuration file", + paramLabel = "", + defaultValue = "") + private String configurationOption; + + public Integer call() { + + File configurationFile = new File(configurationOption); + + LanguageServerConfiguration configuration = LanguageServerConfiguration.create(configurationFile); + LanguageServer server = new BSLLanguageServer(configuration); + + Launcher launcher = getLanguageClientLauncher(server, configuration); + + LanguageClient client = launcher.getRemoteProxy(); + ((LanguageClientAware) server).connect(client); + + launcher.startListening(); + return -1; + } + + private static Launcher getLanguageClientLauncher( + LanguageServer server, + LanguageServerConfiguration configuration + ) { + InputStream in = System.in; + OutputStream out = System.out; + + File logFile = configuration.getTraceLog(); + if (logFile == null) { + return LSPLauncher.createServerLauncher(server, in, out); + } + + Launcher launcher; + + try { + PrintWriter printWriter = new PrintWriter(logFile, StandardCharsets.UTF_8.name()); + launcher = LSPLauncher.createServerLauncher(server, in, out, false, printWriter); + } catch (FileNotFoundException | UnsupportedEncodingException e) { + LOGGER.error("Can't create LSP trace file", e); + if (logFile.isDirectory()) { + LOGGER.error("Trace log setting must lead to file, not directory! {}", logFile.getAbsolutePath()); + } + + launcher = LSPLauncher.createServerLauncher(server, in, out); + } + + return launcher; + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java index f4b03416561..4427a53b8ed 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java @@ -22,6 +22,7 @@ package com.github._1c_syntax.bsl.languageserver.cli; import lombok.extern.slf4j.Slf4j; +import picocli.CommandLine.Command; import java.io.IOException; import java.io.InputStream; @@ -35,7 +36,7 @@ * -v, (--version) */ @Slf4j -@picocli.CommandLine.Command( +@Command( name = "version", aliases = {"-v", "--version"}, description = "Print version", From eb18448fbcc43776a17badf1d8312138db3ff957 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Fri, 17 Apr 2020 16:06:15 +0300 Subject: [PATCH 114/444] =?UTF-8?q?=D0=9A=D0=BE=D1=80=D1=80=D0=B5=D0=BA?= =?UTF-8?q?=D1=82=D0=B8=D1=80=D0=BE=D0=B2=D0=BA=D0=B0=20=D0=BF=D0=BE=D0=BB?= =?UTF-8?q?=D1=83=D1=87=D0=B5=D1=87=D0=B5=D0=BD=D0=B8=D1=8F=20=D1=80=D0=B5?= =?UTF-8?q?=D0=BF=D0=BE=D1=80=D1=82=D0=B5=D1=80=D0=BE=D0=B2=20=D0=B4=D0=BB?= =?UTF-8?q?=D1=8F=20=D0=BF=D0=BE=D0=B4=D1=81=D0=BA=D0=B0=D0=B7=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../bsl/languageserver/cli/AnalyzeCommand.java | 16 ++-------------- .../bsl/languageserver/cli/FormatCommand.java | 2 +- .../cli/LanguageServerStartCommand.java | 2 +- .../reporter/ReportersAggregator.java | 2 +- 4 files changed, 5 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java index f5a43a55d23..0a94fe5f271 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java @@ -28,12 +28,7 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.DiagnosticSupplier; import com.github._1c_syntax.bsl.languageserver.diagnostics.FileInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.reporter.AnalysisInfo; -import com.github._1c_syntax.bsl.languageserver.diagnostics.reporter.ConsoleReporter; -import com.github._1c_syntax.bsl.languageserver.diagnostics.reporter.GenericIssueReporter; -import com.github._1c_syntax.bsl.languageserver.diagnostics.reporter.JUnitReporter; -import com.github._1c_syntax.bsl.languageserver.diagnostics.reporter.JsonReporter; import com.github._1c_syntax.bsl.languageserver.diagnostics.reporter.ReportersAggregator; -import com.github._1c_syntax.bsl.languageserver.diagnostics.reporter.TSLintReporter; import com.github._1c_syntax.bsl.languageserver.providers.DiagnosticProvider; import com.github._1c_syntax.utils.Absolute; import lombok.extern.slf4j.Slf4j; @@ -49,7 +44,6 @@ import java.nio.file.Path; import java.time.LocalDateTime; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Optional; @@ -91,13 +85,7 @@ public class AnalyzeCommand implements Callable { private static class ReportersKeys extends ArrayList { ReportersKeys() { - super(Arrays.asList( - ConsoleReporter.KEY, - JsonReporter.KEY, - JUnitReporter.KEY, - TSLintReporter.KEY, - GenericIssueReporter.KEY - )); + super(ReportersAggregator.reporterMap().keySet()); } } @@ -105,7 +93,7 @@ private static class ReportersKeys extends ArrayList { names = {"-h", "--help"}, usageHelp = true, description = "Show this help message and exit") - boolean usageHelpRequested; + private boolean usageHelpRequested; @Option( names = {"-s", "--srcDir"}, diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java index 5c690ca14e7..e0f805bf94b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java @@ -73,7 +73,7 @@ public class FormatCommand implements Callable { names = {"-h", "--help"}, usageHelp = true, description = "Show this help message and exit") - boolean usageHelpRequested; + private boolean usageHelpRequested; @Option( names = {"-s", "--srcDir"}, diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java index ba733dc8fb1..2be0ea78068 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java @@ -71,7 +71,7 @@ public class LanguageServerStartCommand implements Callable { names = {"-h", "--help"}, usageHelp = true, description = "Show this help message and exit") - boolean usageHelpRequested; + private boolean usageHelpRequested; @Option( names = {"-c", "--configuration"}, diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/ReportersAggregator.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/ReportersAggregator.java index b916481fb58..42bbaba7fa3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/ReportersAggregator.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/ReportersAggregator.java @@ -62,7 +62,7 @@ private void addReporterKeys(String[] reporterKeys) { } } - private static Map reporterMap() { + public static Map reporterMap() { Map map = new HashMap<>(); map.put(ConsoleReporter.KEY, ConsoleReporter.class); map.put(JsonReporter.KEY, JsonReporter.class); From e1a58b1fedff01a3667026a8fd3244b9a3de102e Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Mon, 20 Apr 2020 11:56:35 +0300 Subject: [PATCH 115/444] =?UTF-8?q?=D0=94=D0=9E=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BE=D0=B1=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=BA=D1=83?= =?UTF-8?q?=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4=D1=8B=20=D0=BF=D0=BE=20?= =?UTF-8?q?=D1=83=D0=BC=D0=BE=D0=BB=D1=87=D0=B0=D0=BD=D0=B8=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../bsl/languageserver/BSLLSPLauncher.java | 73 ++++++++++++++++++- .../cli/LanguageServerStartCommand.java | 14 +--- 2 files changed, 75 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java index 3228ea8ea50..2a9bcdf9240 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java @@ -21,14 +21,83 @@ */ package com.github._1c_syntax.bsl.languageserver; +import com.github._1c_syntax.bsl.languageserver.cli.AnalyzeCommand; +import com.github._1c_syntax.bsl.languageserver.cli.FormatCommand; import com.github._1c_syntax.bsl.languageserver.cli.LanguageServerStartCommand; +import com.github._1c_syntax.bsl.languageserver.cli.VersionCommand; +import org.jetbrains.annotations.NotNull; import picocli.CommandLine; +import picocli.CommandLine.Option; +import picocli.CommandLine.ParameterException; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Callable; + +import static picocli.CommandLine.Command; + +@Command( + name = "bslls", + description = "BSL language server", + subcommands = { + AnalyzeCommand.class, + FormatCommand.class, + VersionCommand.class, + LanguageServerStartCommand.class + }, + usageHelpAutoWidth = true, + synopsisSubcommandLabel = "[COMMAND [ARGS]]", + footer = "@|green Copyright(c) 2018-2020|@", + header = "@|green BSL language server|@") +public class BSLLSPLauncher implements Callable { + + private static final String DEFAULT_COMMAND = "lsp"; + + @Option( + names = {"-h", "--help"}, + usageHelp = true, + description = "Show this help message and exit") + private boolean usageHelpRequested; -public class BSLLSPLauncher { public static void main(String[] args) { - int result = new CommandLine(new LanguageServerStartCommand()).execute(args); + var app = new BSLLSPLauncher(); + var cmd = new CommandLine(app); + + // проверка использования дефолтной команды + // если строка параметров пуста, то это точно вызов команды по умолчанию + if (args.length == 0) { + args = addDefaultCommand(args); + } else { + // выполнение проверки строки запуска в попытке, т.к. парсер при нахождении + // неизвестных параметров выдает ошибку + try { + cmd.parseArgs(args); + } catch (ParameterException ex) { + // если поймали ошибку, а имя команды не передано, подставим команду и посмотрим, + // вдруг заработает + if (!ex.getCommandLine().getParseResult().hasSubcommand()) { + args = addDefaultCommand(args); + } + } + } + + int result = cmd.execute(args); if (result >= 0) { System.exit(result); } } + + @NotNull + private static String[] addDefaultCommand(String[] args) { + List tmpList = new ArrayList<>(Arrays.asList(args)); + tmpList.add(0, DEFAULT_COMMAND); + args = tmpList.toArray(new String[0]); + return args; + } + + public Integer call() { + // заглушка, командой как таковой не пользуемся + return 0; + } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java index 2be0ea78068..d761afc7a46 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java @@ -55,17 +55,11 @@ */ @Slf4j @Command( - name = "", - description = "BSL language server on LSP server mode", - subcommands = { - AnalyzeCommand.class, - FormatCommand.class, - VersionCommand.class - }, + name = "lsp", + aliases = {"--lsp"}, + description = "LSP server mode", usageHelpAutoWidth = true, - synopsisSubcommandLabel = "[COMMAND [ARGS]]", - footer = "@|green Copyright(c) 2018-2020|@", - header = "@|green BSL language server|@") + footer = "@|green Copyright(c) 2018-2020|@") public class LanguageServerStartCommand implements Callable { @Option( names = {"-h", "--help"}, From 2d788161ac3ef1bf7bab901e0018065c3b4e5bb3 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Mon, 20 Apr 2020 14:04:35 +0300 Subject: [PATCH 116/444] =?UTF-8?q?=D0=94=D0=9E=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D1=82=D0=B5=D1=81=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../languageserver/BSLLSPLauncherTest.java | 52 +++++++++++++++++++ src/test/resources/cli/error-trace.json | 3 ++ 2 files changed, 55 insertions(+) create mode 100644 src/test/resources/cli/error-trace.json diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java index 72b5b961200..a6016064dff 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java @@ -106,6 +106,25 @@ void testAnalyzeSilent() { assertThat(errContent.toString()).isEmpty(); } + @Test + @ExpectSystemExitWithStatus(1) + void testAnalyzeError() { + // given + String[] args = "--analyze --srcDir fake-dir".split(" "); + + // when + try { + BSLLSPLauncher.main(args); + } catch (RuntimeException ignored) { + // catch prevented system.exit call + } + + // then + // main-method should runs without exceptions + assertThat(outContent.toString()).isEmpty(); + assertThat(errContent.toString()).contains("is not exists"); + } + @Test @ExpectSystemExitWithStatus(0) void testFormat() { @@ -145,6 +164,25 @@ void testFormatSilent() { assertThat(errContent.toString()).isEmpty(); } + @Test + @ExpectSystemExitWithStatus(1) + void testFormatError() { + // given + String[] args = "--format --srcDir fake-dir".split(" "); + + // when + try { + BSLLSPLauncher.main(args); + } catch (RuntimeException ignored) { + // catch prevented system.exit call + } + + // then + // main-method should runs without exceptions + assertThat(outContent.toString()).isEmpty(); + assertThat(errContent.toString()).contains("is not exists"); + } + @Test @ExpectSystemExitWithStatus(0) void testVersion() { @@ -177,4 +215,18 @@ void testWithoutParameters() { assertThat(outContent.toString()).isEmpty(); assertThat(errContent.toString()).isEmpty(); } + + @Test + void testWithoutParametersErrorCfg() { + // given + String[] args = new String[]{"-c", "src/test/resources/cli/error-trace.json"}; + + // when + BSLLSPLauncher.main(args); + + // then + // main-method should runs without exceptions + assertThat(outContent.toString()).isEmpty(); + assertThat(errContent.toString()).contains("Can't create LSP trace file"); + } } \ No newline at end of file diff --git a/src/test/resources/cli/error-trace.json b/src/test/resources/cli/error-trace.json new file mode 100644 index 00000000000..96bf15b0e35 --- /dev/null +++ b/src/test/resources/cli/error-trace.json @@ -0,0 +1,3 @@ +{ + "traceLog": "build/" +} From 3d8792915b34644855c40164e6ac047c8520cce1 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Wed, 22 Apr 2020 08:34:44 +0300 Subject: [PATCH 117/444] Update build.gradle.kts Co-Authored-By: Nikita Gryzlov --- build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle.kts b/build.gradle.kts index bc4fedf2b89..ba41234ac01 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -56,7 +56,7 @@ dependencies { implementation("org.languagetool", "language-ru", "4.2") implementation("info.picocli", "picocli", "4.2.0") - annotationProcessor("info.picocli", "picocli", "4.2.0") + annotationProcessor("info.picocli", "picocli-codegen", "4.2.0") // https://mvnrepository.com/artifact/commons-io/commons-io implementation("commons-io", "commons-io", "2.6") From 9a17aa16f97c8f34996e55a28159ce9c1a1b6311 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Wed, 22 Apr 2020 08:34:56 +0300 Subject: [PATCH 118/444] Update src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java Co-Authored-By: Nikita Gryzlov --- .../github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java index 2a9bcdf9240..bbbec506f22 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java @@ -38,7 +38,7 @@ import static picocli.CommandLine.Command; @Command( - name = "bslls", + name = "bsl-language-server", description = "BSL language server", subcommands = { AnalyzeCommand.class, From 99474dc077880fa9efffe672df498baa3b38babf Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Wed, 22 Apr 2020 08:35:03 +0300 Subject: [PATCH 119/444] Update src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java Co-Authored-By: Nikita Gryzlov --- .../bsl/languageserver/cli/LanguageServerStartCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java index d761afc7a46..0466ff5e196 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java @@ -57,7 +57,7 @@ @Command( name = "lsp", aliases = {"--lsp"}, - description = "LSP server mode", + description = "LSP server mode (default)", usageHelpAutoWidth = true, footer = "@|green Copyright(c) 2018-2020|@") public class LanguageServerStartCommand implements Callable { From d571681eabb5ab921b160ba9799a39c82c235b22 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Wed, 22 Apr 2020 08:55:11 +0300 Subject: [PATCH 120/444] =?UTF-8?q?=D0=A2=D0=B0=D0=BA=20=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=B0=D0=B5=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle.kts | 1 - 1 file changed, 1 deletion(-) diff --git a/build.gradle.kts b/build.gradle.kts index ba41234ac01..560d4686f15 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -56,7 +56,6 @@ dependencies { implementation("org.languagetool", "language-ru", "4.2") implementation("info.picocli", "picocli", "4.2.0") - annotationProcessor("info.picocli", "picocli-codegen", "4.2.0") // https://mvnrepository.com/artifact/commons-io/commons-io implementation("commons-io", "commons-io", "2.6") From 17df6b0b68982629b50709b6b7525c6e69faef03 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Wed, 22 Apr 2020 09:02:17 +0300 Subject: [PATCH 121/444] doc fix --- docs/diagnostics/TooManyReturns.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/docs/diagnostics/TooManyReturns.md b/docs/diagnostics/TooManyReturns.md index 613bc767c5b..407b821ae90 100644 --- a/docs/diagnostics/TooManyReturns.md +++ b/docs/diagnostics/TooManyReturns.md @@ -40,12 +40,6 @@ ``` ## Источники - - * [Why Many Return Statements Are a Bad Idea in OOP](https://www.yegor256.com/2015/08/18/multiple-return-statements-in-oop.html) * [JAVA: Methods should not have too many return statements](https://rules.sonarsource.com/java/RSPEC-1142) From 94a794bb086b14daed731de063a9198082441b60 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Tue, 21 Apr 2020 22:05:43 +0300 Subject: [PATCH 122/444] another npe fix --- .../diagnostics/DataExchangeLoadingDiagnostic.java | 10 +++------- .../diagnostics/DataExchangeLoadingDiagnostic.bsl | 11 +++++++++++ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java index 2a692d5c736..0a79378fade 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java @@ -126,13 +126,9 @@ && foundReturnStatement(context)) private static boolean foundReturnStatement(BSLParser.IfBranchContext ifBranch) { return Optional.ofNullable(ifBranch.codeBlock()) - .map(BSLParser.CodeBlockContext::statement) - .flatMap(statementContexts -> statementContexts.stream() - .map(BSLParser.StatementContext::compoundStatement) - .map(BSLParser.CompoundStatementContext::returnStatement) - .map(Optional::ofNullable) - .findAny()) - .isPresent(); + .map(codeBlockContext -> Trees.findAllRuleNodes(codeBlockContext, BSLParser.RULE_returnStatement)) + .map(list -> !list.isEmpty()) + .orElse(false); } private static ParserRuleContext getSubContext(BSLParser.ProcDeclarationContext ctx) { diff --git a/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl b/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl index 37388ddc43f..ecc16ed6650 100644 --- a/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl +++ b/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl @@ -52,3 +52,14 @@ EndProcedure Возврат; КонецЕсли; КонецПроцедуры + + + +Процедура ПередЗаписью(Отказ, РежимЗаписи, РежимПроведения) + + Если НЕ ОбменДанными.Загрузка И РольДоступна("ПолныеПрава")) И НЕ (ДополнительныеСвойства.Свойство("Обмен") И ДополнительныеСвойства.Обмен = Истина) Тогда + Отказ = Истина; + Возврат; + КонецЕсли; + +КонецПроцедуры \ No newline at end of file From 10cbe9fc35f91bee6e001aae384eb53dd086c0de Mon Sep 17 00:00:00 2001 From: Yuri Goncharuk Date: Wed, 22 Apr 2020 13:42:17 +0300 Subject: [PATCH 123/444] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=87?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../reporter/GenericCoverageReport.java | 20 +++++++++---------- .../reporter/GenericCoverageTest.java | 14 ++++++++----- 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageReport.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageReport.java index 7c95a477e91..f3793d3ac11 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageReport.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageReport.java @@ -26,22 +26,20 @@ import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import com.github._1c_syntax.bsl.languageserver.diagnostics.FileInfo; -import lombok.Getter; import lombok.Value; import java.util.ArrayList; import java.util.List; @JacksonXmlRootElement(localName = "coverage") +@Value public class GenericCoverageReport { @JacksonXmlProperty(isAttribute = true) - @Getter - public final String version; + final String version; @JacksonXmlElementWrapper(useWrapping = false) - @Getter - public final List file; + final List file; public GenericCoverageReport(AnalysisInfo analysisInfo) { @@ -66,10 +64,10 @@ public GenericCoverageReport( static class GenericCoverageReportEntry { @JacksonXmlProperty(isAttribute = true) - public String path; + String path; @JacksonXmlElementWrapper(useWrapping = false) - public List lineToCover; + List lineToCover; public GenericCoverageReportEntry(FileInfo fileInfo) { this.path = fileInfo.getPath().toString(); @@ -82,10 +80,10 @@ public GenericCoverageReportEntry(FileInfo fileInfo) { public GenericCoverageReportEntry( @JsonProperty("path") String path, - @JsonProperty("version") List lineToCover + @JsonProperty("lineToCover") List lineToCover ) { this.path = path; - this.lineToCover = new ArrayList<>(); + this.lineToCover = new ArrayList<>(lineToCover); } } @@ -93,10 +91,10 @@ public GenericCoverageReportEntry( static class LineToCoverEntry { @JacksonXmlProperty(isAttribute = true) - public int lineNumber; + int lineNumber; @JacksonXmlProperty(isAttribute = true) - public boolean covered; + boolean covered; public LineToCoverEntry( @JsonProperty("lineNumber") int lineNumber, diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageTest.java index 30676b1da76..0bc8b95cd39 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/reporter/GenericCoverageTest.java @@ -27,7 +27,6 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.FileInfo; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import org.apache.commons.io.FileUtils; -import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -37,7 +36,6 @@ import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; -import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @@ -75,11 +73,17 @@ void report() throws IOException { GenericCoverageReport report = mapper.readValue(file, GenericCoverageReport.class); assertThat(report).isNotNull(); - assertThat(report.version).isEqualTo("1"); - assertThat(report.file.size()).isEqualTo(1); + assertThat(report.getVersion()).isEqualTo("1"); + assertThat(report.getFile().size()).isEqualTo(1); - GenericCoverageReport.GenericCoverageReportEntry fileEntry = report.file.get(0); + GenericCoverageReport.GenericCoverageReportEntry fileEntry = report.getFile().get(0); assertThat(fileEntry.getPath()).isEqualTo(fileInfo.getPath().toString()); + assertThat(fileEntry.getLineToCover().size()).isEqualTo(12); + + GenericCoverageReport.LineToCoverEntry lineToCover = fileEntry.getLineToCover().get(0); + + assertThat(lineToCover.getLineNumber()).isEqualTo(5); + assertThat(lineToCover.isCovered()).isFalse(); } } From 9a3eb47ae00bde0b7617d257da05915b363f380a Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Wed, 22 Apr 2020 14:26:08 +0300 Subject: [PATCH 124/444] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B3=D0=B5=D0=BD=D0=B5=D1=80?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8=20=D0=BA=D0=BE=D0=BD=D1=84=D0=B8=D0=B3?= =?UTF-8?q?=D0=B0=20=D0=B4=D0=BB=D1=8F=20=D0=B4=D0=B5=D0=B2=D0=B5=D0=BB?= =?UTF-8?q?=D0=BE=D0=BF-=D0=B2=D0=B5=D1=80=D1=81=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/benchmark.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/scripts/benchmark.py b/.github/scripts/benchmark.py index 4f299a0761d..f4d0e8882ea 100644 --- a/.github/scripts/benchmark.py +++ b/.github/scripts/benchmark.py @@ -37,7 +37,9 @@ def createBSLLSConfiguration(): newPath = thisPath + "/ssl/.bsl-language-server.json" data = {} data['configurationRoot'] = './src' - data['diagnostics'] = {'Typo': False} + data['diagnostics'] = {} + data['diagnostics']['mode'] = 'except' + data['diagnostics']['parameters'] = {'Typo': False} with open(newPath, 'w') as outfile: json.dump(data, outfile) From f2515f0fc3549553d9c6c9e5343d60b47b14eb5f Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Wed, 22 Apr 2020 16:56:06 +0300 Subject: [PATCH 125/444] =?UTF-8?q?=D0=9D=D0=B0=D1=87=D0=B0=D0=BB=D1=8C?= =?UTF-8?q?=D0=BD=D1=8B=D0=B9=20=D0=B4=D1=80=D0=B0=D1=84=D1=82=20=D0=B4?= =?UTF-8?q?=D0=B8=D0=B0=D0=B3=D0=BD=D0=BE=D1=81=D1=82=D0=B8=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/DeprecatedMethods8310.md | 36 ++++++ docs/diagnostics/index.md | 5 +- docs/en/diagnostics/DeprecatedMethods8310.md | 36 ++++++ docs/en/diagnostics/index.md | 5 +- .../DeprecatedMethods8310Diagnostic.java | 111 ++++++++++++++++++ .../configuration/parameters-schema.json | 10 ++ .../languageserver/configuration/schema.json | 3 + ...recatedMethods8310Diagnostic_en.properties | 2 + ...recatedMethods8310Diagnostic_ru.properties | 2 + .../DeprecatedMethods8310DiagnosticTest.java | 46 ++++++++ .../DeprecatedMethods8310Diagnostic.bsl | 3 + 11 files changed, 255 insertions(+), 4 deletions(-) create mode 100644 docs/diagnostics/DeprecatedMethods8310.md create mode 100644 docs/en/diagnostics/DeprecatedMethods8310.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310DiagnosticTest.java create mode 100644 src/test/resources/diagnostics/DeprecatedMethods8310Diagnostic.bsl diff --git a/docs/diagnostics/DeprecatedMethods8310.md b/docs/diagnostics/DeprecatedMethods8310.md new file mode 100644 index 00000000000..0252bb30bdf --- /dev/null +++ b/docs/diagnostics/DeprecatedMethods8310.md @@ -0,0 +1,36 @@ +# Использование устаревшего метода клиентского приложения (DeprecatedMethods8310) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Дефект кода` | `BSL` | `Информационный` | `Да` | `1` | `deprecated` | + + +## Описание диагностики + + +## Примеры + + +## Источники + + + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:DeprecatedMethods8310-off +// BSLLS:DeprecatedMethods8310-on +``` + +### Параметр конфигурационного файла + +```json +"DeprecatedMethods8310": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 6dce551df6a..eac9427cc9b 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,9 +8,9 @@ ## Список реализованных диагностик -Общее количество: **92** +Общее количество: **93** -* Дефект кода: **57** +* Дефект кода: **58** * Уязвимость: **2** * Ошибка: **31** * Потенциальная уязвимость: **2** @@ -35,6 +35,7 @@ | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Использование устаревшего метода "ТекущаяДата" | Да | Важный | Ошибка | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Использование устаревшего метода "Найти" | Да | Незначительный | Дефект кода | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Ограничение на использование устаревшего метода "Сообщить" | Да | Незначительный | Дефект кода | `standard`
`deprecated` | +| [DeprecatedMethods8310](DeprecatedMethods8310.md) | Использование устаревшего метода клиентского приложения | Да | Информационный | Дефект кода | `deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Устаревшее использование типа "УправляемаяФорма" | Да | Информационный | Дефект кода | `standard`
`deprecated` | | [DuplicateRegion](DuplicateRegion.md) | Повторяющиеся разделы модуля | Да | Информационный | Дефект кода | `standard` | | [EmptyCodeBlock](EmptyCodeBlock.md) | Пустой блок кода | Да | Важный | Дефект кода | `badpractice`
`suspicious` | diff --git a/docs/en/diagnostics/DeprecatedMethods8310.md b/docs/en/diagnostics/DeprecatedMethods8310.md new file mode 100644 index 00000000000..0e538b82967 --- /dev/null +++ b/docs/en/diagnostics/DeprecatedMethods8310.md @@ -0,0 +1,36 @@ +# (DeprecatedMethods8310) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Code smell` | `BSL` | `Info` | `Yes` | `1` | `deprecated` | + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:DeprecatedMethods8310-off +// BSLLS:DeprecatedMethods8310-on +``` + +### Parameter for config + +```json +"DeprecatedMethods8310": false +``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 659c900dc05..14be03cf5e4 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,10 +8,10 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **92** +Total: **93** * Error: **31** -* Code smell: **57** +* Code smell: **58** * Vulnerability: **2** * Security Hotspot: **2** @@ -35,6 +35,7 @@ Total: **92** | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Using of the deprecated method "CurrentDate" | Yes | Major | Error | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Using of the deprecated method "Find" | Yes | Minor | Code smell | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Restriction on the use of deprecated "Message" method | Yes | Minor | Code smell | `standard`
`deprecated` | +| [DeprecatedMethods8310](DeprecatedMethods8310.md) | | Yes | Info | Code smell | `deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Deprecated ManagedForm type | Yes | Info | Code smell | `standard`
`deprecated` | | [DuplicateRegion](DuplicateRegion.md) | Duplicate regions | Yes | Info | Code smell | `standard` | | [EmptyCodeBlock](EmptyCodeBlock.md) | Empty code block | Yes | Major | Code smell | `badpractice`
`suspicious` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java new file mode 100644 index 00000000000..df5d0cfd020 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java @@ -0,0 +1,111 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCompatibilityMode; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.parser.BSLParser; +import org.antlr.v4.runtime.tree.ParseTree; + +import java.util.HashMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.INFO, + minutesToFix = 1, + scope = DiagnosticScope.BSL, + compatibilityMode = DiagnosticCompatibilityMode.COMPATIBILITY_MODE_8_3_10, + tags = { + DiagnosticTag.DEPRECATED + } + +) +public class DeprecatedMethods8310Diagnostic extends AbstractVisitorDiagnostic { + + private static final String SET_SHORT_APPLICATION_CAPTION_RU = "УстановитьКраткийЗаголовокПриложения"; + private static final String SET_SHORT_APPLICATION_CAPTION_EN = "SetShortApplicationCaption"; + private static final String GET_SHORT_APPLICATION_CAPTION_RU = "ПолучитьКраткийЗаголовокПриложения"; + private static final String GET_SHORT_APPLICATION_CAPTION_EN = "GetShortApplicationCaption"; + private static final String SET_CLIENT_APPLICATION_CAPTION_RU = "УстановитьЗаголовокКлиентскогоПриложения"; + private static final String SET_CLIENT_APPLICATION_CAPTION_EN = "SetClientApplicationCaption"; + private static final String GET_CLIENT_APPLICATION_CAPTION_RU = "ПолучитьЗаголовокКлиентскогоПриложения"; + private static final String GET_CLIENT_APPLICATION_CAPTION_EN = "GetClientApplicationCaption"; + private static final String BASE_FONT_CURRENT_VARIANT_RU = "ТекущийВариантОсновногоШрифтаКлиентскогоПриложения"; + private static final String BASE_FONT_CURRENT_VARIANT_EN = "ClientApplicationBaseFontCurrentVariant"; + private static final String CLIENT_INTERFACE_VARIANT_RU = "ТекущийВариантИнтерфейсаКлиентскогоПриложения"; + private static final String CLIENT_INTERFACE_VARIANT_EN = "ClientApplicationInterfaceCurrentVariant"; + private static final String METHOD_PAIR = "%s|%s|"; + private static final String REGEX = String.format(METHOD_PAIR + + METHOD_PAIR + + METHOD_PAIR + + METHOD_PAIR + + METHOD_PAIR + + "%s|%s" + , SET_SHORT_APPLICATION_CAPTION_RU, SET_SHORT_APPLICATION_CAPTION_EN + , GET_SHORT_APPLICATION_CAPTION_RU, GET_SHORT_APPLICATION_CAPTION_EN + , SET_CLIENT_APPLICATION_CAPTION_RU, SET_CLIENT_APPLICATION_CAPTION_EN + , GET_CLIENT_APPLICATION_CAPTION_RU, GET_CLIENT_APPLICATION_CAPTION_EN + , BASE_FONT_CURRENT_VARIANT_RU, BASE_FONT_CURRENT_VARIANT_EN + , CLIENT_INTERFACE_VARIANT_RU, CLIENT_INTERFACE_VARIANT_EN); + private static final Pattern METHOD_PATTERN = Pattern.compile(REGEX, + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + + private static final HashMap newMethods = new HashMap<>(); + static { + newMethods.put(SET_SHORT_APPLICATION_CAPTION_RU, "КлиентскоеПриложение.УстановитьКраткийЗаголовок"); + newMethods.put(GET_SHORT_APPLICATION_CAPTION_RU, "КлиентскоеПриложение.ПолучитьКраткийЗаголовок"); + newMethods.put(SET_CLIENT_APPLICATION_CAPTION_RU, "КлиентскоеПриложение.УстановитьЗаголовок"); + newMethods.put(GET_CLIENT_APPLICATION_CAPTION_RU, "КлиентскоеПриложение.ПолучитьЗаголовок"); + newMethods.put(BASE_FONT_CURRENT_VARIANT_RU, "КлиентскоеПриложение.ТекущийВариантОсновногоШрифта"); + newMethods.put(CLIENT_INTERFACE_VARIANT_RU, "КлиентскоеПриложение.ТекущийВариантИнтерфейса"); + + newMethods.put(SET_SHORT_APPLICATION_CAPTION_EN, "ClientApplication.SetShortCaption"); + newMethods.put(GET_SHORT_APPLICATION_CAPTION_EN, "ClientApplication.GetShortCaption"); + newMethods.put(SET_CLIENT_APPLICATION_CAPTION_EN, "ClientApplication.SetCaption"); + newMethods.put(GET_CLIENT_APPLICATION_CAPTION_EN, "ClientApplication.GetCaption"); + newMethods.put(BASE_FONT_CURRENT_VARIANT_EN, "ClientApplication.CurrentBaseFontVariant"); + newMethods.put(CLIENT_INTERFACE_VARIANT_EN, "ClientApplication.CurrentInterfaceVariant"); + } + + public DeprecatedMethods8310Diagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { + + Matcher matcher = METHOD_PATTERN.matcher(ctx.methodName().getText()); + if (matcher.matches()) { + diagnosticStorage.addDiagnostic(ctx, + info.getMessage(matcher.group(), newMethods.getOrDefault(matcher.group(), ""))); + } + + return super.visitGlobalMethodCall(ctx); + } +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index 6eb3492e4b4..f516b08d685 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -236,6 +236,16 @@ "title": "Restriction on the use of deprecated \"Message\" method", "$id": "#/definitions/DeprecatedMessage" }, + "DeprecatedMethods8310": { + "description": "", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "", + "$id": "#/definitions/DeprecatedMethods8310" + }, "DeprecatedTypeManagedForm": { "description": "Deprecated ManagedForm type", "default": true, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index aa01b50a23f..e4e5668caff 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -77,6 +77,9 @@ "DeprecatedMessage": { "$ref": "parameters-schema.json#/definitions/DeprecatedMessage" }, + "DeprecatedMethods8310": { + "$ref": "parameters-schema.json#/definitions/DeprecatedMethods8310" + }, "DeprecatedTypeManagedForm": { "$ref": "parameters-schema.json#/definitions/DeprecatedTypeManagedForm" }, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic_en.properties new file mode 100644 index 00000000000..66831715dfd --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage= +diagnosticName= diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic_ru.properties new file mode 100644 index 00000000000..dbbd77f67a8 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Метод "%s" устарел. Следует использовать "%s". +diagnosticName=Использование устаревшего метода клиентского приложения diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310DiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310DiagnosticTest.java new file mode 100644 index 00000000000..b7f0ba2f6cc --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310DiagnosticTest.java @@ -0,0 +1,46 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class DeprecatedMethods8310DiagnosticTest extends AbstractDiagnosticTest { + DeprecatedMethods8310DiagnosticTest() { + super(DeprecatedMethods8310Diagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(1, 31, 1, 78); + + } +} diff --git a/src/test/resources/diagnostics/DeprecatedMethods8310Diagnostic.bsl b/src/test/resources/diagnostics/DeprecatedMethods8310Diagnostic.bsl new file mode 100644 index 00000000000..fcca9dfa9c1 --- /dev/null +++ b/src/test/resources/diagnostics/DeprecatedMethods8310Diagnostic.bsl @@ -0,0 +1,3 @@ +Процедура Тест() + ТекущийВариантИнтерфейса = ТекущийВариантИнтерфейсаКлиентскогоПриложения(); +КонецПроцедуры From 5894fabf5f2e4058dc6044fafa3aeaf5ecc758e9 Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Wed, 22 Apr 2020 18:01:03 +0300 Subject: [PATCH 126/444] =?UTF-8?q?=D0=9D=D0=BE=D0=B2=D0=B0=D1=8F=20=D0=B4?= =?UTF-8?q?=D0=B8=D0=B0=D0=B3=D0=BD=D0=BE=D1=81=D1=82=D0=B8=D0=BA=D0=B0:?= =?UTF-8?q?=20=D1=83=D1=81=D1=82=D0=B0=D1=80=D0=B5=D0=B2=D1=88=D0=B8=D0=B5?= =?UTF-8?q?=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4=D1=8B=208.3.10?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/DeprecatedMethods8310.md | 14 +++-- docs/en/diagnostics/DeprecatedMethods8310.md | 17 ++++-- docs/en/diagnostics/index.md | 2 +- .../configuration/parameters-schema.json | 4 +- ...recatedMethods8310Diagnostic_en.properties | 4 +- .../DeprecatedMethods8310DiagnosticTest.java | 15 +++++- .../DeprecatedMethods8310Diagnostic.bsl | 53 +++++++++++++++++++ 7 files changed, 94 insertions(+), 15 deletions(-) diff --git a/docs/diagnostics/DeprecatedMethods8310.md b/docs/diagnostics/DeprecatedMethods8310.md index 0252bb30bdf..2fdf6d3e965 100644 --- a/docs/diagnostics/DeprecatedMethods8310.md +++ b/docs/diagnostics/DeprecatedMethods8310.md @@ -7,9 +7,16 @@ ## Описание диагностики - -## Примеры - +Следующие методы глобального контекста объявляены устаревшими и их использование не рекомендуется +начиная с версии платформы 8.3.10: +``` +УстановитьКраткийЗаголовокПриложения(); +ПолучитьКраткийЗаголовокПриложения(); +УстановитьЗаголовокКлиентскогоПриложения(); +ПолучитьЗаголовокКлиентскогоПриложения(); +ТекущийВариантОсновногоШрифтаКлиентскогоПриложения(); +ТекущийВариантИнтерфейсаКлиентскогоПриложения(). +``` ## Источники @@ -18,6 +25,7 @@ * Источник: [Стандарт: Тексты модулей](https://its.1c.ru/db/v8std#content:456:hdoc) * Полезная информаця: [Отказ от использования модальных окон](https://its.1c.ru/db/metod8dev#content:5272:hdoc) * Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) --> +Источник: [Список изменений платформы 8.3.10:](https://dl03.1c.ru/content/Platform/8_3_10_2699/1cv8upd.htm) ## Сниппеты diff --git a/docs/en/diagnostics/DeprecatedMethods8310.md b/docs/en/diagnostics/DeprecatedMethods8310.md index 0e538b82967..325a4e26edd 100644 --- a/docs/en/diagnostics/DeprecatedMethods8310.md +++ b/docs/en/diagnostics/DeprecatedMethods8310.md @@ -1,4 +1,4 @@ -# (DeprecatedMethods8310) +# Deprecated client application method. (DeprecatedMethods8310) | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | @@ -7,10 +7,16 @@ ## Description - -## Examples - - +The following global context methods are deprecated and are not recommended +since platform version 8.3.10: +``` +SetShortApplicationCaption(); +GetShortApplicationCaption(); +SetClientApplicationCaption(); +GetClientApplicationCaption(); +ClientApplicationBaseFontCurrentVariant(); +ClientApplicationInterfaceCurrentVariant(). +``` ## Sources +Source: [Version 8.3.10 changelog](https://dl03.1c.ru/content/Platform/8_3_10_2699/1cv8upd.htm) ## Snippets diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 14be03cf5e4..40af697dbe0 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -35,7 +35,7 @@ Total: **93** | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Using of the deprecated method "CurrentDate" | Yes | Major | Error | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Using of the deprecated method "Find" | Yes | Minor | Code smell | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Restriction on the use of deprecated "Message" method | Yes | Minor | Code smell | `standard`
`deprecated` | -| [DeprecatedMethods8310](DeprecatedMethods8310.md) | | Yes | Info | Code smell | `deprecated` | +| [DeprecatedMethods8310](DeprecatedMethods8310.md) | Deprecated client application method. | Yes | Info | Code smell | `deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Deprecated ManagedForm type | Yes | Info | Code smell | `standard`
`deprecated` | | [DuplicateRegion](DuplicateRegion.md) | Duplicate regions | Yes | Info | Code smell | `standard` | | [EmptyCodeBlock](EmptyCodeBlock.md) | Empty code block | Yes | Major | Code smell | `badpractice`
`suspicious` | diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index f516b08d685..aab363c6a53 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -237,13 +237,13 @@ "$id": "#/definitions/DeprecatedMessage" }, "DeprecatedMethods8310": { - "description": "", + "description": "Deprecated client application method.", "default": true, "type": [ "boolean", "object" ], - "title": "", + "title": "Deprecated client application method.", "$id": "#/definitions/DeprecatedMethods8310" }, "DeprecatedTypeManagedForm": { diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic_en.properties index 66831715dfd..90ba23ca9b8 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic_en.properties @@ -1,2 +1,2 @@ -diagnosticMessage= -diagnosticName= +diagnosticMessage=Method "%s" is deprecated. You should use "%s". +diagnosticName=Deprecated client application method. diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310DiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310DiagnosticTest.java index b7f0ba2f6cc..acbb1a33903 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310DiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310DiagnosticTest.java @@ -38,9 +38,20 @@ void test() { List diagnostics = getDiagnostics(); - assertThat(diagnostics).hasSize(1); + assertThat(diagnostics).hasSize(12); assertThat(diagnostics, true) - .hasRange(1, 31, 1, 78); + .hasRange(1, 31, 1, 78) + .hasRange(5, 31, 5, 67) + .hasRange(9, 31, 9, 73) + .hasRange(13, 31, 13, 71) + .hasRange(17, 31, 17, 83) + .hasRange(21, 31, 21, 78) + .hasRange(25, 11, 25, 39) + .hasRange(30, 11, 30, 39) + .hasRange(35, 11, 35, 40) + .hasRange(40, 11, 40, 40) + .hasRange(45, 11, 45, 52) + .hasRange(50, 11, 50, 53); } } diff --git a/src/test/resources/diagnostics/DeprecatedMethods8310Diagnostic.bsl b/src/test/resources/diagnostics/DeprecatedMethods8310Diagnostic.bsl index fcca9dfa9c1..e4761ea79c4 100644 --- a/src/test/resources/diagnostics/DeprecatedMethods8310Diagnostic.bsl +++ b/src/test/resources/diagnostics/DeprecatedMethods8310Diagnostic.bsl @@ -1,3 +1,56 @@ Процедура Тест() ТекущийВариантИнтерфейса = ТекущийВариантИнтерфейсаКлиентскогоПриложения(); КонецПроцедуры + +Процедура Тест() + ТекущийВариантИнтерфейса = ПолучитьКраткийЗаголовокПриложения(); +КонецПроцедуры + +Процедура Тест() + ТекущийВариантИнтерфейса = УстановитьЗаголовокКлиентскогоПриложения(); +КонецПроцедуры + +Процедура Тест() + ТекущийВариантИнтерфейса = ПолучитьЗаголовокКлиентскогоПриложения(); +КонецПроцедуры + +Процедура Тест() + ТекущийВариантИнтерфейса = ТекущийВариантОсновногоШрифтаКлиентскогоПриложения(); +КонецПроцедуры + +Процедура Тест() + ТекущийВариантИнтерфейса = ТекущийВариантИнтерфейсаКлиентскогоПриложения(); +КонецПроцедуры + +Procedure Test() + test = SetShortApplicationCaption(); + return; +EndProcedure + +Procedure Test() + test = GetShortApplicationCaption(); + return; +EndProcedure + +Procedure Test() + test = SetClientApplicationCaption(); + return; +EndProcedure + +Procedure Test() + test = GetClientApplicationCaption(); + return; +EndProcedure + +Procedure Test() + test = ClientApplicationBaseFontCurrentVariant(); + return; +EndProcedure + +Procedure Test() + test = ClientApplicationInterfaceCurrentVariant(); + return; +EndProcedure + + + From d1a4a1d1b9501aa8adfe8fb7dd2fb8be4573c882 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Wed, 22 Apr 2020 19:20:04 +0300 Subject: [PATCH 127/444] =?UTF-8?q?=D0=BA=D0=B5=D0=B9=D1=81=20=D0=B2=20?= =?UTF-8?q?=D1=82=D0=B5=D1=81=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DataExchangeLoadingDiagnosticTest.java | 12 +++++++++--- .../DataExchangeLoadingDiagnostic.bsl | 16 ++++++++++++++-- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java index 39bd6d671d9..fa742f99ae5 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java @@ -48,11 +48,17 @@ void test() { // then assertThat(diagnostics) - .hasSize(2) + .hasSize(3) .anyMatch(diagnostic -> diagnostic.getRange().equals( Ranges.create(7, 10, 7, 22))) .anyMatch(diagnostic -> diagnostic.getRange().equals( - Ranges.create(19, 10, 19, 17))); + Ranges.create(19, 10, 19, 17))) + .anyMatch(diagnostic -> diagnostic.getRange().equals( + Ranges.create(70, 10, 70, 22))) + //fix me "Если НЕ обменданными" +// .anyMatch(diagnostic -> diagnostic.getRange().equals( +// Ranges.create(57, 10, 57, 22))); + ; // Проверяем с включенным параметром findFirst // when @@ -63,7 +69,7 @@ void test() { // then assertThat(diagnostics) - .hasSize(3) + .hasSize(4) .anyMatch(diagnostic -> diagnostic.getRange().equals( Ranges.create(7, 10, 7, 22))) .anyMatch(diagnostic -> diagnostic.getRange().equals( diff --git a/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl b/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl index ecc16ed6650..e921c47d59a 100644 --- a/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl +++ b/src/test/resources/diagnostics/DataExchangeLoadingDiagnostic.bsl @@ -57,9 +57,21 @@ EndProcedure Процедура ПередЗаписью(Отказ, РежимЗаписи, РежимПроведения) - Если НЕ ОбменДанными.Загрузка И РольДоступна("ПолныеПрава")) И НЕ (ДополнительныеСвойства.Свойство("Обмен") И ДополнительныеСвойства.Обмен = Истина) Тогда + Если НЕ ОбменДанными.Загрузка И РольДоступна("ПолныеПрава") И НЕ (ДополнительныеСвойства.Свойство("Обмен") И ДополнительныеСвойства.Обмен = Истина) Тогда Отказ = Истина; Возврат; КонецЕсли; -КонецПроцедуры \ No newline at end of file +КонецПроцедуры + +Процедура просто() + +КонецПроцедуры + +Процедура ПередЗаписью(Отказ, РежимЗаписи, РежимПроведения) + + Если ОбменДанными.Загрузка Тогда + КонецЕсли; + +КонецПроцедуры + From 4280c6aaf02f3b9721b1c56cf6226cd1edb7bc36 Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Thu, 23 Apr 2020 10:14:56 +0300 Subject: [PATCH 128/444] =?UTF-8?q?=D0=93=D0=B5=D0=BD=D0=B5=D1=80=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D1=8F=20=D1=80=D0=B5=D0=B3=D1=83=D0=BB=D1=8F=D1=80?= =?UTF-8?q?=D0=BD=D0=BE=D0=B3=D0=BE=20=D0=B2=D1=8B=D1=80=D0=B0=D0=B6=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D1=8F=20=D0=B2=D1=8B=D0=BD=D0=B5=D1=81=D0=B5=D0=BD?= =?UTF-8?q?=D0=B0=20=D0=B2=20=D0=BE=D1=82=D0=B4=D0=B5=D0=BB=D1=8C=D0=BD?= =?UTF-8?q?=D1=8B=D0=B9=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DeprecatedMethods8310Diagnostic.java | 36 +++++++++++-------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java index df5d0cfd020..2576e6fd086 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java @@ -60,20 +60,8 @@ public class DeprecatedMethods8310Diagnostic extends AbstractVisitorDiagnostic { private static final String BASE_FONT_CURRENT_VARIANT_EN = "ClientApplicationBaseFontCurrentVariant"; private static final String CLIENT_INTERFACE_VARIANT_RU = "ТекущийВариантИнтерфейсаКлиентскогоПриложения"; private static final String CLIENT_INTERFACE_VARIANT_EN = "ClientApplicationInterfaceCurrentVariant"; - private static final String METHOD_PAIR = "%s|%s|"; - private static final String REGEX = String.format(METHOD_PAIR + - METHOD_PAIR + - METHOD_PAIR + - METHOD_PAIR + - METHOD_PAIR + - "%s|%s" - , SET_SHORT_APPLICATION_CAPTION_RU, SET_SHORT_APPLICATION_CAPTION_EN - , GET_SHORT_APPLICATION_CAPTION_RU, GET_SHORT_APPLICATION_CAPTION_EN - , SET_CLIENT_APPLICATION_CAPTION_RU, SET_CLIENT_APPLICATION_CAPTION_EN - , GET_CLIENT_APPLICATION_CAPTION_RU, GET_CLIENT_APPLICATION_CAPTION_EN - , BASE_FONT_CURRENT_VARIANT_RU, BASE_FONT_CURRENT_VARIANT_EN - , CLIENT_INTERFACE_VARIANT_RU, CLIENT_INTERFACE_VARIANT_EN); - private static final Pattern METHOD_PATTERN = Pattern.compile(REGEX, + + private static final Pattern METHOD_PATTERN = Pattern.compile(getRegex(), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final HashMap newMethods = new HashMap<>(); @@ -93,6 +81,26 @@ public class DeprecatedMethods8310Diagnostic extends AbstractVisitorDiagnostic { newMethods.put(CLIENT_INTERFACE_VARIANT_EN, "ClientApplication.CurrentInterfaceVariant"); } + private static String getRegex() { + HashMap methodsPair = new HashMap<>(); + methodsPair.put(SET_SHORT_APPLICATION_CAPTION_RU, SET_SHORT_APPLICATION_CAPTION_EN); + methodsPair.put(GET_SHORT_APPLICATION_CAPTION_RU, GET_SHORT_APPLICATION_CAPTION_EN); + methodsPair.put(SET_CLIENT_APPLICATION_CAPTION_RU, SET_CLIENT_APPLICATION_CAPTION_EN); + methodsPair.put(GET_CLIENT_APPLICATION_CAPTION_RU, GET_CLIENT_APPLICATION_CAPTION_EN); + methodsPair.put(BASE_FONT_CURRENT_VARIANT_RU, BASE_FONT_CURRENT_VARIANT_EN); + methodsPair.put(CLIENT_INTERFACE_VARIANT_RU, CLIENT_INTERFACE_VARIANT_EN); + StringBuilder regex = new StringBuilder(); + + methodsPair.forEach((k, v) -> { + regex.append(k); + regex.append("|"); + regex.append(v); + regex.append("|"); + }); + + return regex.toString().substring(0, regex.length() - 1); + } + public DeprecatedMethods8310Diagnostic(DiagnosticInfo info) { super(info); } From a17129eac45dea7291368e3bfd4f351738b36c4a Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Thu, 23 Apr 2020 11:14:48 +0300 Subject: [PATCH 129/444] =?UTF-8?q?=D0=97=D0=B0=D0=BC=D0=B5=D0=BD=D0=B0=20?= =?UTF-8?q?StringBuilder=20=D0=BD=D0=B0=20StringJoiner?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/DeprecatedMethods8310Diagnostic.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java index 2576e6fd086..307dc884194 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java @@ -32,6 +32,7 @@ import org.antlr.v4.runtime.tree.ParseTree; import java.util.HashMap; +import java.util.StringJoiner; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -89,16 +90,14 @@ private static String getRegex() { methodsPair.put(GET_CLIENT_APPLICATION_CAPTION_RU, GET_CLIENT_APPLICATION_CAPTION_EN); methodsPair.put(BASE_FONT_CURRENT_VARIANT_RU, BASE_FONT_CURRENT_VARIANT_EN); methodsPair.put(CLIENT_INTERFACE_VARIANT_RU, CLIENT_INTERFACE_VARIANT_EN); - StringBuilder regex = new StringBuilder(); + StringJoiner regex = new StringJoiner("|"); methodsPair.forEach((k, v) -> { - regex.append(k); - regex.append("|"); - regex.append(v); - regex.append("|"); + regex.add(k); + regex.add(v); }); - return regex.toString().substring(0, regex.length() - 1); + return regex.toString(); } public DeprecatedMethods8310Diagnostic(DiagnosticInfo info) { From 0159fec2943fb466fc4a0f0bcc13474c756cb05e Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Thu, 23 Apr 2020 12:45:26 +0300 Subject: [PATCH 130/444] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D0=BF=D1=83=D1=89?= =?UTF-8?q?=D0=B5=D0=BD=D0=BD=D1=8B=D0=B9=20-q?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java | 2 +- .../github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java index 0a94fe5f271..76b5e3b5ae1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java @@ -124,7 +124,7 @@ private static class ReportersKeys extends ArrayList { private String[] reportersOptions; @Option( - names = {"--silent"}, + names = {"-q", "--silent"}, description = "Silent mode") private boolean silentMode; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java index e0f805bf94b..ac9270a1beb 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java @@ -83,7 +83,7 @@ public class FormatCommand implements Callable { private String srcDirOption; @Option( - names = {"--silent"}, + names = {"-q", "--silent"}, description = "Silent mode") private boolean silentMode; From 8e63625226f86276bf9c4af568b0ceeda7169ed2 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Thu, 23 Apr 2020 12:45:49 +0300 Subject: [PATCH 131/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20-c=20=D0=B2=20=D0=BE=D1=81=D0=BD=D0=BE=D0=B2=D0=BD?= =?UTF-8?q?=D1=83=D1=8E=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4=D1=83,=20?= =?UTF-8?q?=D1=87=D1=82=D0=BE=D0=B1=D1=8B=20=D0=B1=D1=8B=D0=BB=D0=B0=20?= =?UTF-8?q?=D1=87=D0=B5=D0=BB=D0=BE=D0=B2=D0=B5=D1=87=D0=B5=D1=81=D0=BA?= =?UTF-8?q?=D0=B0=D1=8F=20=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../_1c_syntax/bsl/languageserver/BSLLSPLauncher.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java index bbbec506f22..c941a06572c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java @@ -60,6 +60,13 @@ public class BSLLSPLauncher implements Callable { description = "Show this help message and exit") private boolean usageHelpRequested; + @Option( + names = {"-c", "--configuration"}, + description = "Path to language server configuration file", + paramLabel = "", + defaultValue = "") + private String configurationOption; + public static void main(String[] args) { var app = new BSLLSPLauncher(); var cmd = new CommandLine(app); From 437907c3f41fb90e04ca8a548be115518f1f92fc Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Thu, 23 Apr 2020 12:46:01 +0300 Subject: [PATCH 132/444] =?UTF-8?q?=D0=9A=D1=80=D0=B0=D1=81=D0=B8=D0=B2?= =?UTF-8?q?=D0=BE=D1=81=D1=82=D0=B8=20=D0=B8=20=D0=B4=D0=BE=D0=BA=D1=83?= =?UTF-8?q?=D0=BC=D0=B5=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 18 +++++++++--------- docs/en/index.md | 16 ++++++++-------- docs/index.md | 16 ++++++++-------- .../bsl/languageserver/BSLLSPLauncher.java | 1 - .../cli/LanguageServerStartCommand.java | 4 ++-- 5 files changed, 27 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 1ebd58b3e3c..a4571c94557 100644 --- a/README.md +++ b/README.md @@ -39,8 +39,7 @@ java -jar bsl-language-server.jar --help BSL language server -Usage: [-h] [-c=] [COMMAND [ARGS]] -BSL language server on LSP server mode +Usage: bsl-language-server [-h] [-c=] [COMMAND [ARGS]] -c, --configuration= Path to language server configuration file -h, --help Show this help message and exit @@ -48,6 +47,7 @@ Commands: analyze, -a, --analyze Run analysis and get diagnostic info format, -f, --format Format files in source directory version, -v, --version Print version + lsp, --lsp LSP server mode (default) ``` При запуске BSL Language Server в обычном режиме будет запущен сам Language Server, взаимодействующий по протоколу [LSP]([language server protocol](https://microsoft.github.io/language-server-protocol/)). Для взаимодействия используются stdin и stdout. @@ -61,16 +61,16 @@ Commands: Для запуска в режиме анализа используется параметр `--analyze` (сокращенно `-a`). ```sh -Usage: analyze [-h] [--silent] [-c=] [-o=] [-s=] - [-r=]... +Usage: bsl-language-server analyze [-hq] [-c=] [-o=] [-s=] + [-r=]... Run analysis and get diagnostic info -c, --configuration= Path to language server configuration file -h, --help Show this help message and exit -o, --outputDir= Output report directory - -r, --reporter= Reporter key (console, json, junit, tslint, generic) + -q, --silent Silent mode + -r, --reporter= Reporter key (console, junit, json, tslint, generic) -s, --srcDir= Source directory - --silent Silent mode ``` Для указания каталога расположения анализируемых исходников используется параметр `--srcDir` (сокращенно `-s`), за которым следует путь (относительный или абсолютный) к каталогу исходников. @@ -95,11 +95,11 @@ java -Xmx4g -jar bsl-language-server.jar ...остальные параметр Для запуска в режиме форматтера используется параметр `--format` (сокращенно `-f`). ```sh -Usage: format [-h] [--silent] [-s=] +Usage: bsl-language-server format [-hq] [-s=] Format files in source directory -h, --help Show this help message and exit + -q, --silent Silent mode -s, --srcDir= Source directory - --silent Silent mode ``` Для указания каталога расположения форматируемых исходников используется параметр `--srcDir` (сокращенно `-s`), за которым следует путь (относительный или абсолютный) к каталогу исходников. @@ -141,7 +141,7 @@ java -jar bsl-language-server.jar --format --srcDir ./src/cf * Автодополнение методов текущего модуля * Автодополнение контекстных методов (конфигурация 1С и OneScript) * Сигнатура функций -* Подброная всплывающая подсказка по методам +* Подробная всплывающая подсказка по методам * Переход к определению * Поиск мест использования * Предпросмотр определения процедуры diff --git a/docs/en/index.md b/docs/en/index.md index 3e381864672..d389022690c 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -50,8 +50,7 @@ jar-files run through `java -jar path/to/file.jar`. java -jar bsl-language-server.jar --help BSL language server -Usage: [-h] [-c=] [COMMAND [ARGS]] -BSL language server on LSP server mode +Usage: bsl-language-server [-h] [-c=] [COMMAND [ARGS]] -c, --configuration= Path to language server configuration file -h, --help Show this help message and exit @@ -59,6 +58,7 @@ Commands: analyze, -a, --analyze Run analysis and get diagnostic info format, -f, --format Format files in source directory version, -v, --version Print version + lsp, --lsp LSP server mode (default) ``` Starting BSL Language Server in standard mode will run the Language Server communicating via [LSP]([language server protocol](https://microsoft.github.io/language-server-protocol/)). stdin and stdout are used for communication. @@ -72,16 +72,16 @@ By default diagnostics texts are displayed in Russian. To switch the diagnostics To run in analyzer mode use parameter `--analyze` (short `-a`). ```sh -Usage: analyze [-h] [--silent] [-c=] [-o=] [-s=] - [-r=]... +Usage: bsl-language-server analyze [-hq] [-c=] [-o=] [-s=] + [-r=]... Run analysis and get diagnostic info -c, --configuration= Path to language server configuration file -h, --help Show this help message and exit -o, --outputDir= Output report directory - -r, --reporter= Reporter key (console, json, junit, tslint, generic) + -q, --silent Silent mode + -r, --reporter= Reporter key (console, junit, json, tslint, generic) -s, --srcDir= Source directory - --silent Silent mode ``` To set source code folder for analysis use parameter `--srcDir` (short `-s`) followed by the path (relative or absolute) to the source code folder. @@ -107,11 +107,11 @@ java -Xmx4g -jar bsl-language-server.jar ... other parameters To run in formatter mode use parameter `--format` (short `-f`). ```sh -Usage: format [-h] [--silent] [-s=] +Usage: bsl-language-server format [-hq] [-s=] Format files in source directory -h, --help Show this help message and exit + -q, --silent Silent mode -s, --srcDir= Source directory - --silent Silent mode ``` To set source code folder for formatting use parameter `--srcDir` (short `-s`) followed by the path (relative or absolute) to the source code folder. diff --git a/docs/index.md b/docs/index.md index f220196ce59..89819fd003a 100644 --- a/docs/index.md +++ b/docs/index.md @@ -50,8 +50,7 @@ java -jar bsl-language-server.jar --help BSL language server -Usage: [-h] [-c=] [COMMAND [ARGS]] -BSL language server on LSP server mode +Usage: bsl-language-server [-h] [-c=] [COMMAND [ARGS]] -c, --configuration= Path to language server configuration file -h, --help Show this help message and exit @@ -59,6 +58,7 @@ Commands: analyze, -a, --analyze Run analysis and get diagnostic info format, -f, --format Format files in source directory version, -v, --version Print version + lsp, --lsp LSP server mode (default) ``` При запуске BSL Language Server в обычном режиме будет запущен сам Language Server, взаимодействующий по протоколу [LSP]([language server protocol](https://microsoft.github.io/language-server-protocol/)). Для взаимодействия используются stdin и stdout. @@ -72,16 +72,16 @@ Commands: Для запуска в режиме анализа используется параметр `--analyze` (сокращенно `-a`). ```sh -Usage: analyze [-h] [--silent] [-c=] [-o=] [-s=] - [-r=]... +Usage: bsl-language-server analyze [-hq] [-c=] [-o=] [-s=] + [-r=]... Run analysis and get diagnostic info -c, --configuration= Path to language server configuration file -h, --help Show this help message and exit -o, --outputDir= Output report directory - -r, --reporter= Reporter key (console, json, junit, tslint, generic) + -q, --silent Silent mode + -r, --reporter= Reporter key (console, junit, json, tslint, generic) -s, --srcDir= Source directory - --silent Silent mode ``` Для указания каталога расположения анализируемых исходников используется параметр `--srcDir` (сокращенно `-s`), за которым следует путь (относительный или абсолютный) к каталогу исходников. @@ -106,11 +106,11 @@ java -Xmx4g -jar bsl-language-server.jar ...остальные параметр Для запуска в режиме форматтера используется параметр `--format` (сокращенно `-f`). ```sh -Usage: format [-h] [--silent] [-s=] +Usage: bsl-language-server format [-hq] [-s=] Format files in source directory -h, --help Show this help message and exit + -q, --silent Silent mode -s, --srcDir= Source directory - --silent Silent mode ``` Для указания каталога расположения форматируемых исходников используется параметр `--srcDir` (сокращенно `-s`), за которым следует путь (относительный или абсолютный) к каталогу исходников. diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java index c941a06572c..e552d0ead67 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java @@ -39,7 +39,6 @@ @Command( name = "bsl-language-server", - description = "BSL language server", subcommands = { AnalyzeCommand.class, FormatCommand.class, diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java index 0466ff5e196..a0bf35d2c24 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java @@ -48,8 +48,8 @@ * без ключа * Параметры: * -c, (--configuration) <arg> - Путь к конфигурационному файлу BSL Language Server (.bsl-language-server.json). - * Возможно указывать как в абсолютном, так и относительном виде. Если параметр опущен, - * то будут использованы настройки по умолчанию. + * Возможно указывать как в абсолютном, так и относительном виде. + * Если параметр опущен, то будут использованы настройки по умолчанию. * Выводимая информация: * Данный режим используется для взаимодействия с клиентом по протоколу LSP. */ From 7cb61c34a6ad021f878a9a453906e562f565ca39 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Thu, 23 Apr 2020 13:04:10 +0300 Subject: [PATCH 133/444] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20skipped-=D1=82=D0=B5=D1=81=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Внутри кода System.exit, который надо превентить. --- .../github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java index a6016064dff..35b785f7fba 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java @@ -217,6 +217,7 @@ void testWithoutParameters() { } @Test + @ExpectSystemExitWithStatus(0) void testWithoutParametersErrorCfg() { // given String[] args = new String[]{"-c", "src/test/resources/cli/error-trace.json"}; From 70208070877e533859d14f2a30c7aa57e7a20e6e Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Thu, 23 Apr 2020 17:33:24 +0300 Subject: [PATCH 134/444] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B2=D0=B0=D1=8F=20?= =?UTF-8?q?=D1=87=D0=B0=D1=81=D1=82=D1=8C=20=D0=B4=D0=B8=D0=B0=D0=B3=D0=BD?= =?UTF-8?q?=D0=BE=D1=81=D1=82=D0=B8=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DeprecatedAttributes8312Diagnostic.java | 212 ++++++++++++++++++ 1 file changed, 212 insertions(+) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic.java diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic.java new file mode 100644 index 00000000000..c51482c8d4c --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic.java @@ -0,0 +1,212 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCompatibilityMode; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.Trees; +import com.github._1c_syntax.bsl.parser.BSLParser; +import org.antlr.v4.runtime.tree.ParseTree; + +import java.util.HashMap; +import java.util.StringJoiner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.INFO, + scope = DiagnosticScope.BSL, + compatibilityMode = DiagnosticCompatibilityMode.COMPATIBILITY_MODE_8_3_12, + minutesToFix = 1, + tags = { + DiagnosticTag.DEPRECATED + } + +) +public class DeprecatedAttributes8312Diagnostic extends AbstractVisitorDiagnostic { + + private static final String CHART_PLOT_AREA_RU = "ОбластьПостроенияДиаграммы"; + private static final String CHART_PLOT_AREA_EN = "ChartPlotArea"; + // ChartPlotArea deprecated attributes + private static final String SHOW_SCALE_RU = "ОтображатьШкалу"; + private static final String SHOW_SCALE_EN = "ShowScale"; + private static final String SCALE_LINES_RU = "ЛинииШкалы"; + private static final String SCALE_LINES_EN = "ScaleLines"; + private static final String SCALE_COLOR_RU = "ЦветШкалы"; + private static final String SCALE_COLOR_EN = "ScaleColor"; + private static final String SHOW_SERIES_SCALE_LABELS_RU = "ОтображатьПодписиШкалыСерий"; + private static final String SHOW_SERIES_SCALE_LABELS_EN = "ShowSeriesScaleLabels"; + private static final String SHOW_POINTS_SCALE_LABELS_RU = "ОтображатьПодписиШкалыТочек"; + private static final String SHOW_POINTS_SCALE_LABELS_EN = "ShowPointsScaleLabels"; + private static final String SHOW_VALUES_SCALE_LABELS_RU = "ОтображатьПодписиШкалыЗначений"; + private static final String SHOW_VALUES_SCALE_LABELS_EN = "ShowValuesScaleLabels"; + private static final String SHOW_SCALE_VALUE_LINES_RU = "ОтображатьЛинииЗначенийШкалы"; + private static final String SHOW_SCALE_VALUE_LINES_EN = "ShowScaleValueLines"; + private static final String VALUE_SCALE_FORMAT_RU = "ФорматШкалыЗначений"; + private static final String VALUE_SCALE_FORMAT_EN = "ValueScaleFormat"; + private static final String LABELS_ORIENTATION_RU = "ОриентацияМеток"; + private static final String LABELS_ORIENTATION_EN = "LabelsOrientation"; + + private static final String CHART_RU = "Диаграмма"; + private static final String CHART_EN = "Chart"; + private static final String GANTT_CHART_EN = "GanttChart"; + private static final String GANTT_CHART_RU = "ДиаграммаГанта"; + private static final String PIVOT_CHART_EN = "PivotChart"; + private static final String PIVOT_CHART_RU = "СводнаяДиаграмма"; + // General deprecated attributes + private static final String SHOW_LEGEND_EN = "ShowLegend"; + private static final String SHOW_LEGEND_RU = "ОтображатьЛегенду"; + private static final String SHOW_TITLE_EN = "ShowTitle"; + private static final String SHOW_TITLE_RU = "ОтображатьЗаголовок"; + // Chart deprecated attributes + private static final String COLOR_PALETTE_EN = "ColorPalette"; + private static final String COLOR_PALETTE_RU = "ПалитраЦветов"; + private static final String GRADIENT_PALETTE_START_COLOR_EN = "GradientPaletteStartColor"; + private static final String GRADIENT_PALETTE_START_COLOR_RU = "ЦветНачалаГрадиентнойПалитры"; + private static final String GRADIENT_PALETTE_END_COLOR_EN = "GradientPaletteEndColor"; + private static final String GRADIENT_PALETTE_END_COLOR_RU = "ЦветКонцаГрадиентнойПалитры"; + private static final String GRADIENT_PALETTE_MAX_COLORS_EN = "GradientPaletteMaxColors"; + private static final String GRADIENT_PALETTE_MAX_COLORS_RU = "МаксимальноеКоличествоЦветовГрадиентнойПалитры"; + // Chart deprecated methods + private static final String GET_PALETTE_EN = "GetPalette"; + private static final String GET_PALETTE_RU = "ПалитраЦветов"; + private static final String SET_PALETTE_EN = "SetPalette"; + private static final String SET_PALETTE_RU = "УстановитьПалитру"; + + + private static String getDeprecatedAttributesRegex(Metaobject metaobject) { + HashMap attributesPair = new HashMap<>(); + if (metaobject.equals(Metaobject.CHART_PLOT_AREA)) { + attributesPair.put(SHOW_SCALE_RU, SHOW_SCALE_EN); + attributesPair.put(SCALE_LINES_RU, SCALE_LINES_EN); + attributesPair.put(SCALE_COLOR_RU, SCALE_COLOR_EN); + attributesPair.put(SHOW_SERIES_SCALE_LABELS_RU, SHOW_SERIES_SCALE_LABELS_EN); + attributesPair.put(SHOW_POINTS_SCALE_LABELS_RU, SHOW_POINTS_SCALE_LABELS_EN); + attributesPair.put(SHOW_VALUES_SCALE_LABELS_RU, SHOW_VALUES_SCALE_LABELS_EN); + attributesPair.put(SHOW_SCALE_VALUE_LINES_RU, SHOW_SCALE_VALUE_LINES_EN); + attributesPair.put(VALUE_SCALE_FORMAT_RU, VALUE_SCALE_FORMAT_EN); + attributesPair.put(LABELS_ORIENTATION_RU, LABELS_ORIENTATION_EN); + } else if (metaobject.equals(Metaobject.CHART)) { + attributesPair.put(SHOW_LEGEND_EN, SHOW_LEGEND_RU); + attributesPair.put(SHOW_TITLE_EN, SHOW_TITLE_RU); + attributesPair.put(COLOR_PALETTE_EN, COLOR_PALETTE_RU); + attributesPair.put(GRADIENT_PALETTE_START_COLOR_EN, GRADIENT_PALETTE_START_COLOR_RU); + attributesPair.put(GRADIENT_PALETTE_END_COLOR_EN, GRADIENT_PALETTE_END_COLOR_RU); + attributesPair.put(GRADIENT_PALETTE_MAX_COLORS_EN, GRADIENT_PALETTE_MAX_COLORS_RU); + } + StringJoiner regex = new StringJoiner("|"); + + attributesPair.forEach((k, v) -> { + regex.add(k); + regex.add(v); + }); + + return regex.toString(); + } + + private static String getChartMethodsRegex() { + HashMap attributesPair = new HashMap<>(); + + attributesPair.put(GET_PALETTE_EN, GET_PALETTE_RU); + attributesPair.put(SET_PALETTE_EN, SET_PALETTE_RU); + + StringJoiner regex = new StringJoiner("|"); + + attributesPair.forEach((k, v) -> { + regex.add(k); + regex.add(v); + }); + + return regex.toString(); + } + + private static String getMetaobjectNameRegex(Metaobject metaobject) { + HashMap namePair = new HashMap<>(); + if (metaobject.equals(Metaobject.CHART_PLOT_AREA)) { + namePair.put(CHART_PLOT_AREA_RU, CHART_PLOT_AREA_EN); + } else if (metaobject.equals(Metaobject.CHART)) { + namePair.put(CHART_RU, CHART_EN); + namePair.put(GANTT_CHART_EN, GANTT_CHART_RU); + namePair.put(PIVOT_CHART_EN, PIVOT_CHART_RU); + } + StringJoiner regex = new StringJoiner("|"); + + namePair.forEach((k, v) -> { + regex.add(k); + regex.add(v); + }); + + return regex.toString(); + } + + private static final Pattern CHART_PLOT_AREA_ATTRIBUTES_PATTERN = Pattern.compile( + getDeprecatedAttributesRegex(Metaobject.CHART_PLOT_AREA), + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + + private static final Pattern CHART_ATTRIBUTES_PATTERN = Pattern.compile( + getDeprecatedAttributesRegex(Metaobject.CHART), + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + + private static final Pattern CHART_METHODS_PATTERN = Pattern.compile( + getChartMethodsRegex(), + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + + private static final Pattern CHART_PLOT_AREA_NAME_PATTERN = Pattern.compile( + getMetaobjectNameRegex(Metaobject.CHART_PLOT_AREA), + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + + private static final Pattern CHART_NAME_PATTERN = Pattern.compile( + getMetaobjectNameRegex(Metaobject.CHART), + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + + + public DeprecatedAttributes8312Diagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + public ParseTree visitAccessProperty(BSLParser.AccessPropertyContext ctx) { + + if (isDeprecated(ctx, CHART_PLOT_AREA_NAME_PATTERN, CHART_PLOT_AREA_ATTRIBUTES_PATTERN) + || isDeprecated(ctx, CHART_NAME_PATTERN, CHART_ATTRIBUTES_PATTERN)) { + diagnosticStorage.addDiagnostic(ctx); + } + + return super.visitAccessProperty(ctx); + } + + private boolean isDeprecated(BSLParser.AccessPropertyContext ctx, + Pattern objectNamePattern, + Pattern deprecatedAttributesPattern) { + + Matcher matcherChartPlotArea = deprecatedAttributesPattern.matcher(ctx.getText().substring(1)); + + if (matcherChartPlotArea.matches()) { + var complexCtx = Trees.getAncestorByRuleIndex(ctx, BSLParser.RULE_complexIdentifier); + if (complexCtx == null) { + complexCtx = Trees.getAncestorByRuleIndex(ctx, BSLParser.RULE_lValue); + if (complexCtx == null) { + return false; + } + } + + Matcher matcherChartPlotAreaName = objectNamePattern.matcher( + complexCtx.getStart().getText() + ); + return matcherChartPlotAreaName.matches(); + } + + return false; + } + + private enum Metaobject{ + CHART, + CHART_PLOT_AREA + } +} + + From 502066cde005c8f80ec9410ece5e4e63a25d98f3 Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Thu, 23 Apr 2020 20:55:08 +0300 Subject: [PATCH 135/444] =?UTF-8?q?=D0=A7=D0=B5=D1=80=D0=BD=D0=BE=D0=B2?= =?UTF-8?q?=D0=BE=D0=B9=20=D0=BA=D0=BE=D0=BC=D0=BC=D0=B8=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/DeprecatedAttributes8312.md | 36 +++++ docs/diagnostics/index.md | 5 +- .../diagnostics/DeprecatedAttributes8312.md | 36 +++++ docs/en/diagnostics/index.md | 5 +- .../DeprecatedAttributes8312Diagnostic.java | 148 +++++++++++++++--- .../configuration/parameters-schema.json | 10 ++ .../languageserver/configuration/schema.json | 3 + ...atedAttributes8312Diagnostic_en.properties | 3 + ...atedAttributes8312Diagnostic_ru.properties | 3 + ...eprecatedAttributes8312DiagnosticTest.java | 46 ++++++ .../DeprecatedAttributes8312Diagnostic.bsl | 80 ++++++++++ 11 files changed, 346 insertions(+), 29 deletions(-) create mode 100644 docs/diagnostics/DeprecatedAttributes8312.md create mode 100644 docs/en/diagnostics/DeprecatedAttributes8312.md create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312DiagnosticTest.java create mode 100644 src/test/resources/diagnostics/DeprecatedAttributes8312Diagnostic.bsl diff --git a/docs/diagnostics/DeprecatedAttributes8312.md b/docs/diagnostics/DeprecatedAttributes8312.md new file mode 100644 index 00000000000..252b10a1d49 --- /dev/null +++ b/docs/diagnostics/DeprecatedAttributes8312.md @@ -0,0 +1,36 @@ +# Устаревшее использование объектов (DeprecatedAttributes8312) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Дефект кода` | `BSL` | `Информационный` | `Да` | `1` | `deprecated` | + + +## Описание диагностики + + +## Примеры + + +## Источники + + + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:DeprecatedAttributes8312-off +// BSLLS:DeprecatedAttributes8312-on +``` + +### Параметр конфигурационного файла + +```json +"DeprecatedAttributes8312": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index eac9427cc9b..c29cd957733 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,9 +8,9 @@ ## Список реализованных диагностик -Общее количество: **93** +Общее количество: **94** -* Дефект кода: **58** +* Дефект кода: **59** * Уязвимость: **2** * Ошибка: **31** * Потенциальная уязвимость: **2** @@ -32,6 +32,7 @@ | [CyclomaticComplexity](CyclomaticComplexity.md) | Цикломатическая сложность | Да | Критичный | Дефект кода | `brainoverload` | | [DataExchangeLoading](DataExchangeLoading.md) | Отсутствует проверка признака ОбменДанными.Загрузка в обработчике событий объекта | Да | Критичный | Ошибка | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Удаление элемента при обходе коллекции посредством оператора "Для каждого ... Из ... Цикл" | Да | Важный | Ошибка | `standard`
`error` | +| [DeprecatedAttributes8312](DeprecatedAttributes8312.md) | Устаревшее использование объектов | Да | Информационный | Дефект кода | `deprecated` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Использование устаревшего метода "ТекущаяДата" | Да | Важный | Ошибка | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Использование устаревшего метода "Найти" | Да | Незначительный | Дефект кода | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Ограничение на использование устаревшего метода "Сообщить" | Да | Незначительный | Дефект кода | `standard`
`deprecated` | diff --git a/docs/en/diagnostics/DeprecatedAttributes8312.md b/docs/en/diagnostics/DeprecatedAttributes8312.md new file mode 100644 index 00000000000..055a3f60cc5 --- /dev/null +++ b/docs/en/diagnostics/DeprecatedAttributes8312.md @@ -0,0 +1,36 @@ +# (DeprecatedAttributes8312) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Code smell` | `BSL` | `Info` | `Yes` | `1` | `deprecated` | + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:DeprecatedAttributes8312-off +// BSLLS:DeprecatedAttributes8312-on +``` + +### Parameter for config + +```json +"DeprecatedAttributes8312": false +``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 40af697dbe0..7eb695f67f9 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,10 +8,10 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **93** +Total: **94** * Error: **31** -* Code smell: **58** +* Code smell: **59** * Vulnerability: **2** * Security Hotspot: **2** @@ -32,6 +32,7 @@ Total: **93** | [CyclomaticComplexity](CyclomaticComplexity.md) | Cyclomatic complexity | Yes | Critical | Code smell | `brainoverload` | | [DataExchangeLoading](DataExchangeLoading.md) | There is no check for the attribute DataExchange.Load in the object's event handler | Yes | Critical | Error | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Deleting an item when iterating through collection using the operator "For each ... In ... Do" | Yes | Major | Error | `standard`
`error` | +| [DeprecatedAttributes8312](DeprecatedAttributes8312.md) | | Yes | Info | Code smell | `deprecated` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Using of the deprecated method "CurrentDate" | Yes | Major | Error | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Using of the deprecated method "Find" | Yes | Minor | Code smell | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Restriction on the use of deprecated "Message" method | Yes | Minor | Code smell | `standard`
`deprecated` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic.java index c51482c8d4c..59d1653da67 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic.java @@ -1,3 +1,24 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCompatibilityMode; @@ -9,9 +30,11 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.utils.Trees; import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; import java.util.HashMap; +import java.util.Objects; import java.util.StringJoiner; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -35,9 +58,9 @@ public class DeprecatedAttributes8312Diagnostic extends AbstractVisitorDiagnosti private static final String SHOW_SCALE_RU = "ОтображатьШкалу"; private static final String SHOW_SCALE_EN = "ShowScale"; private static final String SCALE_LINES_RU = "ЛинииШкалы"; - private static final String SCALE_LINES_EN = "ScaleLines"; + //private static final String SCALE_LINES_EN = "ScaleLines"; private static final String SCALE_COLOR_RU = "ЦветШкалы"; - private static final String SCALE_COLOR_EN = "ScaleColor"; + //private static final String SCALE_COLOR_EN = "ScaleColor"; private static final String SHOW_SERIES_SCALE_LABELS_RU = "ОтображатьПодписиШкалыСерий"; private static final String SHOW_SERIES_SCALE_LABELS_EN = "ShowSeriesScaleLabels"; private static final String SHOW_POINTS_SCALE_LABELS_RU = "ОтображатьПодписиШкалыТочек"; @@ -73,17 +96,38 @@ public class DeprecatedAttributes8312Diagnostic extends AbstractVisitorDiagnosti private static final String GRADIENT_PALETTE_MAX_COLORS_RU = "МаксимальноеКоличествоЦветовГрадиентнойПалитры"; // Chart deprecated methods private static final String GET_PALETTE_EN = "GetPalette"; - private static final String GET_PALETTE_RU = "ПалитраЦветов"; + private static final String GET_PALETTE_RU = "ПолучитьПалитру"; private static final String SET_PALETTE_EN = "SetPalette"; private static final String SET_PALETTE_RU = "УстановитьПалитру"; + // Global context enum + private static final String CHART_LABELS_ORIENTATION_EN = "ChartLabelsOrientation"; + private static final String CHART_LABELS_ORIENTATION_RU = "ОриентацияМетокДиаграммы"; + + // Global context enum attribute + private static final String CHILD_FORM_ITEMS_GROUP_EN = "ChildFormItemsGroup"; + private static final String CHILD_FORM_ITEMS_GROUP_RU = "ГруппировкаПодчиненныхЭлементовФормы"; + private static final String CHILD_FORM_ITEMS_GROUP_HORIZONTAL_EN = "Horizontal"; + private static final String CHILD_FORM_ITEMS_GROUP_HORIZONTAL_RU = "Горизонтальная"; + + // Global context methods + private static final String CLEAR_EVENT_LOG_EN = "ClearEventLog"; + private static final String CLEAR_EVENT_LOG_RU = "ОчиститьЖурналРегистрации"; + + private static final HashMap NEW_ATTRIBUTES = new HashMap<>(); + static { + NEW_ATTRIBUTES.put(SHOW_SCALE_RU, "ОтображатьШкалы"); + NEW_ATTRIBUTES.put(SHOW_SCALE_EN, "ShowScales"); + NEW_ATTRIBUTES.put(SCALE_LINES_RU, "ЛинииШкал"); + NEW_ATTRIBUTES.put(SCALE_COLOR_RU, "ЦветШкал"); + } private static String getDeprecatedAttributesRegex(Metaobject metaobject) { HashMap attributesPair = new HashMap<>(); if (metaobject.equals(Metaobject.CHART_PLOT_AREA)) { attributesPair.put(SHOW_SCALE_RU, SHOW_SCALE_EN); - attributesPair.put(SCALE_LINES_RU, SCALE_LINES_EN); - attributesPair.put(SCALE_COLOR_RU, SCALE_COLOR_EN); + attributesPair.put(SCALE_LINES_RU, ""); + attributesPair.put(SCALE_COLOR_RU, ""); attributesPair.put(SHOW_SERIES_SCALE_LABELS_RU, SHOW_SERIES_SCALE_LABELS_EN); attributesPair.put(SHOW_POINTS_SCALE_LABELS_RU, SHOW_POINTS_SCALE_LABELS_EN); attributesPair.put(SHOW_VALUES_SCALE_LABELS_RU, SHOW_VALUES_SCALE_LABELS_EN); @@ -97,6 +141,8 @@ private static String getDeprecatedAttributesRegex(Metaobject metaobject) { attributesPair.put(GRADIENT_PALETTE_START_COLOR_EN, GRADIENT_PALETTE_START_COLOR_RU); attributesPair.put(GRADIENT_PALETTE_END_COLOR_EN, GRADIENT_PALETTE_END_COLOR_RU); attributesPair.put(GRADIENT_PALETTE_MAX_COLORS_EN, GRADIENT_PALETTE_MAX_COLORS_RU); + } else if (metaobject.equals(Metaobject.ENUM_ITEMS_GROUP)) { + attributesPair.put(CHILD_FORM_ITEMS_GROUP_HORIZONTAL_EN, CHILD_FORM_ITEMS_GROUP_HORIZONTAL_RU); } StringJoiner regex = new StringJoiner("|"); @@ -108,11 +154,13 @@ private static String getDeprecatedAttributesRegex(Metaobject metaobject) { return regex.toString(); } - private static String getChartMethodsRegex() { + private static String getDeprecatedMethodsRegex(Metaobject metaobject) { HashMap attributesPair = new HashMap<>(); - attributesPair.put(GET_PALETTE_EN, GET_PALETTE_RU); - attributesPair.put(SET_PALETTE_EN, SET_PALETTE_RU); + if (metaobject.equals(Metaobject.CHART)) { + attributesPair.put(GET_PALETTE_EN, GET_PALETTE_RU); + attributesPair.put(SET_PALETTE_EN, SET_PALETTE_RU); + } StringJoiner regex = new StringJoiner("|"); @@ -132,6 +180,8 @@ private static String getMetaobjectNameRegex(Metaobject metaobject) { namePair.put(CHART_RU, CHART_EN); namePair.put(GANTT_CHART_EN, GANTT_CHART_RU); namePair.put(PIVOT_CHART_EN, PIVOT_CHART_RU); + } else if (metaobject.equals(Metaobject.ENUM_ITEMS_GROUP)) { + namePair.put(CHILD_FORM_ITEMS_GROUP_EN, CHILD_FORM_ITEMS_GROUP_RU); } StringJoiner regex = new StringJoiner("|"); @@ -152,7 +202,7 @@ private static String getMetaobjectNameRegex(Metaobject metaobject) { Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final Pattern CHART_METHODS_PATTERN = Pattern.compile( - getChartMethodsRegex(), + getDeprecatedMethodsRegex(Metaobject.CHART), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final Pattern CHART_PLOT_AREA_NAME_PATTERN = Pattern.compile( @@ -163,49 +213,97 @@ private static String getMetaobjectNameRegex(Metaobject metaobject) { getMetaobjectNameRegex(Metaobject.CHART), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + private static final Pattern CHART_LABELS_ORIENTATION_PATTERN = Pattern.compile( + CHART_LABELS_ORIENTATION_EN + "|" + CHART_LABELS_ORIENTATION_RU, + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + + private static final Pattern CHILD_FORM_ITEMS_GROUP_NAME_PATTERN = Pattern.compile( + getMetaobjectNameRegex(Metaobject.ENUM_ITEMS_GROUP), + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + + private static final Pattern CHILD_FORM_ITEMS_GROUP_ATTRIBUTE_PATTERN = Pattern.compile( + getDeprecatedAttributesRegex(Metaobject.ENUM_ITEMS_GROUP), + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + + private static final Pattern CLEAR_EVENT_LOG_PATTERN = Pattern.compile( + CLEAR_EVENT_LOG_EN + "|" + CLEAR_EVENT_LOG_RU, + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + public DeprecatedAttributes8312Diagnostic(DiagnosticInfo info) { super(info); } @Override - public ParseTree visitAccessProperty(BSLParser.AccessPropertyContext ctx) { + public ParseTree visitMethodCall(BSLParser.MethodCallContext ctx) { + + if (CHART_METHODS_PATTERN.matcher(ctx.methodName().getText()).matches()) { + diagnosticStorage.addDiagnostic(ctx); + } + + return super.visitMethodCall(ctx); + } - if (isDeprecated(ctx, CHART_PLOT_AREA_NAME_PATTERN, CHART_PLOT_AREA_ATTRIBUTES_PATTERN) - || isDeprecated(ctx, CHART_NAME_PATTERN, CHART_ATTRIBUTES_PATTERN)) { + @Override + public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { + if (CLEAR_EVENT_LOG_PATTERN.matcher(ctx.methodName().getText()).matches()) { diagnosticStorage.addDiagnostic(ctx); } + return super.visitGlobalMethodCall(ctx); + } + + @Override + public ParseTree visitAccessProperty(BSLParser.AccessPropertyContext ctx) { + + HashMap patternsToCheck = new HashMap<>(); + patternsToCheck.put(CHART_PLOT_AREA_NAME_PATTERN, CHART_PLOT_AREA_ATTRIBUTES_PATTERN); + patternsToCheck.put(CHART_NAME_PATTERN, CHART_ATTRIBUTES_PATTERN); + patternsToCheck.put(CHILD_FORM_ITEMS_GROUP_NAME_PATTERN, CHILD_FORM_ITEMS_GROUP_ATTRIBUTE_PATTERN); + + patternsToCheck.forEach((k, v) -> checkDeprecatedAttributes(ctx, k, v)); return super.visitAccessProperty(ctx); } - private boolean isDeprecated(BSLParser.AccessPropertyContext ctx, - Pattern objectNamePattern, - Pattern deprecatedAttributesPattern) { + @Override + public ParseTree visitComplexIdentifier(BSLParser.ComplexIdentifierContext ctx) { + if (CHART_LABELS_ORIENTATION_PATTERN.matcher(ctx.getStart().getText()).matches()) { + diagnosticStorage.addDiagnostic(ctx); + } + + return super.visitComplexIdentifier(ctx); + } + + private void checkDeprecatedAttributes(BSLParserRuleContext ctx, + Pattern objectNamePattern, + Pattern deprecatedAttributesPattern) { - Matcher matcherChartPlotArea = deprecatedAttributesPattern.matcher(ctx.getText().substring(1)); + Matcher deprecatedAttributesMatcher = deprecatedAttributesPattern.matcher(ctx.getText().substring(1)); - if (matcherChartPlotArea.matches()) { + if (deprecatedAttributesMatcher.matches()) { var complexCtx = Trees.getAncestorByRuleIndex(ctx, BSLParser.RULE_complexIdentifier); if (complexCtx == null) { complexCtx = Trees.getAncestorByRuleIndex(ctx, BSLParser.RULE_lValue); if (complexCtx == null) { - return false; + return; } } + if (objectNamePattern.matcher(complexCtx.getStart().getText()).matches()) { + String deprecatedAttribute = deprecatedAttributesMatcher.group(); + String message = String.format(info.getResourceString("deprecatedAttributeMessage"), + deprecatedAttribute, + Objects.requireNonNullElseGet(NEW_ATTRIBUTES.get(deprecatedAttribute), String::new)); - Matcher matcherChartPlotAreaName = objectNamePattern.matcher( - complexCtx.getStart().getText() - ); - return matcherChartPlotAreaName.matches(); - } + diagnosticStorage.addDiagnostic(ctx, info.getMessage(message)); + } - return false; + } } private enum Metaobject{ CHART, - CHART_PLOT_AREA + CHART_PLOT_AREA, + ENUM_ITEMS_GROUP } } diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index aab363c6a53..8f2d0d04bbe 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -206,6 +206,16 @@ "title": "Deleting an item when iterating through collection using the operator \"For each ... In ... Do\"", "$id": "#/definitions/DeletingCollectionItem" }, + "DeprecatedAttributes8312": { + "description": "", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "", + "$id": "#/definitions/DeprecatedAttributes8312" + }, "DeprecatedCurrentDate": { "description": "Using of the deprecated method \"CurrentDate\"", "default": true, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index e4e5668caff..20141ed863e 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -68,6 +68,9 @@ "DeletingCollectionItem": { "$ref": "parameters-schema.json#/definitions/DeletingCollectionItem" }, + "DeprecatedAttributes8312": { + "$ref": "parameters-schema.json#/definitions/DeprecatedAttributes8312" + }, "DeprecatedCurrentDate": { "$ref": "parameters-schema.json#/definitions/DeprecatedCurrentDate" }, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic_en.properties new file mode 100644 index 00000000000..f56bffb6cd7 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic_en.properties @@ -0,0 +1,3 @@ +diagnosticMessage= +diagnosticName= +deprecatedAttributeMessage=\"%s\" attribute is deprecated. You should use \"%s\" diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic_ru.properties new file mode 100644 index 00000000000..f20e7315b97 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic_ru.properties @@ -0,0 +1,3 @@ +diagnosticMessage=%s +diagnosticName=Устаревшее использование объектов +deprecatedAttributeMessage=Атрибут \"%s\" устарел. Вместо него стоит использовать \"%s\" diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312DiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312DiagnosticTest.java new file mode 100644 index 00000000000..19d2c26bf87 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312DiagnosticTest.java @@ -0,0 +1,46 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class DeprecatedAttributes8312DiagnosticTest extends AbstractDiagnosticTest { + DeprecatedAttributes8312DiagnosticTest() { + super(DeprecatedAttributes8312Diagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(46); +// assertThat(diagnostics, true) +// .hasRange(6, 0, 6, 20); + + } +} diff --git a/src/test/resources/diagnostics/DeprecatedAttributes8312Diagnostic.bsl b/src/test/resources/diagnostics/DeprecatedAttributes8312Diagnostic.bsl new file mode 100644 index 00000000000..1916e3b2c8c --- /dev/null +++ b/src/test/resources/diagnostics/DeprecatedAttributes8312Diagnostic.bsl @@ -0,0 +1,80 @@ +Процедура Тест() + тест = ОбластьПостроенияДиаграммы.ОтображатьШкалу; + ОбластьПостроенияДиаграммы.ЛинииШкалы = Ложь; + ОбластьПостроенияДиаграммы.ЦветШкалы = Ложь; + ОбластьПостроенияДиаграммы.ОтображатьПодписиШкалыСерий = Ложь; + ОбластьПостроенияДиаграммы.ОтображатьПодписиШкалыТочек = Ложь; + ОбластьПостроенияДиаграммы.ОтображатьПодписиШкалыЗначений = Ложь; + ОбластьПостроенияДиаграммы.ОтображатьЛинииЗначенийШкалы = Ложь; + ОбластьПостроенияДиаграммы.ФорматШкалыЗначений = Ложь; + ОбластьПостроенияДиаграммы.ОриентацияМеток = Ложь; +КонецПроцедуры + +Procedure Test() + ChartPlotArea.ShowScale = True; + ChartPlotArea.ShowSeriesScaleLabels = True; + ChartPlotArea.ShowPointsScaleLabels = True; + ChartPlotArea.ShowValuesScaleLabels = True; + ChartPlotArea.ShowScaleValueLines = True; + ChartPlotArea.ValueScaleFormat = True; + ChartPlotArea.LabelsOrientation = True; +EndProcedure + +Процедура Тест2() + Диаграмма.ОтображатьЛегенду = Истина; + Диаграмма.ОтображатьЗаголовок = Истина; + ДиаграммаГанта.ОтображатьЛегенду = Истина; + ДиаграммаГанта.ОтображатьЗаголовок = Истина; + СводнаяДиаграмма.ОтображатьЛегенду = Истина; + СводнаяДиаграмма.ОтображатьЗаголовок = Истина; + + Диаграмма.ПалитраЦветов = Истина; + Диаграмма.ЦветНачалаГрадиентнойПалитры = Истина; + Диаграмма.ЦветКонцаГрадиентнойПалитры = Истина; + Диаграмма.МаксимальноеКоличествоЦветовГрадиентнойПалитры = Истина; + + Тест = Диаграмма.ПолучитьПалитру(); + Диаграмма.УстановитьПалитру(Неопределено); +КонецПроцедуры + +Procedure Test2() + Chart.ShowLegend = True; + GanttChart.ShowLegend = True; + PivotChart.ShowLegend = True; + Chart.ShowTitle = True; + GanttChart.ShowTitle = True; + PivotChart.ShowTitle = True; + + Chart.ColorPalette = True; + Chart.GradientPaletteStartColor = True; + Chart.GradientPaletteEndColor = True; + Chart.GradientPaletteMaxColors = True; + + Chart.GetPalette(); + Chart.SetPalette(True); + +EndProcedure + +Процедура Тест3() + Ориентация = ОриентацияМетокДиаграммы.Авто; +КонецПроцедуры + +Procedure Test3() + test = ChartLabelsOrientation.Auto; +EndProcedure + +Процедура Тест4() + ОчиститьЖурналРегистрации(Отбор); +КонецПроцедуры + +Procedure Test4() + ClearEventLog(Filter); +EndProcedure + +Процедура Тест5() + Группировка = ГруппировкаПодчиненныхЭлементовФормы.Горизонтальная; +КонецПроцедуры + +Procedure Test5() + test = ChildFormItemsGroup.Horizontal; +EndProcedure From 67e567f496821906e2238019961ed6222cc65a01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=B2=D0=B0=D0=BD=D0=BE=D0=B2=20=D0=AD=D0=B4=D1=83?= =?UTF-8?q?=D0=B0=D1=80=D0=B4?= Date: Thu, 23 Apr 2020 21:30:04 +0300 Subject: [PATCH 136/444] =?UTF-8?q?=D0=A0=D0=B5=D1=84=D0=B0=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D0=BD=D0=B3=20=D0=BE=D0=B1=D1=80=D0=B0=D1=89?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BA=20=D1=82=D0=BE=D0=BA=D0=B8?= =?UTF-8?q?=D0=BD=D0=B0=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ExcessiveAutoTestCheckDiagnostic.java | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java index 6f62abf9e05..482dd9a9798 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java @@ -28,8 +28,10 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; +import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.ParseTree; +import java.util.List; import java.util.regex.Pattern; @DiagnosticMetadata( @@ -74,13 +76,15 @@ private boolean expressionMatchesPattern(BSLParser.ExpressionContext expression) } private boolean codeBlockWithOnlyReturn(BSLParser.CodeBlockContext codeBlock) { - return codeBlock - .getTokens() - .stream() - .map(t -> t.getType()) - .filter(t -> t != BSLParser.WHITE_SPACE) - .filter(t -> t != BSLParser.LINE_COMMENT) - .filter(t -> t != BSLParser.SEMICOLON) - .noneMatch(t -> t != BSLParser.RETURN_KEYWORD); + List tokens = codeBlock.getTokens(); + + if (tokens.size() == 2) { + return tokens.get(0).getType() == BSLParser.RETURN_KEYWORD + && tokens.get(1).getType() == BSLParser.SEMICOLON; + } else if (tokens.size() == 1) { + return tokens.get(0).getType() == BSLParser.RETURN_KEYWORD; + } + + return false; } } From cf06f3ba97f33c794d950f3e7ce606cb9ca53960 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Fri, 24 Apr 2020 08:57:02 +0300 Subject: [PATCH 137/444] =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BE=D0=B1=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=BA=D1=83?= =?UTF-8?q?=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B4=D0=B0=D0=BD=D0=BD=D0=BE=D0=B3?= =?UTF-8?q?=D0=BE=20=D0=BF=D0=B0=D1=80=D0=B0=D0=BC=D0=B5=D1=82=D1=80=D0=B0?= =?UTF-8?q?=20=D0=B2=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4=D1=83=20=D0=BF?= =?UTF-8?q?=D0=BE=20=D1=83=D0=BC=D0=BE=D0=BB=D1=87=D0=B0=D0=BD=D0=B8=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../bsl/languageserver/BSLLSPLauncher.java | 7 ++++++- .../languageserver/BSLLSPLauncherTest.java | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java index e552d0ead67..003959134eb 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java @@ -78,7 +78,12 @@ public static void main(String[] args) { // выполнение проверки строки запуска в попытке, т.к. парсер при нахождении // неизвестных параметров выдает ошибку try { - cmd.parseArgs(args); + var parseResult = cmd.parseArgs(args); + // если переданы параметры без команды и это не справка + // то считаем, что параметры для команды по умолчанию + if(!parseResult.hasSubcommand() && !parseResult.isUsageHelpRequested()) { + args = addDefaultCommand(args); + } } catch (ParameterException ex) { // если поймали ошибку, а имя команды не передано, подставим команду и посмотрим, // вдруг заработает diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java index 35b785f7fba..0c894344c74 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java @@ -216,6 +216,25 @@ void testWithoutParameters() { assertThat(errContent.toString()).isEmpty(); } + @Test + void testWithoutCommandWithConfig() { + // проверим, что перешли в команду lsp + + // given + String[] args = "-c .".split(" "); + + // when + try { + BSLLSPLauncher.main(args); + } catch (RuntimeException ignored) { + // catch prevented system.exit call + } + + // then + assertThat(outContent.toString()).isEmpty(); + assertThat(errContent.toString()).contains("LanguageServerStartCommand"); + } + @Test @ExpectSystemExitWithStatus(0) void testWithoutParametersErrorCfg() { From 70663a2a285fc839d64a7916dc5016d8cc232c49 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Fri, 24 Apr 2020 09:04:42 +0300 Subject: [PATCH 138/444] fix test --- .../github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java index 0c894344c74..8016980e416 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java @@ -236,7 +236,6 @@ void testWithoutCommandWithConfig() { } @Test - @ExpectSystemExitWithStatus(0) void testWithoutParametersErrorCfg() { // given String[] args = new String[]{"-c", "src/test/resources/cli/error-trace.json"}; From f9ab293d7240c52a7dada2c818203b7f9c54452f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=98=D0=B2=D0=B0=D0=BD=D0=BE=D0=B2=20=D0=AD=D0=B4=D1=83?= =?UTF-8?q?=D0=B0=D1=80=D0=B4?= Date: Fri, 24 Apr 2020 13:21:40 +0300 Subject: [PATCH 139/444] =?UTF-8?q?=D0=A3=D0=B1=D1=80=D0=B0=D0=BB=20getTok?= =?UTF-8?q?ens=20=D0=B2=D0=BE=D0=BE=D0=B1=D1=89=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ExcessiveAutoTestCheckDiagnostic.java | 13 +++++++------ .../ExcessiveAutoTestCheckDiagnostic.bsl | 8 +++++++- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java index 482dd9a9798..6adea7f6093 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java @@ -76,13 +76,14 @@ private boolean expressionMatchesPattern(BSLParser.ExpressionContext expression) } private boolean codeBlockWithOnlyReturn(BSLParser.CodeBlockContext codeBlock) { - List tokens = codeBlock.getTokens(); + List statements = codeBlock.statement(); - if (tokens.size() == 2) { - return tokens.get(0).getType() == BSLParser.RETURN_KEYWORD - && tokens.get(1).getType() == BSLParser.SEMICOLON; - } else if (tokens.size() == 1) { - return tokens.get(0).getType() == BSLParser.RETURN_KEYWORD; + if (statements.size() == 1) { + BSLParser.CompoundStatementContext compoundStatement = statements.get(0).compoundStatement(); + + if (compoundStatement != null) { + return compoundStatement.returnStatement() != null; + } } return false; diff --git a/src/test/resources/diagnostics/ExcessiveAutoTestCheckDiagnostic.bsl b/src/test/resources/diagnostics/ExcessiveAutoTestCheckDiagnostic.bsl index 3dc0a5f7e61..ccf824e2e73 100644 --- a/src/test/resources/diagnostics/ExcessiveAutoTestCheckDiagnostic.bsl +++ b/src/test/resources/diagnostics/ExcessiveAutoTestCheckDiagnostic.bsl @@ -83,4 +83,10 @@ EndProcedure Возврат; -КонецЕсли; \ No newline at end of file +КонецЕсли; + +If List.Property("AutoTest") Then // No error + + List.Delete("AutoTest"); + +EndIf; \ No newline at end of file From ccd796514ec427b4e92bf6b3f5d7625119dd2e25 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Fri, 24 Apr 2020 17:02:44 +0300 Subject: [PATCH 140/444] Update Typo.md --- docs/diagnostics/Typo.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/docs/diagnostics/Typo.md b/docs/diagnostics/Typo.md index 95cf7f7ec95..3f608c944b8 100644 --- a/docs/diagnostics/Typo.md +++ b/docs/diagnostics/Typo.md @@ -19,11 +19,7 @@ ## Источники - * Полезная информация: [Русский язык для всех](http://gramota.ru/) * [Источник](https://languagetool.org/ru/) From a03b96328bbc925700c00f138cf0581974341311 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Fri, 24 Apr 2020 17:05:00 +0300 Subject: [PATCH 141/444] =?UTF-8?q?=D0=A3=D1=82=D0=BE=D1=87=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8?= =?UTF-8?q?=20=D0=BF=D0=BE=20Typo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/Typo.md | 2 +- docs/en/diagnostics/Typo.md | 2 +- .../bsl/languageserver/configuration/parameters-schema.json | 4 ++-- .../languageserver/diagnostics/TypoDiagnostic_en.properties | 2 +- .../languageserver/diagnostics/TypoDiagnostic_ru.properties | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/diagnostics/Typo.md b/docs/diagnostics/Typo.md index 3f608c944b8..95599089dc3 100644 --- a/docs/diagnostics/Typo.md +++ b/docs/diagnostics/Typo.md @@ -8,7 +8,7 @@ | Имя | Тип | Описание | Значение по умолчанию | | :-: | :-: | :-- | :-: | -| `userWordsToIgnore` | `Строка` | ```Пользовательский словарь исключений``` | `````` | +| `userWordsToIgnore` | `Строка` | ```Пользовательский словарь исключений (через запятую, без пробелов)``` | `````` | | `minWordLength` | `Целое` | ```Минимальная длина проверяемых слов``` | ```3``` | diff --git a/docs/en/diagnostics/Typo.md b/docs/en/diagnostics/Typo.md index 869dae1b61a..8c2289de6e5 100644 --- a/docs/en/diagnostics/Typo.md +++ b/docs/en/diagnostics/Typo.md @@ -8,7 +8,7 @@ | Name | Type | Description | Default value | | :-: | :-: | :-- | :-: | -| `userWordsToIgnore` | `String` | ```Dictionary for excluding words``` | `````` | +| `userWordsToIgnore` | `String` | ```Dictionary for excluding words (comma separated, without spaces)``` | `````` | | `minWordLength` | `Integer` | ```Minimum length for checked words``` | ```3``` | diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index aab363c6a53..5ade19e04ce 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -960,10 +960,10 @@ "title": "Typo", "properties": { "userWordsToIgnore": { - "description": "Dictionary for excluding words", + "description": "Dictionary for excluding words (comma separated, without spaces)", "default": "", "type": "string", - "title": "Dictionary for excluding words" + "title": "Dictionary for excluding words (comma separated, without spaces)" }, "minWordLength": { "description": "Minimum length for checked words", diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_en.properties index ba5aade700f..7c72bc94c95 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_en.properties @@ -7,4 +7,4 @@ diagnosticExceptions=Str,Autotest,Infobase,Enums,Len,Desc,Asc,Overridable,GUID,E Sys,Saas,www,yyyy,xsl,src,deserialization,Params,Archiver,Serializer,xsi,ico,epf,cfu,txt,htm,rtf,ppt,vsd,mpp,mdb,msg,rar,exe,grs,geo,jpg,bmp,\ tif,gif,png,pdf,odt,odf,odp,odg,ods,erf,docx,xlsx,pptx,utf,xsd,SRVR,saas,wsdl,Apdex,APDEX,uid,XLS,XLSX,html,TXT,ODT,Addin,DIB minWordLength=Minimum length for checked words -userWordsToIgnore=Dictionary for excluding words \ No newline at end of file +userWordsToIgnore=Dictionary for excluding words (comma separated, without spaces) \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties index 8643041577d..53e9da049f3 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic_ru.properties @@ -14,4 +14,4 @@ diagnosticExceptions=Автогенерируемых,Автогруппиров ,Сериализованный,Сис,Сконвертировать,Слеш,Слеша,Слеши,Стартован,Стикера,Стр,Студотряде,Субконто,Таб,Техподдержки\ ,Токене,Транслите,Тэги,Тэгов,Убыв,Физлица,Финализировать,Фич,Хэш,Штрихкодам,Штрихкодом,Штрихкоду,Мдд,Чммсс minWordLength=Минимальная длина проверяемых слов -userWordsToIgnore=Пользовательский словарь исключений \ No newline at end of file +userWordsToIgnore=Пользовательский словарь исключений (через запятую, без пробелов) \ No newline at end of file From 36e015d9d6ead85cfb6883dd898e033bdfa70877 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Fri, 24 Apr 2020 17:08:18 +0300 Subject: [PATCH 142/444] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/Typo.md | 17 ----------------- docs/en/diagnostics/Typo.md | 20 -------------------- 2 files changed, 37 deletions(-) diff --git a/docs/diagnostics/Typo.md b/docs/diagnostics/Typo.md index 95599089dc3..22c07c37d0d 100644 --- a/docs/diagnostics/Typo.md +++ b/docs/diagnostics/Typo.md @@ -23,23 +23,6 @@ * Полезная информация: [Русский язык для всех](http://gramota.ru/) * [Источник](https://languagetool.org/ru/) - -### Экранирование кода - -```bsl -// BSLLS:Typo-off -// BSLLS:Typo-on -``` - -### Параметр конфигурационного файла - -```json -"Typo": { - "userWordsToIgnore": "", - "minWordLength": 3 -} -``` - ## Сниппеты diff --git a/docs/en/diagnostics/Typo.md b/docs/en/diagnostics/Typo.md index 8c2289de6e5..4b090808a73 100644 --- a/docs/en/diagnostics/Typo.md +++ b/docs/en/diagnostics/Typo.md @@ -19,29 +19,9 @@ and checked in the built-in dictionary. ## Sources - * [American English Dictionary](https://dictionary.cambridge.org/dictionary/essential-american-english/) * [Source](https://languagetool.org/en/) - -### Diagnostic ignorance in code - -```bsl -// BSLLS:Typo-off -// BSLLS:Typo-on -``` - -### Parameter for config - -```json -"Typo": { - "userWordsToIgnore": "", - "minWordLength": 3 -} -``` ## Snippets From ea3ea08a9d875c9f2a19f4558ad5080e97b76068 Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Sat, 25 Apr 2020 13:40:59 +0300 Subject: [PATCH 143/444] =?UTF-8?q?Precommit.=20=D0=9D=D0=BE=D0=B2=D0=B0?= =?UTF-8?q?=D1=8F=20=D0=B4=D0=B8=D0=B0=D0=B3=D0=BD=D0=BE=D1=81=D1=82=D0=B8?= =?UTF-8?q?=D0=BA=D0=B0=20=D1=83=D1=81=D1=82=D0=B0=D1=80=D0=B5=D0=B2=D1=88?= =?UTF-8?q?=D0=B8=D1=85=20=D1=81=D0=B2=D0=BE=D0=B9=D1=81=D1=82=D0=B2=208.3?= =?UTF-8?q?.12.=20=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=BF=D0=BE=D0=BB=D1=83=D1=87=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F=20=D0=BF=D1=80=D0=B0=D0=B2=D0=B8=D0=BB=D1=8C=D0=BD=D1=8B?= =?UTF-8?q?=D0=B9=20=D0=B2=D0=B0=D1=80=D0=B8=D0=B0=D0=BD=D1=82=D0=BE=D0=B2?= =?UTF-8?q?=20=D0=B2=20=D0=B4=D0=B8=D0=B0=D0=B3=D0=BD=D0=BE=D1=81=D1=82?= =?UTF-8?q?=D0=B8=D0=BA=D0=B5=208.3.10?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/DeprecatedAttributes8312.md | 38 +++++- docs/diagnostics/index.md | 2 +- .../diagnostics/DeprecatedAttributes8312.md | 2 +- docs/en/diagnostics/index.md | 2 +- .../DeprecatedAttributes8312Diagnostic.java | 112 +++++++++++++++--- .../DeprecatedMethods8310Diagnostic.java | 38 ++++-- .../configuration/parameters-schema.json | 4 +- ...atedAttributes8312Diagnostic_en.properties | 9 +- ...atedAttributes8312Diagnostic_ru.properties | 7 +- ...eprecatedAttributes8312DiagnosticTest.java | 50 +++++++- .../DeprecatedAttributes8312Diagnostic.bsl | 4 - 11 files changed, 217 insertions(+), 51 deletions(-) diff --git a/docs/diagnostics/DeprecatedAttributes8312.md b/docs/diagnostics/DeprecatedAttributes8312.md index 252b10a1d49..da880d16fc3 100644 --- a/docs/diagnostics/DeprecatedAttributes8312.md +++ b/docs/diagnostics/DeprecatedAttributes8312.md @@ -1,4 +1,4 @@ -# Устаревшее использование объектов (DeprecatedAttributes8312) +# Устаревшие объекты платформы 8.3.12 (DeprecatedAttributes8312) | Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | | :-: | :-: | :-: | :-: | :-: | :-: | @@ -7,10 +7,37 @@ ## Описание диагностики - -## Примеры - - +В платформе 8.3.12 следующие элементы стали устаревшими: +* Для системного перечисления ГруппировкаПодчиненныхЭлементовФормы реализовано значение ГоризонтальнаяВсегда. +Значение системного перечисления ГруппировкаПодчиненныхЭлементовФормы.Горизонтальная считается устаревшим; +* Системное перечисление ОриентацияМетокДиаграммы более не доступно. Актуальный вариант ОриентацияПодписейДиаграммы; +* Свойства и методы объекта Диаграмма устарели и не рекомендуются к использованию: + * ПалитраЦветов; + * ЦветНачалаГрадиентнойПалитры; + * ЦветКонцаГрадиентнойПалитры; + * МаксимальноеКоличествоЦветовГрадиентнойПалитры; + * ПолучитьПалитру(); + * УстановитьПалитру(). +* Названия свойств объекта ОбластьПостроенияДиаграммы: + * ОтображатьШкалу; + * ЛинииШкалы; + * ЦветШкалы. +* Свойства объекта ОбластьПостроенияДиаграммы являются устаревшими, +не рекомендуются для использования и поддерживаются для совместимости: + + * ОтображатьПодписиШкалыСерии. Для доступа рекомендуется использовать ШкалаСерий.ПоложениеПодписейШкалы; + * ОтображатьПодписиШкалыТочек. Для доступа рекомендуется использовать ШкалаТочек.ПоложениеПодписейШкалы; + * ОтображатьПодписиШкалыЗначений. Для доступа рекомендуется использовать ШкалаЗначений.ПоложениеПодписейШкалы; + * ОтображатьЛинииЗначенийШкалы. Для доступа рекомендуется использовать ШкалаЗначений.ОтображениеЛинийСетки; + * ФорматШкалыЗначений. Для доступа рекомендуется использовать ШкалаЗначений.ФорматПодписей; + * ОриентацияМеток. Для доступа рекомендуется использовать ШкалаТочек.ОриентацияПодписей. +* Свойство ОтображатьЛегенду объектов Диаграмма, ДиаграммаГанта, СводнаяДиаграмма является устаревшим +и не рекомендуется для использования. +* Свойство ОтображатьЗаголовок объектов Диаграмма, ДиаграммаГанта, СводнаяДиаграмма является устаревшим и + не рекомендуется для использования. +* Метод глобального контекста ОчиститьЖурналРегистрации() +применим только к журналу в формата SQLite, признан устаревшим и его использование не рекомендуется. + ## Источники +Источник: [Описание изменений платформы 8.3.12](https://dl04.1c.ru/content/Platform/8_3_12_1714/1cv8upd_8_3_12_1714.htm) ## Сниппеты diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index c29cd957733..784ac601b59 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -32,7 +32,7 @@ | [CyclomaticComplexity](CyclomaticComplexity.md) | Цикломатическая сложность | Да | Критичный | Дефект кода | `brainoverload` | | [DataExchangeLoading](DataExchangeLoading.md) | Отсутствует проверка признака ОбменДанными.Загрузка в обработчике событий объекта | Да | Критичный | Ошибка | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Удаление элемента при обходе коллекции посредством оператора "Для каждого ... Из ... Цикл" | Да | Важный | Ошибка | `standard`
`error` | -| [DeprecatedAttributes8312](DeprecatedAttributes8312.md) | Устаревшее использование объектов | Да | Информационный | Дефект кода | `deprecated` | +| [DeprecatedAttributes8312](DeprecatedAttributes8312.md) | Устаревшие объекты платформы 8.3.12 | Да | Информационный | Дефект кода | `deprecated` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Использование устаревшего метода "ТекущаяДата" | Да | Важный | Ошибка | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Использование устаревшего метода "Найти" | Да | Незначительный | Дефект кода | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Ограничение на использование устаревшего метода "Сообщить" | Да | Незначительный | Дефект кода | `standard`
`deprecated` | diff --git a/docs/en/diagnostics/DeprecatedAttributes8312.md b/docs/en/diagnostics/DeprecatedAttributes8312.md index 055a3f60cc5..6f31f95cf59 100644 --- a/docs/en/diagnostics/DeprecatedAttributes8312.md +++ b/docs/en/diagnostics/DeprecatedAttributes8312.md @@ -1,4 +1,4 @@ -# (DeprecatedAttributes8312) +# Deprecated 8.3.12 platform features. (DeprecatedAttributes8312) | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 7eb695f67f9..5088bbd207c 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -32,7 +32,7 @@ Total: **94** | [CyclomaticComplexity](CyclomaticComplexity.md) | Cyclomatic complexity | Yes | Critical | Code smell | `brainoverload` | | [DataExchangeLoading](DataExchangeLoading.md) | There is no check for the attribute DataExchange.Load in the object's event handler | Yes | Critical | Error | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Deleting an item when iterating through collection using the operator "For each ... In ... Do" | Yes | Major | Error | `standard`
`error` | -| [DeprecatedAttributes8312](DeprecatedAttributes8312.md) | | Yes | Info | Code smell | `deprecated` | +| [DeprecatedAttributes8312](DeprecatedAttributes8312.md) | Deprecated 8.3.12 platform features. | Yes | Info | Code smell | `deprecated` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Using of the deprecated method "CurrentDate" | Yes | Major | Error | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Using of the deprecated method "Find" | Yes | Minor | Code smell | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Restriction on the use of deprecated "Message" method | Yes | Minor | Code smell | `standard`
`deprecated` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic.java index 59d1653da67..cba975748e0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic.java @@ -58,9 +58,7 @@ public class DeprecatedAttributes8312Diagnostic extends AbstractVisitorDiagnosti private static final String SHOW_SCALE_RU = "ОтображатьШкалу"; private static final String SHOW_SCALE_EN = "ShowScale"; private static final String SCALE_LINES_RU = "ЛинииШкалы"; - //private static final String SCALE_LINES_EN = "ScaleLines"; private static final String SCALE_COLOR_RU = "ЦветШкалы"; - //private static final String SCALE_COLOR_EN = "ScaleColor"; private static final String SHOW_SERIES_SCALE_LABELS_RU = "ОтображатьПодписиШкалыСерий"; private static final String SHOW_SERIES_SCALE_LABELS_EN = "ShowSeriesScaleLabels"; private static final String SHOW_POINTS_SCALE_LABELS_RU = "ОтображатьПодписиШкалыТочек"; @@ -101,7 +99,6 @@ public class DeprecatedAttributes8312Diagnostic extends AbstractVisitorDiagnosti private static final String SET_PALETTE_RU = "УстановитьПалитру"; // Global context enum - private static final String CHART_LABELS_ORIENTATION_EN = "ChartLabelsOrientation"; private static final String CHART_LABELS_ORIENTATION_RU = "ОриентацияМетокДиаграммы"; // Global context enum attribute @@ -114,12 +111,78 @@ public class DeprecatedAttributes8312Diagnostic extends AbstractVisitorDiagnosti private static final String CLEAR_EVENT_LOG_EN = "ClearEventLog"; private static final String CLEAR_EVENT_LOG_RU = "ОчиститьЖурналРегистрации"; - private static final HashMap NEW_ATTRIBUTES = new HashMap<>(); + private static final HashMap NEW_ATTRIBUTES_AND_METHODS = new HashMap<>(); static { - NEW_ATTRIBUTES.put(SHOW_SCALE_RU, "ОтображатьШкалы"); - NEW_ATTRIBUTES.put(SHOW_SCALE_EN, "ShowScales"); - NEW_ATTRIBUTES.put(SCALE_LINES_RU, "ЛинииШкал"); - NEW_ATTRIBUTES.put(SCALE_COLOR_RU, "ЦветШкал"); + NEW_ATTRIBUTES_AND_METHODS.put(SHOW_SCALE_RU.toLowerCase(), "ОтображатьШкалы"); + NEW_ATTRIBUTES_AND_METHODS.put(SHOW_SCALE_EN.toLowerCase(), "ShowScales"); + NEW_ATTRIBUTES_AND_METHODS.put(SCALE_LINES_RU.toLowerCase(), "ЛинииШкал"); + NEW_ATTRIBUTES_AND_METHODS.put(SCALE_COLOR_RU.toLowerCase(), "ЦветШкал"); + NEW_ATTRIBUTES_AND_METHODS.put(SHOW_SERIES_SCALE_LABELS_RU.toLowerCase(), + "ШкалаСерий.ПоложениеПодписейШкалы"); + NEW_ATTRIBUTES_AND_METHODS.put(SHOW_SERIES_SCALE_LABELS_EN.toLowerCase(), + "SeriesScale.ScaleLabelLocation"); + NEW_ATTRIBUTES_AND_METHODS.put(SHOW_POINTS_SCALE_LABELS_RU.toLowerCase(), + "ШкалаТочек.ПоложениеПодписейШкалы"); + NEW_ATTRIBUTES_AND_METHODS.put(SHOW_POINTS_SCALE_LABELS_EN.toLowerCase(), + "PointsScale.ScaleLabelLocation"); + NEW_ATTRIBUTES_AND_METHODS.put(SHOW_VALUES_SCALE_LABELS_RU.toLowerCase(), + "ШкалаЗначений.ПоложениеПодписейШкалы"); + NEW_ATTRIBUTES_AND_METHODS.put(SHOW_VALUES_SCALE_LABELS_EN.toLowerCase(), + "ValuesScale.ScaleLabelLocation"); + NEW_ATTRIBUTES_AND_METHODS.put(SHOW_SCALE_VALUE_LINES_RU.toLowerCase(), + "ШкалаЗначений.ОтображениеЛинийСетки"); + NEW_ATTRIBUTES_AND_METHODS.put(SHOW_SCALE_VALUE_LINES_EN.toLowerCase(), + "ValuesScale.GridLinesShowMode"); + NEW_ATTRIBUTES_AND_METHODS.put(VALUE_SCALE_FORMAT_RU.toLowerCase(), + "ШкалаЗначений.ФорматПодписей"); + NEW_ATTRIBUTES_AND_METHODS.put(VALUE_SCALE_FORMAT_EN.toLowerCase(), + "ValuesScale.LabelFormat"); + NEW_ATTRIBUTES_AND_METHODS.put(LABELS_ORIENTATION_RU.toLowerCase(), + "ШкалаТочек.ОриентацияПодписей"); + NEW_ATTRIBUTES_AND_METHODS.put(LABELS_ORIENTATION_EN.toLowerCase(), + "PointsScale.LabelOrientation"); + NEW_ATTRIBUTES_AND_METHODS.put(SHOW_LEGEND_RU.toLowerCase(), + "одно из свойств ОбластьЛегендыДиаграммы, " + + "ОбластьЛегендыДиаграммыГанта или ОбластьЛегендыСводнойДиаграммы"); + NEW_ATTRIBUTES_AND_METHODS.put(SHOW_LEGEND_EN.toLowerCase(), + "one of the properties of ChartLegendArea, " + + "GanttChartLegendArea or PivotChartLegendArea"); + NEW_ATTRIBUTES_AND_METHODS.put(SHOW_TITLE_EN.toLowerCase(), + "one of the properties of ChartTitleArea, " + + "GanttChartTitleArea or PivotChartTitleArea"); + NEW_ATTRIBUTES_AND_METHODS.put(SHOW_TITLE_RU.toLowerCase(), + "одно из свойств ОбластьЗаголовкаДиаграммы, " + + "ОбластьЗаголовкаДиаграммыГанта или ОбластьЗаголовкаСводнойДиаграммы"); + NEW_ATTRIBUTES_AND_METHODS.put(COLOR_PALETTE_EN.toLowerCase(), + "ColorPaletteDescription.ColorPalette"); + NEW_ATTRIBUTES_AND_METHODS.put(COLOR_PALETTE_RU.toLowerCase(), + "ОписаниеПалитрыЦветов.ПалитраЦветов"); + NEW_ATTRIBUTES_AND_METHODS.put(GRADIENT_PALETTE_START_COLOR_EN.toLowerCase(), + "ColorPaletteDescription.GradientPaletteStartColor"); + NEW_ATTRIBUTES_AND_METHODS.put(GRADIENT_PALETTE_START_COLOR_RU.toLowerCase(), + "ОписаниеПалитрыЦветов.ЦветНачалаГрадиентнойПалитры"); + NEW_ATTRIBUTES_AND_METHODS.put(GRADIENT_PALETTE_END_COLOR_EN.toLowerCase(), + "ColorPaletteDescription.GradientPaletteEndColor"); + NEW_ATTRIBUTES_AND_METHODS.put(GRADIENT_PALETTE_END_COLOR_RU.toLowerCase(), + "ОписаниеПалитрыЦветов.ЦветКонцаГрадиентнойПалитры"); + NEW_ATTRIBUTES_AND_METHODS.put(GRADIENT_PALETTE_MAX_COLORS_EN.toLowerCase(), + "ColorPaletteDescription.GradientPaletteMaxColors"); + NEW_ATTRIBUTES_AND_METHODS.put(GRADIENT_PALETTE_MAX_COLORS_RU.toLowerCase(), + "ОписаниеПалитрыЦветов.МаксимальноеКоличествоЦветовГрадиентнойПалитры"); + NEW_ATTRIBUTES_AND_METHODS.put(GET_PALETTE_EN.toLowerCase(), + "ColorPaletteDescription.GetPalette"); + NEW_ATTRIBUTES_AND_METHODS.put(GET_PALETTE_RU.toLowerCase(), + "ОписаниеПалитрыЦветов.ПолучитьПалитру"); + NEW_ATTRIBUTES_AND_METHODS.put(SET_PALETTE_EN.toLowerCase(), + "ColorPaletteDescription.SetPalette"); + NEW_ATTRIBUTES_AND_METHODS.put(SET_PALETTE_RU.toLowerCase(), + "ОписаниеПалитрыЦветов.УстановитьПалитру"); + NEW_ATTRIBUTES_AND_METHODS.put(CHART_LABELS_ORIENTATION_RU.toLowerCase(), + "ОриентацияПодписейДиаграммы"); + NEW_ATTRIBUTES_AND_METHODS.put(CHILD_FORM_ITEMS_GROUP_HORIZONTAL_EN.toLowerCase(), + "AlwaysHorizontal"); + NEW_ATTRIBUTES_AND_METHODS.put(CHILD_FORM_ITEMS_GROUP_HORIZONTAL_RU.toLowerCase(), + "ГоризонтальнаяВсегда"); } private static String getDeprecatedAttributesRegex(Metaobject metaobject) { @@ -214,7 +277,7 @@ private static String getMetaobjectNameRegex(Metaobject metaobject) { Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final Pattern CHART_LABELS_ORIENTATION_PATTERN = Pattern.compile( - CHART_LABELS_ORIENTATION_EN + "|" + CHART_LABELS_ORIENTATION_RU, + CHART_LABELS_ORIENTATION_RU, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); private static final Pattern CHILD_FORM_ITEMS_GROUP_NAME_PATTERN = Pattern.compile( @@ -237,8 +300,14 @@ public DeprecatedAttributes8312Diagnostic(DiagnosticInfo info) { @Override public ParseTree visitMethodCall(BSLParser.MethodCallContext ctx) { - if (CHART_METHODS_PATTERN.matcher(ctx.methodName().getText()).matches()) { - diagnosticStorage.addDiagnostic(ctx); + Matcher matcher = CHART_METHODS_PATTERN.matcher(ctx.methodName().getText()); + if (matcher.matches()) { + String deprecatedMethod = matcher.group(); + String message = String.format(info.getResourceString("deprecatedMethodsMessage"), + deprecatedMethod, + Objects.requireNonNullElseGet(NEW_ATTRIBUTES_AND_METHODS.get(deprecatedMethod.toLowerCase()), + String::new)); + diagnosticStorage.addDiagnostic(ctx, info.getMessage(message)); } return super.visitMethodCall(ctx); @@ -246,8 +315,12 @@ public ParseTree visitMethodCall(BSLParser.MethodCallContext ctx) { @Override public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { - if (CLEAR_EVENT_LOG_PATTERN.matcher(ctx.methodName().getText()).matches()) { - diagnosticStorage.addDiagnostic(ctx); + Matcher matcher = CLEAR_EVENT_LOG_PATTERN.matcher(ctx.methodName().getText()); + if (matcher.matches()) { + String deprecatedMethod = ctx.getStart().getText(); + String message = String.format(info.getResourceString("deprecatedGlobalMethodsMessage"), + deprecatedMethod); + diagnosticStorage.addDiagnostic(ctx, info.getMessage(message)); } return super.visitGlobalMethodCall(ctx); } @@ -267,8 +340,14 @@ public ParseTree visitAccessProperty(BSLParser.AccessPropertyContext ctx) { @Override public ParseTree visitComplexIdentifier(BSLParser.ComplexIdentifierContext ctx) { - if (CHART_LABELS_ORIENTATION_PATTERN.matcher(ctx.getStart().getText()).matches()) { - diagnosticStorage.addDiagnostic(ctx); + Matcher matcher = CHART_LABELS_ORIENTATION_PATTERN.matcher(ctx.getStart().getText()); + if (matcher.matches()) { + String deprecatedEnum = ctx.getStart().getText(); + String message = String.format(info.getResourceString("deprecatedEnumNameMessage"), + deprecatedEnum, + Objects.requireNonNullElseGet(NEW_ATTRIBUTES_AND_METHODS.get(deprecatedEnum.toLowerCase()), + String::new)); + diagnosticStorage.addDiagnostic(ctx, info.getMessage(message)); } return super.visitComplexIdentifier(ctx); @@ -292,7 +371,8 @@ private void checkDeprecatedAttributes(BSLParserRuleContext ctx, String deprecatedAttribute = deprecatedAttributesMatcher.group(); String message = String.format(info.getResourceString("deprecatedAttributeMessage"), deprecatedAttribute, - Objects.requireNonNullElseGet(NEW_ATTRIBUTES.get(deprecatedAttribute), String::new)); + Objects.requireNonNullElseGet(NEW_ATTRIBUTES_AND_METHODS.get(deprecatedAttribute.toLowerCase()), + String::new)); diagnosticStorage.addDiagnostic(ctx, info.getMessage(message)); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java index 307dc884194..f31c37eca7f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java @@ -67,19 +67,31 @@ public class DeprecatedMethods8310Diagnostic extends AbstractVisitorDiagnostic { private static final HashMap newMethods = new HashMap<>(); static { - newMethods.put(SET_SHORT_APPLICATION_CAPTION_RU, "КлиентскоеПриложение.УстановитьКраткийЗаголовок"); - newMethods.put(GET_SHORT_APPLICATION_CAPTION_RU, "КлиентскоеПриложение.ПолучитьКраткийЗаголовок"); - newMethods.put(SET_CLIENT_APPLICATION_CAPTION_RU, "КлиентскоеПриложение.УстановитьЗаголовок"); - newMethods.put(GET_CLIENT_APPLICATION_CAPTION_RU, "КлиентскоеПриложение.ПолучитьЗаголовок"); - newMethods.put(BASE_FONT_CURRENT_VARIANT_RU, "КлиентскоеПриложение.ТекущийВариантОсновногоШрифта"); - newMethods.put(CLIENT_INTERFACE_VARIANT_RU, "КлиентскоеПриложение.ТекущийВариантИнтерфейса"); + newMethods.put(SET_SHORT_APPLICATION_CAPTION_RU.toLowerCase(), + "КлиентскоеПриложение.УстановитьКраткийЗаголовок"); + newMethods.put(GET_SHORT_APPLICATION_CAPTION_RU.toLowerCase(), + "КлиентскоеПриложение.ПолучитьКраткийЗаголовок"); + newMethods.put(SET_CLIENT_APPLICATION_CAPTION_RU.toLowerCase(), + "КлиентскоеПриложение.УстановитьЗаголовок"); + newMethods.put(GET_CLIENT_APPLICATION_CAPTION_RU.toLowerCase(), + "КлиентскоеПриложение.ПолучитьЗаголовок"); + newMethods.put(BASE_FONT_CURRENT_VARIANT_RU.toLowerCase(), + "КлиентскоеПриложение.ТекущийВариантОсновногоШрифта"); + newMethods.put(CLIENT_INTERFACE_VARIANT_RU.toLowerCase(), + "КлиентскоеПриложение.ТекущийВариантИнтерфейса"); - newMethods.put(SET_SHORT_APPLICATION_CAPTION_EN, "ClientApplication.SetShortCaption"); - newMethods.put(GET_SHORT_APPLICATION_CAPTION_EN, "ClientApplication.GetShortCaption"); - newMethods.put(SET_CLIENT_APPLICATION_CAPTION_EN, "ClientApplication.SetCaption"); - newMethods.put(GET_CLIENT_APPLICATION_CAPTION_EN, "ClientApplication.GetCaption"); - newMethods.put(BASE_FONT_CURRENT_VARIANT_EN, "ClientApplication.CurrentBaseFontVariant"); - newMethods.put(CLIENT_INTERFACE_VARIANT_EN, "ClientApplication.CurrentInterfaceVariant"); + newMethods.put(SET_SHORT_APPLICATION_CAPTION_EN.toLowerCase(), + "ClientApplication.SetShortCaption"); + newMethods.put(GET_SHORT_APPLICATION_CAPTION_EN.toLowerCase(), + "ClientApplication.GetShortCaption"); + newMethods.put(SET_CLIENT_APPLICATION_CAPTION_EN.toLowerCase(), + "ClientApplication.SetCaption"); + newMethods.put(GET_CLIENT_APPLICATION_CAPTION_EN.toLowerCase(), + "ClientApplication.GetCaption"); + newMethods.put(BASE_FONT_CURRENT_VARIANT_EN.toLowerCase(), + "ClientApplication.CurrentBaseFontVariant"); + newMethods.put(CLIENT_INTERFACE_VARIANT_EN.toLowerCase(), + "ClientApplication.CurrentInterfaceVariant"); } private static String getRegex() { @@ -110,7 +122,7 @@ public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { Matcher matcher = METHOD_PATTERN.matcher(ctx.methodName().getText()); if (matcher.matches()) { diagnosticStorage.addDiagnostic(ctx, - info.getMessage(matcher.group(), newMethods.getOrDefault(matcher.group(), ""))); + info.getMessage(matcher.group(), newMethods.getOrDefault(matcher.group().toLowerCase(), ""))); } return super.visitGlobalMethodCall(ctx); diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index 1d004a2dca0..a6dcbbd3085 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -207,13 +207,13 @@ "$id": "#/definitions/DeletingCollectionItem" }, "DeprecatedAttributes8312": { - "description": "", + "description": "Deprecated 8.3.12 platform features.", "default": true, "type": [ "boolean", "object" ], - "title": "", + "title": "Deprecated 8.3.12 platform features.", "$id": "#/definitions/DeprecatedAttributes8312" }, "DeprecatedCurrentDate": { diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic_en.properties index f56bffb6cd7..232ae5da5db 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic_en.properties @@ -1,3 +1,6 @@ -diagnosticMessage= -diagnosticName= -deprecatedAttributeMessage=\"%s\" attribute is deprecated. You should use \"%s\" +diagnosticMessage=%s +diagnosticName=Deprecated 8.3.12 platform features. +deprecatedAttributeMessage=\"%s\" attribute is deprecated. You should use %s +deprecatedMethodsMessage=\"%s\" method is deprecated. You should use \"%s\" +deprecatedEnumNameMessage=Deprecated enum name \"%s\". You should use \"%s\" instead. +deprecatedGlobalMethodsMessage=\"%s\" global method is deprecated. You should not use it. \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic_ru.properties index f20e7315b97..f59017a7ca8 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic_ru.properties @@ -1,3 +1,6 @@ diagnosticMessage=%s -diagnosticName=Устаревшее использование объектов -deprecatedAttributeMessage=Атрибут \"%s\" устарел. Вместо него стоит использовать \"%s\" +diagnosticName=Устаревшие объекты платформы 8.3.12 +deprecatedAttributeMessage=Атрибут \"%s\" устарел. Вместо него стоит использовать %s +deprecatedMethodsMessage=Метод \"%s\" устарел. Вместо него стоит использовать \"%s\" +deprecatedEnumNameMessage=Используется старое наименование \"%s\". Вместо него необходимо использовать \"%s\" +deprecatedGlobalMethodsMessage=Метод \"%s\" устарел и больше не используется diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312DiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312DiagnosticTest.java index 19d2c26bf87..7395706af25 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312DiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312DiagnosticTest.java @@ -38,9 +38,53 @@ void test() { List diagnostics = getDiagnostics(); - assertThat(diagnostics).hasSize(46); -// assertThat(diagnostics, true) -// .hasRange(6, 0, 6, 20); + assertThat(diagnostics).hasSize(45); + assertThat(diagnostics, true) + .hasRange(1, 37, 1, 53) + .hasRange(2, 30, 2, 41) + .hasRange(3, 30, 3, 40) + .hasRange(4, 30, 4, 58) + .hasRange(5, 30, 5, 58) + .hasRange(6, 30, 6, 61) + .hasRange(7, 30, 7, 59) + .hasRange(8, 30, 8, 50) + .hasRange(9, 30, 9, 46) + .hasRange(13, 17, 13, 27) + .hasRange(14, 17, 14, 39) + .hasRange(15, 17, 15, 39) + .hasRange(16, 17, 16, 39) + .hasRange(17, 17, 17, 37) + .hasRange(18, 17, 18, 34) + .hasRange(19, 17, 19, 35) + .hasRange(23, 13, 23, 31) + .hasRange(24, 13, 24, 33) + .hasRange(25, 18, 25, 36) + .hasRange(26, 18, 26, 38) + .hasRange(27, 20, 27, 38) + .hasRange(28, 20, 28, 40) + .hasRange(30, 13, 30, 27) + .hasRange(31, 13, 31, 42) + .hasRange(32, 13, 32, 41) + .hasRange(33, 13, 33, 60) + .hasRange(35, 21, 35, 38) + .hasRange(36, 14, 36, 45) + .hasRange(40, 9, 40, 20) + .hasRange(41, 14, 41, 25) + .hasRange(42, 14, 42, 25) + .hasRange(43, 9, 43, 19) + .hasRange(44, 14, 44, 24) + .hasRange(45, 14, 45, 24) + .hasRange(47, 9, 47, 22) + .hasRange(48, 9, 48, 35) + .hasRange(49, 9, 49, 33) + .hasRange(50, 9, 50 ,34) + .hasRange(52, 10, 52, 22) + .hasRange(53, 10, 53, 26) + .hasRange(58, 17, 58, 46) + .hasRange(62, 4, 62, 36) + .hasRange(66, 4, 66, 25) + .hasRange(70, 54, 70, 69) + .hasRange(74, 30, 74, 41); } } diff --git a/src/test/resources/diagnostics/DeprecatedAttributes8312Diagnostic.bsl b/src/test/resources/diagnostics/DeprecatedAttributes8312Diagnostic.bsl index 1916e3b2c8c..9e8ea07b2c2 100644 --- a/src/test/resources/diagnostics/DeprecatedAttributes8312Diagnostic.bsl +++ b/src/test/resources/diagnostics/DeprecatedAttributes8312Diagnostic.bsl @@ -59,10 +59,6 @@ EndProcedure Ориентация = ОриентацияМетокДиаграммы.Авто; КонецПроцедуры -Procedure Test3() - test = ChartLabelsOrientation.Auto; -EndProcedure - Процедура Тест4() ОчиститьЖурналРегистрации(Отбор); КонецПроцедуры From 02f3293074f2456b0f941591ba63a655ca4dd53a Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sat, 25 Apr 2020 23:29:52 +0700 Subject: [PATCH 144/444] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B2=D0=BE=D0=B5=20?= =?UTF-8?q?=D0=BF=D1=80=D0=B8=D0=B1=D0=BB=D0=B8=D0=B6=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...unctionReturnsSamePrimitiveDiagnostic.java | 68 +++++++++++++++++++ ...turnsSamePrimitiveDiagnostic_en.properties | 2 + ...turnsSamePrimitiveDiagnostic_ru.properties | 2 + ...ionReturnsSamePrimitiveDiagnosticTest.java | 23 +++++++ .../FunctionReturnsSameValueDiagnostic.bsl | 52 ++++++++++++++ 5 files changed, 147 insertions(+) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java new file mode 100644 index 00000000000..6c7c1c750b4 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java @@ -0,0 +1,68 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.languageserver.utils.RelatedInformation; +import com.github._1c_syntax.bsl.languageserver.utils.Trees; +import com.github._1c_syntax.bsl.parser.BSLLexer; +import com.github._1c_syntax.bsl.parser.BSLParser; +import org.antlr.v4.runtime.tree.ParseTree; +import org.checkerframework.checker.nullness.Opt; +import org.eclipse.lsp4j.DiagnosticRelatedInformation; + +import javax.tools.Diagnostic; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collector; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@DiagnosticMetadata( + type = DiagnosticType.ERROR, + severity = DiagnosticSeverity.INFO, + minutesToFix = 1, + tags = { + DiagnosticTag.BADPRACTICE + } + +) +public class FunctionReturnsSamePrimitiveDiagnostic extends AbstractVisitorDiagnostic { + public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + public ParseTree visitFunction(BSLParser.FunctionContext ctx) { + var tree = Trees.findAllRuleNodes(ctx, BSLParser.RULE_returnStatement); + if (tree.size() > 1){ + var set = tree.stream() + .map(BSLParser.ReturnStatementContext.class::cast) + .map(BSLParser.ReturnStatementContext::expression) + .flatMap(Stream::ofNullable) + .map(BSLParser.ExpressionContext::getText) + .collect(Collectors.toSet()); + if (set.size() == 1) { + var relatedInformation = tree.stream() + .map(BSLParser.ReturnStatementContext.class::cast) + .map(statement -> + RelatedInformation.create( + documentContext.getUri(), + Ranges.create(statement.getStart()), + info.getMessage())) + .collect(Collectors.toList()); + diagnosticStorage.addDiagnostic(ctx.funcDeclaration(), info.getMessage(), relatedInformation); + } + } + return ctx; + } +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties new file mode 100644 index 00000000000..66831715dfd --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage= +diagnosticName= diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties new file mode 100644 index 00000000000..df22ba92595 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Проверьте правильность возврата одного и того жк значения в функции +diagnosticName=Функция всегда возвращает одно и то же значение diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java new file mode 100644 index 00000000000..1517ec60634 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java @@ -0,0 +1,23 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class FunctionReturnsSamePrimitiveDiagnosticTest extends AbstractDiagnosticTest { + FunctionReturnsSamePrimitiveDiagnosticTest() { + super(FunctionReturnsSamePrimitiveDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(4); + + } +} diff --git a/src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl b/src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl new file mode 100644 index 00000000000..c8e246d08f3 --- /dev/null +++ b/src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl @@ -0,0 +1,52 @@ +Функция ПроверитьСтроку(Знач СтрокаТаблицы) // <-- ошибка + Если ЭтоХорошаяСтрока(СтрокаТаблицы) Тогда + ДелаемЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + Возврат Истина; + ИначеЕсли ЭтоТожеНеплохаяСтрока(СтрокаТаблицы) Тогда + ДелаемДругоеЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + Возврат Истина; + Иначе + Возврат Истина; + КонецЕсли; +КонецФункции + +Функция БудемТестироватьФункциональность() + Возврат Ложь; +КонецФункции + +Функция ВернутьСтроку() + Возврат "Истина"; +КонецФункции + +Процедура СделаемЧтоНибудь() + Значение = Истина; + Возврат; +КонецПроцедуры + +Функция Метод1() // <-- ошибка + Значение = "Фича"; + Если Фича = "Дирижабль" Тогда + Возврат "Фича"; + ИначеЕсли Фича = "Ага" Тогда + Возврат "Фича"; + КонецЕсли; + Возврат "Фича"; +КонецФункции + +Функция СтавкаНДС(Ставка) // <-- ошибка + Значение = 20; + Если Ставка = "Ставка18" Тогда + Возврат 20; + КонецЕсли; + Возврат 20; +КонецФункции + +// надо бы подумать как правильно диагностировать +// по идее ошибка +Функция СтавкаНДС2(Ставка) + Значение = 20; + Если Ставка = "Ставка18" Тогда + Возврат Значение; + КонецЕсли; + Возврат Значение; +КонецФункции \ No newline at end of file From f687ef3626081d41c1d5444d2d6c337c1f373679 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sun, 26 Apr 2020 01:23:36 +0700 Subject: [PATCH 145/444] =?UTF-8?q?=D0=98=D1=81=D0=BA=D0=BB=D1=8E=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BD=D0=B5=20=D0=BF=D1=80=D0=B8?= =?UTF-8?q?=D0=BC=D0=B8=D1=82=D0=B8=D0=B2=D0=BE=D0=B2,=20=D0=B4=D0=BE?= =?UTF-8?q?=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5=D0=BD=D0=B0=20=D0=B4=D0=BE=D0=BA?= =?UTF-8?q?=D1=83=D0=BC=D0=B5=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D1=8F=20=D0=BD?= =?UTF-8?q?=D0=B0=20ru,=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B8=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5=20=D0=B8=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=20=D1=84=D0=B0=D0=B9=D0=BB=D0=B0=20=D0=BA=D0=B5=D0=B9?= =?UTF-8?q?=D1=81=D0=B0=20=D0=B4=D0=BB=D1=8F=20=D1=82=D0=B5=D1=81=D1=82?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FunctionReturnsSamePrimitive.md | 71 ++++++++++++++ .../FunctionReturnsSamePrimitive.md | 36 +++++++ ...unctionReturnsSamePrimitiveDiagnostic.java | 96 +++++++++++++------ ...turnsSamePrimitiveDiagnostic_en.properties | 5 +- ...turnsSamePrimitiveDiagnostic_ru.properties | 5 +- ...ionReturnsSamePrimitiveDiagnosticTest.java | 10 +- ...unctionReturnsSamePrimitiveDiagnostic.bsl} | 3 +- 7 files changed, 192 insertions(+), 34 deletions(-) create mode 100644 docs/diagnostics/FunctionReturnsSamePrimitive.md create mode 100644 docs/en/diagnostics/FunctionReturnsSamePrimitive.md rename src/test/resources/diagnostics/{FunctionReturnsSameValueDiagnostic.bsl => FunctionReturnsSamePrimitiveDiagnostic.bsl} (94%) diff --git a/docs/diagnostics/FunctionReturnsSamePrimitive.md b/docs/diagnostics/FunctionReturnsSamePrimitive.md new file mode 100644 index 00000000000..464ba00e5f5 --- /dev/null +++ b/docs/diagnostics/FunctionReturnsSamePrimitive.md @@ -0,0 +1,71 @@ +# Функция всегда возвращает одно и то же примитивное значение () + + + +## + + +## Описание диагностики + + +Функция не должна возвращать одно и тоже примитивное значение. Если результат функции не учитывается - то нужно функцию +переписать на процедуру. + +## Примеры + + +Плохо: +```bsl +Функция ПроверитьСтроку(Знач СтрокаТаблицы) + + Если ЭтоХорошаяСтрока(СтрокаТаблицы) Тогда + ДелаемЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + Возврат Истина; + ИначеЕсли ЭтоТожеНеплохаяСтрока(СтрокаТаблицы) Тогда + ДелаемДругоеЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + Возврат Истина; + Иначе + Возврат Истина; + КонецЕсли; + +КонецФункции +``` + +Хорошо: +```bsl +Процедура ПроверитьСтроку(Знач СтрокаТаблицы) + + Если ЭтоХорошаяСтрока(СтрокаТаблицы) Тогда + ДелаемЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + ИначеЕсли ЭтоТожеНеплохаяСтрока(СтрокаТаблицы) Тогда + ДелаемДругоеЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + Иначе + ДелаемЧтотоДругоеИзВеткиИначе(); + КонецЕсли; + +КонецПроцедуры +``` + +## Источники + + + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Параметр конфигурационного файла + +```json +"": +``` \ No newline at end of file diff --git a/docs/en/diagnostics/FunctionReturnsSamePrimitive.md b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md new file mode 100644 index 00000000000..4e7e0f78ada --- /dev/null +++ b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md @@ -0,0 +1,36 @@ +# + + + +## + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Parameter for config + +```json +"": +``` diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java index 6c7c1c750b4..c0dc94b38af 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java @@ -1,5 +1,27 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; @@ -8,35 +30,31 @@ import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import com.github._1c_syntax.bsl.languageserver.utils.RelatedInformation; import com.github._1c_syntax.bsl.languageserver.utils.Trees; -import com.github._1c_syntax.bsl.parser.BSLLexer; import com.github._1c_syntax.bsl.parser.BSLParser; +import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; -import org.checkerframework.checker.nullness.Opt; -import org.eclipse.lsp4j.DiagnosticRelatedInformation; +import org.eclipse.lsp4j.Range; -import javax.tools.Diagnostic; -import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; import java.util.List; -import java.util.Objects; import java.util.Optional; -import java.util.Set; -import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.Stream; @DiagnosticMetadata( type = DiagnosticType.ERROR, - severity = DiagnosticSeverity.INFO, - minutesToFix = 1, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 5, tags = { + DiagnosticTag.DESIGN, DiagnosticTag.BADPRACTICE } ) public class FunctionReturnsSamePrimitiveDiagnostic extends AbstractVisitorDiagnostic { + + private static final String KEY_MESSAGE = "diagnosticMessageReturnStatement"; + public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { super(info); } @@ -44,25 +62,49 @@ public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { @Override public ParseTree visitFunction(BSLParser.FunctionContext ctx) { var tree = Trees.findAllRuleNodes(ctx, BSLParser.RULE_returnStatement); - if (tree.size() > 1){ - var set = tree.stream() + if (tree.size() > 1) { + var expressions = tree.stream() .map(BSLParser.ReturnStatementContext.class::cast) .map(BSLParser.ReturnStatementContext::expression) .flatMap(Stream::ofNullable) - .map(BSLParser.ExpressionContext::getText) - .collect(Collectors.toSet()); - if (set.size() == 1) { - var relatedInformation = tree.stream() - .map(BSLParser.ReturnStatementContext.class::cast) - .map(statement -> - RelatedInformation.create( - documentContext.getUri(), - Ranges.create(statement.getStart()), - info.getMessage())) - .collect(Collectors.toList()); - diagnosticStorage.addDiagnostic(ctx.funcDeclaration(), info.getMessage(), relatedInformation); - } + .collect(Collectors.toList()); + + expressions.stream() + .map(expression -> Trees.findAllRuleNodes(expression, BSLParser.RULE_complexIdentifier)) + .filter(Collection::isEmpty) + .findAny() + .ifPresent( + parseTrees -> checkPrimitiveValue(ctx, tree, expressions) + ); } return ctx; } + + private void checkPrimitiveValue( + BSLParser.FunctionContext ctx, Collection tree, List expressions) { + + var set = expressions.stream().map(BSLParser.ExpressionContext::getText).collect(Collectors.toSet()); + if (set.size() == 1) { + var relatedInformation = tree.stream() + .map(BSLParser.ReturnStatementContext.class::cast) + .map(statement -> RelatedInformation.create( + documentContext.getUri(), + Ranges.create(statement.getStart()), + info.getResourceString(KEY_MESSAGE))) + .collect(Collectors.toList()); + diagnosticStorage.addDiagnostic(getSubNameRange(ctx), info.getMessage(), relatedInformation); + } + + } + + private Range getSubNameRange(ParserRuleContext ctx) { + return Optional.ofNullable(Trees.getAncestorByRuleIndex(ctx, BSLParser.RULE_sub)) + .map(BSLParser.SubContext.class::cast) + .map(context -> documentContext.getSymbolTree().getMethodSymbol(context)) + .filter(Optional::isPresent) + .map(Optional::get) + .map(MethodSymbol::getSubNameRange) + .orElse(Ranges.create(ctx.getStart())); + } + } diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties index 66831715dfd..fb0ac7ddbfc 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties @@ -1,2 +1,3 @@ -diagnosticMessage= -diagnosticName= +diagnosticMessage=Check that the same primitive value is returned in the function +diagnosticName=The function always returns the same primitive value +diagnosticMessageReturnStatement=Repeat return value diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties index df22ba92595..2ac2ec79e1b 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties @@ -1,2 +1,3 @@ -diagnosticMessage=Проверьте правильность возврата одного и того жк значения в функции -diagnosticName=Функция всегда возвращает одно и то же значение +diagnosticMessage=Проверьте правильность возврата одного и того же примитивного значения в функции +diagnosticName=Функция всегда возвращает одно и то же примитивное значение +diagnosticMessageReturnStatement=Повтор возвращаемого значения diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java index 1517ec60634..1af20cc2524 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java @@ -1,5 +1,6 @@ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; @@ -17,7 +18,14 @@ void test() { List diagnostics = getDiagnostics(); - assertThat(diagnostics).hasSize(4); + assertThat(diagnostics) + .hasSize(3) + .anyMatch(diagnostic -> diagnostic.getRange().equals( + Ranges.create(0, 8, 0, 23))) + .anyMatch(diagnostic -> diagnostic.getRange().equals( + Ranges.create(25, 8, 25, 14))) + .anyMatch(diagnostic -> diagnostic.getRange().equals( + Ranges.create(35, 8, 35, 17))); } } diff --git a/src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl b/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl similarity index 94% rename from src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl rename to src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl index c8e246d08f3..66f0df2975e 100644 --- a/src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl +++ b/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl @@ -41,8 +41,7 @@ Возврат 20; КонецФункции -// надо бы подумать как правильно диагностировать -// по идее ошибка +// здесь нет ошибки, т.к. проверка только на примитивы Функция СтавкаНДС2(Ставка) Значение = 20; Если Ставка = "Ставка18" Тогда From 4421d3b4737e0b330b7df794b8564ca8f967e801 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sun, 26 Apr 2020 01:38:38 +0700 Subject: [PATCH 146/444] =?UTF-8?q?=D0=94=D0=BE=D0=BF=D0=BE=D0=BB=D0=BD?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D1=82=D0=B0=D1=86=D0=B8=D1=8F,=20=D0=B7=D0=B0=D0=BF=D1=83?= =?UTF-8?q?=D1=89=D0=B5=D0=BD=20=D0=BF=D1=80=D0=B5=D0=BA=D0=BE=D0=BC=D0=BC?= =?UTF-8?q?=D0=B8=D1=82,=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=BF=D0=BE=D1=82=D0=B5=D1=80=D1=8F=D0=BD=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F=20=D0=BB=D0=B8=D1=86=D0=B5=D0=BD=D0=B7=D0=B8=D1=8F?= =?UTF-8?q?=20=D0=B2=20=D1=84=D0=B0=D0=B9=D0=BB=D0=B5=20=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=B0.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FunctionReturnsSamePrimitive.md | 18 +++---- docs/diagnostics/index.md | 5 +- .../FunctionReturnsSamePrimitive.md | 51 ++++++++++++++++--- docs/en/diagnostics/index.md | 5 +- .../configuration/diagnostics-schema.json | 10 ++++ .../languageserver/configuration/schema.json | 3 ++ ...ionReturnsSamePrimitiveDiagnosticTest.java | 21 ++++++++ 7 files changed, 92 insertions(+), 21 deletions(-) diff --git a/docs/diagnostics/FunctionReturnsSamePrimitive.md b/docs/diagnostics/FunctionReturnsSamePrimitive.md index 464ba00e5f5..cbd70345b65 100644 --- a/docs/diagnostics/FunctionReturnsSamePrimitive.md +++ b/docs/diagnostics/FunctionReturnsSamePrimitive.md @@ -1,8 +1,8 @@ -# Функция всегда возвращает одно и то же примитивное значение () +# Функция всегда возвращает одно и то же примитивное значение (FunctionReturnsSamePrimitive) - - -## +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Ошибка` | `BSL`
`OS` | `Важный` | `Да` | `5` | `design`
`badpractice` | ## Описание диагностики @@ -55,17 +55,17 @@ * Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) --> ## Сниппеты - + ### Экранирование кода ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:FunctionReturnsSamePrimitive-off +// BSLLS:FunctionReturnsSamePrimitive-on ``` ### Параметр конфигурационного файла ```json -"": -``` \ No newline at end of file +"FunctionReturnsSamePrimitive": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index d1eccfc2ac0..0fab59f2d5f 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,11 +8,11 @@ ## Список реализованных диагностик -Общее количество: **88** +Общее количество: **89** * Дефект кода: **55** * Уязвимость: **2** -* Ошибка: **29** +* Ошибка: **30** * Потенциальная уязвимость: **2** | Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги | @@ -40,6 +40,7 @@ | [ExtraCommas](ExtraCommas.md) | Запятые без указания параметра в конце вызова метода | Да | Важный | Дефект кода | `standard`
`badpractice` | | [FormDataToValue](FormDataToValue.md) | Использование метода ДанныеФормыВЗначение | Да | Информационный | Дефект кода | `badpractice` | | [FunctionNameStartsWithGet](FunctionNameStartsWithGet.md) | Имя функции не должно начинаться с "Получить" | Нет | Информационный | Дефект кода | `standard` | +| [FunctionReturnsSamePrimitive](FunctionReturnsSamePrimitive.md) | Функция всегда возвращает одно и то же примитивное значение | Да | Важный | Ошибка | `design`
`badpractice` | | [FunctionShouldHaveReturn](FunctionShouldHaveReturn.md) | Функция должна содержать возврат | Да | Важный | Ошибка | `suspicious`
`unpredictable` | | [GetFormMethod](GetFormMethod.md) | Использование метода ПолучитьФорму | Да | Важный | Ошибка | `error` | | [IdenticalExpressions](IdenticalExpressions.md) | Одинаковые выражения слева и справа от "foo" оператора | Да | Важный | Ошибка | `suspicious` | diff --git a/docs/en/diagnostics/FunctionReturnsSamePrimitive.md b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md index 4e7e0f78ada..a7b5d484497 100644 --- a/docs/en/diagnostics/FunctionReturnsSamePrimitive.md +++ b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md @@ -1,16 +1,51 @@ -# +# The function always returns the same primitive value (FunctionReturnsSamePrimitive) - - -## +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Error` | `BSL`
`OS` | `Major` | `Yes` | `5` | `design`
`badpractice` | ## Description +A function should not return the same primitive value. If the result of the function isn't use into code, then you need the function +rewrite to the procedure. + ## Examples +Bad: +```bsl +Function CheckString(Val RowTable) + + If ItsGoodString(RowTable) Then + ActionGood(); + Return True; + ElsIf ItsNodBadString(RowTable) Then + ActionNoBad(); + Return True; + Else + Return True; + EndIf; + +EndFunction +``` + +Good: +```bsl +Function CheckString(Val RowTable) + + If ItsGoodString(RowTable) Then + ActionGood(); + ElsIf ItsNodBadString(RowTable) Then + ActionNoBad(); + Else + ActionElse(); + EndIf; + +EndFunction +``` + ## Sources ## Snippets - + ### Diagnostic ignorance in code ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:FunctionReturnsSamePrimitive-off +// BSLLS:FunctionReturnsSamePrimitive-on ``` ### Parameter for config ```json -"": +"FunctionReturnsSamePrimitive": false ``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 92ef4e4c507..b22ab4029d5 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,9 +8,9 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **88** +Total: **89** -* Error: **29** +* Error: **30** * Code smell: **55** * Vulnerability: **2** * Security Hotspot: **2** @@ -40,6 +40,7 @@ Total: **88** | [ExtraCommas](ExtraCommas.md) | Commas without a parameter at the end of a method call | Yes | Major | Code smell | `standard`
`badpractice` | | [FormDataToValue](FormDataToValue.md) | FormDataToValue method call | Yes | Info | Code smell | `badpractice` | | [FunctionNameStartsWithGet](FunctionNameStartsWithGet.md) | Function name shouldn't start with "Получить" | No | Info | Code smell | `standard` | +| [FunctionReturnsSamePrimitive](FunctionReturnsSamePrimitive.md) | The function always returns the same primitive value | Yes | Major | Error | `design`
`badpractice` | | [FunctionShouldHaveReturn](FunctionShouldHaveReturn.md) | The function should have return | Yes | Major | Error | `suspicious`
`unpredictable` | | [GetFormMethod](GetFormMethod.md) | GetForm method call | Yes | Major | Error | `error` | | [IdenticalExpressions](IdenticalExpressions.md) | There are identical sub-expressions to the left and to the right of the "foo" operator | Yes | Major | Error | `suspicious` | diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json index 3369ec036ca..a88716c7949 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics-schema.json @@ -278,6 +278,16 @@ "title": "Function name shouldn't start with \"\u041f\u043e\u043b\u0443\u0447\u0438\u0442\u044c\"", "$id": "#/definitions/FunctionNameStartsWithGet" }, + "FunctionReturnsSamePrimitive": { + "description": "The function always returns the same primitive value", + "default": null, + "type": [ + "boolean", + "object" + ], + "title": "The function always returns the same primitive value", + "$id": "#/definitions/FunctionReturnsSamePrimitive" + }, "FunctionShouldHaveReturn": { "description": "The function should have return", "default": null, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index c34797acb3e..bcd5efb647f 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -170,6 +170,9 @@ "FunctionNameStartsWithGet": { "$ref": "diagnostics-schema.json#/definitions/FunctionNameStartsWithGet" }, + "FunctionReturnsSamePrimitive": { + "$ref": "diagnostics-schema.json#/definitions/FunctionReturnsSamePrimitive" + }, "FunctionShouldHaveReturn": { "$ref": "diagnostics-schema.json#/definitions/FunctionShouldHaveReturn" }, diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java index 1af20cc2524..b4d1a3cd769 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java @@ -1,3 +1,24 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; From d4e585a1e9c999c950d5c6b1971d84ce1f8678e8 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sat, 25 Apr 2020 23:29:52 +0700 Subject: [PATCH 147/444] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B2=D0=BE=D0=B5=20?= =?UTF-8?q?=D0=BF=D1=80=D0=B8=D0=B1=D0=BB=D0=B8=D0=B6=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...unctionReturnsSamePrimitiveDiagnostic.java | 68 +++++++++++++++++++ ...turnsSamePrimitiveDiagnostic_en.properties | 2 + ...turnsSamePrimitiveDiagnostic_ru.properties | 2 + ...ionReturnsSamePrimitiveDiagnosticTest.java | 23 +++++++ .../FunctionReturnsSameValueDiagnostic.bsl | 52 ++++++++++++++ 5 files changed, 147 insertions(+) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java new file mode 100644 index 00000000000..6c7c1c750b4 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java @@ -0,0 +1,68 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.languageserver.utils.RelatedInformation; +import com.github._1c_syntax.bsl.languageserver.utils.Trees; +import com.github._1c_syntax.bsl.parser.BSLLexer; +import com.github._1c_syntax.bsl.parser.BSLParser; +import org.antlr.v4.runtime.tree.ParseTree; +import org.checkerframework.checker.nullness.Opt; +import org.eclipse.lsp4j.DiagnosticRelatedInformation; + +import javax.tools.Diagnostic; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collector; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@DiagnosticMetadata( + type = DiagnosticType.ERROR, + severity = DiagnosticSeverity.INFO, + minutesToFix = 1, + tags = { + DiagnosticTag.BADPRACTICE + } + +) +public class FunctionReturnsSamePrimitiveDiagnostic extends AbstractVisitorDiagnostic { + public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + public ParseTree visitFunction(BSLParser.FunctionContext ctx) { + var tree = Trees.findAllRuleNodes(ctx, BSLParser.RULE_returnStatement); + if (tree.size() > 1){ + var set = tree.stream() + .map(BSLParser.ReturnStatementContext.class::cast) + .map(BSLParser.ReturnStatementContext::expression) + .flatMap(Stream::ofNullable) + .map(BSLParser.ExpressionContext::getText) + .collect(Collectors.toSet()); + if (set.size() == 1) { + var relatedInformation = tree.stream() + .map(BSLParser.ReturnStatementContext.class::cast) + .map(statement -> + RelatedInformation.create( + documentContext.getUri(), + Ranges.create(statement.getStart()), + info.getMessage())) + .collect(Collectors.toList()); + diagnosticStorage.addDiagnostic(ctx.funcDeclaration(), info.getMessage(), relatedInformation); + } + } + return ctx; + } +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties new file mode 100644 index 00000000000..66831715dfd --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage= +diagnosticName= diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties new file mode 100644 index 00000000000..df22ba92595 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Проверьте правильность возврата одного и того жк значения в функции +diagnosticName=Функция всегда возвращает одно и то же значение diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java new file mode 100644 index 00000000000..1517ec60634 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java @@ -0,0 +1,23 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class FunctionReturnsSamePrimitiveDiagnosticTest extends AbstractDiagnosticTest { + FunctionReturnsSamePrimitiveDiagnosticTest() { + super(FunctionReturnsSamePrimitiveDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(4); + + } +} diff --git a/src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl b/src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl new file mode 100644 index 00000000000..c8e246d08f3 --- /dev/null +++ b/src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl @@ -0,0 +1,52 @@ +Функция ПроверитьСтроку(Знач СтрокаТаблицы) // <-- ошибка + Если ЭтоХорошаяСтрока(СтрокаТаблицы) Тогда + ДелаемЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + Возврат Истина; + ИначеЕсли ЭтоТожеНеплохаяСтрока(СтрокаТаблицы) Тогда + ДелаемДругоеЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + Возврат Истина; + Иначе + Возврат Истина; + КонецЕсли; +КонецФункции + +Функция БудемТестироватьФункциональность() + Возврат Ложь; +КонецФункции + +Функция ВернутьСтроку() + Возврат "Истина"; +КонецФункции + +Процедура СделаемЧтоНибудь() + Значение = Истина; + Возврат; +КонецПроцедуры + +Функция Метод1() // <-- ошибка + Значение = "Фича"; + Если Фича = "Дирижабль" Тогда + Возврат "Фича"; + ИначеЕсли Фича = "Ага" Тогда + Возврат "Фича"; + КонецЕсли; + Возврат "Фича"; +КонецФункции + +Функция СтавкаНДС(Ставка) // <-- ошибка + Значение = 20; + Если Ставка = "Ставка18" Тогда + Возврат 20; + КонецЕсли; + Возврат 20; +КонецФункции + +// надо бы подумать как правильно диагностировать +// по идее ошибка +Функция СтавкаНДС2(Ставка) + Значение = 20; + Если Ставка = "Ставка18" Тогда + Возврат Значение; + КонецЕсли; + Возврат Значение; +КонецФункции \ No newline at end of file From e40a786fef5f118b230bcc336ec0892a5cc3d6af Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sun, 26 Apr 2020 01:23:36 +0700 Subject: [PATCH 148/444] =?UTF-8?q?=D0=98=D1=81=D0=BA=D0=BB=D1=8E=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BD=D0=B5=20=D0=BF=D1=80=D0=B8?= =?UTF-8?q?=D0=BC=D0=B8=D1=82=D0=B8=D0=B2=D0=BE=D0=B2,=20=D0=B4=D0=BE?= =?UTF-8?q?=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5=D0=BD=D0=B0=20=D0=B4=D0=BE=D0=BA?= =?UTF-8?q?=D1=83=D0=BC=D0=B5=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D1=8F=20=D0=BD?= =?UTF-8?q?=D0=B0=20ru,=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B8=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5=20=D0=B8=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=20=D1=84=D0=B0=D0=B9=D0=BB=D0=B0=20=D0=BA=D0=B5=D0=B9?= =?UTF-8?q?=D1=81=D0=B0=20=D0=B4=D0=BB=D1=8F=20=D1=82=D0=B5=D1=81=D1=82?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FunctionReturnsSamePrimitive.md | 71 ++++++++++++++ .../FunctionReturnsSamePrimitive.md | 36 +++++++ ...unctionReturnsSamePrimitiveDiagnostic.java | 96 +++++++++++++------ ...turnsSamePrimitiveDiagnostic_en.properties | 5 +- ...turnsSamePrimitiveDiagnostic_ru.properties | 5 +- ...ionReturnsSamePrimitiveDiagnosticTest.java | 10 +- ...unctionReturnsSamePrimitiveDiagnostic.bsl} | 3 +- 7 files changed, 192 insertions(+), 34 deletions(-) create mode 100644 docs/diagnostics/FunctionReturnsSamePrimitive.md create mode 100644 docs/en/diagnostics/FunctionReturnsSamePrimitive.md rename src/test/resources/diagnostics/{FunctionReturnsSameValueDiagnostic.bsl => FunctionReturnsSamePrimitiveDiagnostic.bsl} (94%) diff --git a/docs/diagnostics/FunctionReturnsSamePrimitive.md b/docs/diagnostics/FunctionReturnsSamePrimitive.md new file mode 100644 index 00000000000..464ba00e5f5 --- /dev/null +++ b/docs/diagnostics/FunctionReturnsSamePrimitive.md @@ -0,0 +1,71 @@ +# Функция всегда возвращает одно и то же примитивное значение () + + + +## + + +## Описание диагностики + + +Функция не должна возвращать одно и тоже примитивное значение. Если результат функции не учитывается - то нужно функцию +переписать на процедуру. + +## Примеры + + +Плохо: +```bsl +Функция ПроверитьСтроку(Знач СтрокаТаблицы) + + Если ЭтоХорошаяСтрока(СтрокаТаблицы) Тогда + ДелаемЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + Возврат Истина; + ИначеЕсли ЭтоТожеНеплохаяСтрока(СтрокаТаблицы) Тогда + ДелаемДругоеЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + Возврат Истина; + Иначе + Возврат Истина; + КонецЕсли; + +КонецФункции +``` + +Хорошо: +```bsl +Процедура ПроверитьСтроку(Знач СтрокаТаблицы) + + Если ЭтоХорошаяСтрока(СтрокаТаблицы) Тогда + ДелаемЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + ИначеЕсли ЭтоТожеНеплохаяСтрока(СтрокаТаблицы) Тогда + ДелаемДругоеЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + Иначе + ДелаемЧтотоДругоеИзВеткиИначе(); + КонецЕсли; + +КонецПроцедуры +``` + +## Источники + + + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Параметр конфигурационного файла + +```json +"": +``` \ No newline at end of file diff --git a/docs/en/diagnostics/FunctionReturnsSamePrimitive.md b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md new file mode 100644 index 00000000000..4e7e0f78ada --- /dev/null +++ b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md @@ -0,0 +1,36 @@ +# + + + +## + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Parameter for config + +```json +"": +``` diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java index 6c7c1c750b4..c0dc94b38af 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java @@ -1,5 +1,27 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; @@ -8,35 +30,31 @@ import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import com.github._1c_syntax.bsl.languageserver.utils.RelatedInformation; import com.github._1c_syntax.bsl.languageserver.utils.Trees; -import com.github._1c_syntax.bsl.parser.BSLLexer; import com.github._1c_syntax.bsl.parser.BSLParser; +import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; -import org.checkerframework.checker.nullness.Opt; -import org.eclipse.lsp4j.DiagnosticRelatedInformation; +import org.eclipse.lsp4j.Range; -import javax.tools.Diagnostic; -import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; import java.util.List; -import java.util.Objects; import java.util.Optional; -import java.util.Set; -import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.Stream; @DiagnosticMetadata( type = DiagnosticType.ERROR, - severity = DiagnosticSeverity.INFO, - minutesToFix = 1, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 5, tags = { + DiagnosticTag.DESIGN, DiagnosticTag.BADPRACTICE } ) public class FunctionReturnsSamePrimitiveDiagnostic extends AbstractVisitorDiagnostic { + + private static final String KEY_MESSAGE = "diagnosticMessageReturnStatement"; + public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { super(info); } @@ -44,25 +62,49 @@ public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { @Override public ParseTree visitFunction(BSLParser.FunctionContext ctx) { var tree = Trees.findAllRuleNodes(ctx, BSLParser.RULE_returnStatement); - if (tree.size() > 1){ - var set = tree.stream() + if (tree.size() > 1) { + var expressions = tree.stream() .map(BSLParser.ReturnStatementContext.class::cast) .map(BSLParser.ReturnStatementContext::expression) .flatMap(Stream::ofNullable) - .map(BSLParser.ExpressionContext::getText) - .collect(Collectors.toSet()); - if (set.size() == 1) { - var relatedInformation = tree.stream() - .map(BSLParser.ReturnStatementContext.class::cast) - .map(statement -> - RelatedInformation.create( - documentContext.getUri(), - Ranges.create(statement.getStart()), - info.getMessage())) - .collect(Collectors.toList()); - diagnosticStorage.addDiagnostic(ctx.funcDeclaration(), info.getMessage(), relatedInformation); - } + .collect(Collectors.toList()); + + expressions.stream() + .map(expression -> Trees.findAllRuleNodes(expression, BSLParser.RULE_complexIdentifier)) + .filter(Collection::isEmpty) + .findAny() + .ifPresent( + parseTrees -> checkPrimitiveValue(ctx, tree, expressions) + ); } return ctx; } + + private void checkPrimitiveValue( + BSLParser.FunctionContext ctx, Collection tree, List expressions) { + + var set = expressions.stream().map(BSLParser.ExpressionContext::getText).collect(Collectors.toSet()); + if (set.size() == 1) { + var relatedInformation = tree.stream() + .map(BSLParser.ReturnStatementContext.class::cast) + .map(statement -> RelatedInformation.create( + documentContext.getUri(), + Ranges.create(statement.getStart()), + info.getResourceString(KEY_MESSAGE))) + .collect(Collectors.toList()); + diagnosticStorage.addDiagnostic(getSubNameRange(ctx), info.getMessage(), relatedInformation); + } + + } + + private Range getSubNameRange(ParserRuleContext ctx) { + return Optional.ofNullable(Trees.getAncestorByRuleIndex(ctx, BSLParser.RULE_sub)) + .map(BSLParser.SubContext.class::cast) + .map(context -> documentContext.getSymbolTree().getMethodSymbol(context)) + .filter(Optional::isPresent) + .map(Optional::get) + .map(MethodSymbol::getSubNameRange) + .orElse(Ranges.create(ctx.getStart())); + } + } diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties index 66831715dfd..fb0ac7ddbfc 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties @@ -1,2 +1,3 @@ -diagnosticMessage= -diagnosticName= +diagnosticMessage=Check that the same primitive value is returned in the function +diagnosticName=The function always returns the same primitive value +diagnosticMessageReturnStatement=Repeat return value diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties index df22ba92595..2ac2ec79e1b 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties @@ -1,2 +1,3 @@ -diagnosticMessage=Проверьте правильность возврата одного и того жк значения в функции -diagnosticName=Функция всегда возвращает одно и то же значение +diagnosticMessage=Проверьте правильность возврата одного и того же примитивного значения в функции +diagnosticName=Функция всегда возвращает одно и то же примитивное значение +diagnosticMessageReturnStatement=Повтор возвращаемого значения diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java index 1517ec60634..1af20cc2524 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java @@ -1,5 +1,6 @@ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; @@ -17,7 +18,14 @@ void test() { List diagnostics = getDiagnostics(); - assertThat(diagnostics).hasSize(4); + assertThat(diagnostics) + .hasSize(3) + .anyMatch(diagnostic -> diagnostic.getRange().equals( + Ranges.create(0, 8, 0, 23))) + .anyMatch(diagnostic -> diagnostic.getRange().equals( + Ranges.create(25, 8, 25, 14))) + .anyMatch(diagnostic -> diagnostic.getRange().equals( + Ranges.create(35, 8, 35, 17))); } } diff --git a/src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl b/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl similarity index 94% rename from src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl rename to src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl index c8e246d08f3..66f0df2975e 100644 --- a/src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl +++ b/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl @@ -41,8 +41,7 @@ Возврат 20; КонецФункции -// надо бы подумать как правильно диагностировать -// по идее ошибка +// здесь нет ошибки, т.к. проверка только на примитивы Функция СтавкаНДС2(Ставка) Значение = 20; Если Ставка = "Ставка18" Тогда From c9a65c76b9e44a8eb71347890ffe7287598a1bb4 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sun, 26 Apr 2020 01:38:38 +0700 Subject: [PATCH 149/444] =?UTF-8?q?=D0=94=D0=BE=D0=BF=D0=BE=D0=BB=D0=BD?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D1=82=D0=B0=D1=86=D0=B8=D1=8F,=20=D0=B7=D0=B0=D0=BF=D1=83?= =?UTF-8?q?=D1=89=D0=B5=D0=BD=20=D0=BF=D1=80=D0=B5=D0=BA=D0=BE=D0=BC=D0=BC?= =?UTF-8?q?=D0=B8=D1=82,=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=BF=D0=BE=D1=82=D0=B5=D1=80=D1=8F=D0=BD=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F=20=D0=BB=D0=B8=D1=86=D0=B5=D0=BD=D0=B7=D0=B8=D1=8F?= =?UTF-8?q?=20=D0=B2=20=D1=84=D0=B0=D0=B9=D0=BB=D0=B5=20=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=B0.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FunctionReturnsSamePrimitive.md | 18 +++---- docs/diagnostics/index.md | 12 ++--- .../FunctionReturnsSamePrimitive.md | 51 ++++++++++++++++--- docs/en/diagnostics/index.md | 12 ++--- .../configuration/parameters-schema.json | 10 ++++ .../languageserver/configuration/schema.json | 3 ++ ...ionReturnsSamePrimitiveDiagnosticTest.java | 21 ++++++++ 7 files changed, 94 insertions(+), 33 deletions(-) diff --git a/docs/diagnostics/FunctionReturnsSamePrimitive.md b/docs/diagnostics/FunctionReturnsSamePrimitive.md index 464ba00e5f5..cbd70345b65 100644 --- a/docs/diagnostics/FunctionReturnsSamePrimitive.md +++ b/docs/diagnostics/FunctionReturnsSamePrimitive.md @@ -1,8 +1,8 @@ -# Функция всегда возвращает одно и то же примитивное значение () +# Функция всегда возвращает одно и то же примитивное значение (FunctionReturnsSamePrimitive) - - -## +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Ошибка` | `BSL`
`OS` | `Важный` | `Да` | `5` | `design`
`badpractice` | ## Описание диагностики @@ -55,17 +55,17 @@ * Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) --> ## Сниппеты - + ### Экранирование кода ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:FunctionReturnsSamePrimitive-off +// BSLLS:FunctionReturnsSamePrimitive-on ``` ### Параметр конфигурационного файла ```json -"": -``` \ No newline at end of file +"FunctionReturnsSamePrimitive": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index eac9427cc9b..0fab59f2d5f 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,11 +8,11 @@ ## Список реализованных диагностик -Общее количество: **93** +Общее количество: **89** -* Дефект кода: **58** +* Дефект кода: **55** * Уязвимость: **2** -* Ошибка: **31** +* Ошибка: **30** * Потенциальная уязвимость: **2** | Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги | @@ -24,27 +24,23 @@ | [CognitiveComplexity](CognitiveComplexity.md) | Когнитивная сложность | Да | Критичный | Дефект кода | `brainoverload` | | [CommentedCode](CommentedCode.md) | Закомментированный фрагмент кода | Да | Незначительный | Дефект кода | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Нарушение правил работы с транзакциями для метода 'ЗафиксироватьТранзакцию' | Да | Важный | Ошибка | `standard` | -| [CommonModuleAssign](CommonModuleAssign.md) | Присвоение общему модулю | Да | Блокирующий | Ошибка | `error` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Директивы компиляции методов | Да | Важный | Дефект кода | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Лишняя директива компиляции | Да | Важный | Дефект кода | `clumsy`
`standard`
`unpredictable` | -| [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Подряд идущие пустые строки | Да | Информационный | Дефект кода | `badpractice` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Выполнение запроса в цикле | Да | Критичный | Ошибка | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Цикломатическая сложность | Да | Критичный | Дефект кода | `brainoverload` | -| [DataExchangeLoading](DataExchangeLoading.md) | Отсутствует проверка признака ОбменДанными.Загрузка в обработчике событий объекта | Да | Критичный | Ошибка | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Удаление элемента при обходе коллекции посредством оператора "Для каждого ... Из ... Цикл" | Да | Важный | Ошибка | `standard`
`error` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Использование устаревшего метода "ТекущаяДата" | Да | Важный | Ошибка | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Использование устаревшего метода "Найти" | Да | Незначительный | Дефект кода | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Ограничение на использование устаревшего метода "Сообщить" | Да | Незначительный | Дефект кода | `standard`
`deprecated` | -| [DeprecatedMethods8310](DeprecatedMethods8310.md) | Использование устаревшего метода клиентского приложения | Да | Информационный | Дефект кода | `deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Устаревшее использование типа "УправляемаяФорма" | Да | Информационный | Дефект кода | `standard`
`deprecated` | | [DuplicateRegion](DuplicateRegion.md) | Повторяющиеся разделы модуля | Да | Информационный | Дефект кода | `standard` | | [EmptyCodeBlock](EmptyCodeBlock.md) | Пустой блок кода | Да | Важный | Дефект кода | `badpractice`
`suspicious` | | [EmptyRegion](EmptyRegion.md) | Область не должна быть пустой | Да | Информационный | Дефект кода | `standard` | | [EmptyStatement](EmptyStatement.md) | Пустой оператор | Да | Информационный | Дефект кода | `badpractice` | -| [ExcessiveAutoTestCheck](ExcessiveAutoTestCheck.md) | Избыточная проверка параметра АвтоТест | Да | Незначительный | Дефект кода | `standard`
`deprecated` | | [ExtraCommas](ExtraCommas.md) | Запятые без указания параметра в конце вызова метода | Да | Важный | Дефект кода | `standard`
`badpractice` | | [FormDataToValue](FormDataToValue.md) | Использование метода ДанныеФормыВЗначение | Да | Информационный | Дефект кода | `badpractice` | | [FunctionNameStartsWithGet](FunctionNameStartsWithGet.md) | Имя функции не должно начинаться с "Получить" | Нет | Информационный | Дефект кода | `standard` | +| [FunctionReturnsSamePrimitive](FunctionReturnsSamePrimitive.md) | Функция всегда возвращает одно и то же примитивное значение | Да | Важный | Ошибка | `design`
`badpractice` | | [FunctionShouldHaveReturn](FunctionShouldHaveReturn.md) | Функция должна содержать возврат | Да | Важный | Ошибка | `suspicious`
`unpredictable` | | [GetFormMethod](GetFormMethod.md) | Использование метода ПолучитьФорму | Да | Важный | Ошибка | `error` | | [IdenticalExpressions](IdenticalExpressions.md) | Одинаковые выражения слева и справа от "foo" оператора | Да | Важный | Ошибка | `suspicious` | diff --git a/docs/en/diagnostics/FunctionReturnsSamePrimitive.md b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md index 4e7e0f78ada..a7b5d484497 100644 --- a/docs/en/diagnostics/FunctionReturnsSamePrimitive.md +++ b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md @@ -1,16 +1,51 @@ -# +# The function always returns the same primitive value (FunctionReturnsSamePrimitive) - - -## +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Error` | `BSL`
`OS` | `Major` | `Yes` | `5` | `design`
`badpractice` | ## Description +A function should not return the same primitive value. If the result of the function isn't use into code, then you need the function +rewrite to the procedure. + ## Examples +Bad: +```bsl +Function CheckString(Val RowTable) + + If ItsGoodString(RowTable) Then + ActionGood(); + Return True; + ElsIf ItsNodBadString(RowTable) Then + ActionNoBad(); + Return True; + Else + Return True; + EndIf; + +EndFunction +``` + +Good: +```bsl +Function CheckString(Val RowTable) + + If ItsGoodString(RowTable) Then + ActionGood(); + ElsIf ItsNodBadString(RowTable) Then + ActionNoBad(); + Else + ActionElse(); + EndIf; + +EndFunction +``` + ## Sources ## Snippets - + ### Diagnostic ignorance in code ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:FunctionReturnsSamePrimitive-off +// BSLLS:FunctionReturnsSamePrimitive-on ``` ### Parameter for config ```json -"": +"FunctionReturnsSamePrimitive": false ``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 40af697dbe0..b22ab4029d5 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,10 +8,10 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **93** +Total: **89** -* Error: **31** -* Code smell: **58** +* Error: **30** +* Code smell: **55** * Vulnerability: **2** * Security Hotspot: **2** @@ -24,27 +24,23 @@ Total: **93** | [CognitiveComplexity](CognitiveComplexity.md) | Cognitive complexity | Yes | Critical | Code smell | `brainoverload` | | [CommentedCode](CommentedCode.md) | Commented out code | Yes | Minor | Code smell | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Violating transaction rules for the 'CommitTransaction' method | Yes | Major | Error | `standard` | -| [CommonModuleAssign](CommonModuleAssign.md) | CommonModuleAssign | Yes | Blocker | Error | `error` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Methods compilation directive | Yes | Major | Code smell | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Needless compilation directive | Yes | Major | Code smell | `clumsy`
`standard`
`unpredictable` | -| [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Consecutive empty lines | Yes | Info | Code smell | `badpractice` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Execution query on cycle | Yes | Critical | Error | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Cyclomatic complexity | Yes | Critical | Code smell | `brainoverload` | -| [DataExchangeLoading](DataExchangeLoading.md) | There is no check for the attribute DataExchange.Load in the object's event handler | Yes | Critical | Error | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Deleting an item when iterating through collection using the operator "For each ... In ... Do" | Yes | Major | Error | `standard`
`error` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Using of the deprecated method "CurrentDate" | Yes | Major | Error | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Using of the deprecated method "Find" | Yes | Minor | Code smell | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Restriction on the use of deprecated "Message" method | Yes | Minor | Code smell | `standard`
`deprecated` | -| [DeprecatedMethods8310](DeprecatedMethods8310.md) | Deprecated client application method. | Yes | Info | Code smell | `deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Deprecated ManagedForm type | Yes | Info | Code smell | `standard`
`deprecated` | | [DuplicateRegion](DuplicateRegion.md) | Duplicate regions | Yes | Info | Code smell | `standard` | | [EmptyCodeBlock](EmptyCodeBlock.md) | Empty code block | Yes | Major | Code smell | `badpractice`
`suspicious` | | [EmptyRegion](EmptyRegion.md) | The region should not be empty | Yes | Info | Code smell | `standard` | | [EmptyStatement](EmptyStatement.md) | Empty statement | Yes | Info | Code smell | `badpractice` | -| [ExcessiveAutoTestCheck](ExcessiveAutoTestCheck.md) | Excessive AutoTest Check | Yes | Minor | Code smell | `standard`
`deprecated` | | [ExtraCommas](ExtraCommas.md) | Commas without a parameter at the end of a method call | Yes | Major | Code smell | `standard`
`badpractice` | | [FormDataToValue](FormDataToValue.md) | FormDataToValue method call | Yes | Info | Code smell | `badpractice` | | [FunctionNameStartsWithGet](FunctionNameStartsWithGet.md) | Function name shouldn't start with "Получить" | No | Info | Code smell | `standard` | +| [FunctionReturnsSamePrimitive](FunctionReturnsSamePrimitive.md) | The function always returns the same primitive value | Yes | Major | Error | `design`
`badpractice` | | [FunctionShouldHaveReturn](FunctionShouldHaveReturn.md) | The function should have return | Yes | Major | Error | `suspicious`
`unpredictable` | | [GetFormMethod](GetFormMethod.md) | GetForm method call | Yes | Major | Error | `error` | | [IdenticalExpressions](IdenticalExpressions.md) | There are identical sub-expressions to the left and to the right of the "foo" operator | Yes | Major | Error | `suspicious` | diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index 5ade19e04ce..f91fbfa6928 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -344,6 +344,16 @@ "title": "Function name shouldn't start with \"\u041f\u043e\u043b\u0443\u0447\u0438\u0442\u044c\"", "$id": "#/definitions/FunctionNameStartsWithGet" }, + "FunctionReturnsSamePrimitive": { + "description": "The function always returns the same primitive value", + "default": null, + "type": [ + "boolean", + "object" + ], + "title": "The function always returns the same primitive value", + "$id": "#/definitions/FunctionReturnsSamePrimitive" + }, "FunctionShouldHaveReturn": { "description": "The function should have return", "default": true, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index e4e5668caff..7dea557b8e5 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -107,6 +107,9 @@ "FunctionNameStartsWithGet": { "$ref": "parameters-schema.json#/definitions/FunctionNameStartsWithGet" }, + "FunctionReturnsSamePrimitive": { + "$ref": "diagnostics-schema.json#/definitions/FunctionReturnsSamePrimitive" + }, "FunctionShouldHaveReturn": { "$ref": "parameters-schema.json#/definitions/FunctionShouldHaveReturn" }, diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java index 1af20cc2524..b4d1a3cd769 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java @@ -1,3 +1,24 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; From 17fcd03e91d54dac680eff364a240876302c568b Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sun, 26 Apr 2020 02:14:16 +0700 Subject: [PATCH 150/444] =?UTF-8?q?+=20=D0=BF=D1=80=D0=B5=D0=BA=D0=BE?= =?UTF-8?q?=D0=BC=D0=BC=D0=B8=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/index.md | 11 ++++++++--- docs/en/diagnostics/index.md | 11 ++++++++--- .../configuration/parameters-schema.json | 2 +- .../bsl/languageserver/configuration/schema.json | 2 +- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 0fab59f2d5f..2dfbde26f8d 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,11 +8,11 @@ ## Список реализованных диагностик -Общее количество: **89** +Общее количество: **94** -* Дефект кода: **55** +* Дефект кода: **58** * Уязвимость: **2** -* Ошибка: **30** +* Ошибка: **32** * Потенциальная уязвимость: **2** | Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги | @@ -24,19 +24,24 @@ | [CognitiveComplexity](CognitiveComplexity.md) | Когнитивная сложность | Да | Критичный | Дефект кода | `brainoverload` | | [CommentedCode](CommentedCode.md) | Закомментированный фрагмент кода | Да | Незначительный | Дефект кода | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Нарушение правил работы с транзакциями для метода 'ЗафиксироватьТранзакцию' | Да | Важный | Ошибка | `standard` | +| [CommonModuleAssign](CommonModuleAssign.md) | Присвоение общему модулю | Да | Блокирующий | Ошибка | `error` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Директивы компиляции методов | Да | Важный | Дефект кода | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Лишняя директива компиляции | Да | Важный | Дефект кода | `clumsy`
`standard`
`unpredictable` | +| [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Подряд идущие пустые строки | Да | Информационный | Дефект кода | `badpractice` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Выполнение запроса в цикле | Да | Критичный | Ошибка | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Цикломатическая сложность | Да | Критичный | Дефект кода | `brainoverload` | +| [DataExchangeLoading](DataExchangeLoading.md) | Отсутствует проверка признака ОбменДанными.Загрузка в обработчике событий объекта | Да | Критичный | Ошибка | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Удаление элемента при обходе коллекции посредством оператора "Для каждого ... Из ... Цикл" | Да | Важный | Ошибка | `standard`
`error` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Использование устаревшего метода "ТекущаяДата" | Да | Важный | Ошибка | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Использование устаревшего метода "Найти" | Да | Незначительный | Дефект кода | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Ограничение на использование устаревшего метода "Сообщить" | Да | Незначительный | Дефект кода | `standard`
`deprecated` | +| [DeprecatedMethods8310](DeprecatedMethods8310.md) | Использование устаревшего метода клиентского приложения | Да | Информационный | Дефект кода | `deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Устаревшее использование типа "УправляемаяФорма" | Да | Информационный | Дефект кода | `standard`
`deprecated` | | [DuplicateRegion](DuplicateRegion.md) | Повторяющиеся разделы модуля | Да | Информационный | Дефект кода | `standard` | | [EmptyCodeBlock](EmptyCodeBlock.md) | Пустой блок кода | Да | Важный | Дефект кода | `badpractice`
`suspicious` | | [EmptyRegion](EmptyRegion.md) | Область не должна быть пустой | Да | Информационный | Дефект кода | `standard` | | [EmptyStatement](EmptyStatement.md) | Пустой оператор | Да | Информационный | Дефект кода | `badpractice` | +| [ExcessiveAutoTestCheck](ExcessiveAutoTestCheck.md) | Избыточная проверка параметра АвтоТест | Да | Незначительный | Дефект кода | `standard`
`deprecated` | | [ExtraCommas](ExtraCommas.md) | Запятые без указания параметра в конце вызова метода | Да | Важный | Дефект кода | `standard`
`badpractice` | | [FormDataToValue](FormDataToValue.md) | Использование метода ДанныеФормыВЗначение | Да | Информационный | Дефект кода | `badpractice` | | [FunctionNameStartsWithGet](FunctionNameStartsWithGet.md) | Имя функции не должно начинаться с "Получить" | Нет | Информационный | Дефект кода | `standard` | diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index b22ab4029d5..2f31a4424d4 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,10 +8,10 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **89** +Total: **94** -* Error: **30** -* Code smell: **55** +* Error: **32** +* Code smell: **58** * Vulnerability: **2** * Security Hotspot: **2** @@ -24,19 +24,24 @@ Total: **89** | [CognitiveComplexity](CognitiveComplexity.md) | Cognitive complexity | Yes | Critical | Code smell | `brainoverload` | | [CommentedCode](CommentedCode.md) | Commented out code | Yes | Minor | Code smell | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Violating transaction rules for the 'CommitTransaction' method | Yes | Major | Error | `standard` | +| [CommonModuleAssign](CommonModuleAssign.md) | CommonModuleAssign | Yes | Blocker | Error | `error` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Methods compilation directive | Yes | Major | Code smell | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Needless compilation directive | Yes | Major | Code smell | `clumsy`
`standard`
`unpredictable` | +| [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Consecutive empty lines | Yes | Info | Code smell | `badpractice` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Execution query on cycle | Yes | Critical | Error | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Cyclomatic complexity | Yes | Critical | Code smell | `brainoverload` | +| [DataExchangeLoading](DataExchangeLoading.md) | There is no check for the attribute DataExchange.Load in the object's event handler | Yes | Critical | Error | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Deleting an item when iterating through collection using the operator "For each ... In ... Do" | Yes | Major | Error | `standard`
`error` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Using of the deprecated method "CurrentDate" | Yes | Major | Error | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Using of the deprecated method "Find" | Yes | Minor | Code smell | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Restriction on the use of deprecated "Message" method | Yes | Minor | Code smell | `standard`
`deprecated` | +| [DeprecatedMethods8310](DeprecatedMethods8310.md) | Deprecated client application method. | Yes | Info | Code smell | `deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Deprecated ManagedForm type | Yes | Info | Code smell | `standard`
`deprecated` | | [DuplicateRegion](DuplicateRegion.md) | Duplicate regions | Yes | Info | Code smell | `standard` | | [EmptyCodeBlock](EmptyCodeBlock.md) | Empty code block | Yes | Major | Code smell | `badpractice`
`suspicious` | | [EmptyRegion](EmptyRegion.md) | The region should not be empty | Yes | Info | Code smell | `standard` | | [EmptyStatement](EmptyStatement.md) | Empty statement | Yes | Info | Code smell | `badpractice` | +| [ExcessiveAutoTestCheck](ExcessiveAutoTestCheck.md) | Excessive AutoTest Check | Yes | Minor | Code smell | `standard`
`deprecated` | | [ExtraCommas](ExtraCommas.md) | Commas without a parameter at the end of a method call | Yes | Major | Code smell | `standard`
`badpractice` | | [FormDataToValue](FormDataToValue.md) | FormDataToValue method call | Yes | Info | Code smell | `badpractice` | | [FunctionNameStartsWithGet](FunctionNameStartsWithGet.md) | Function name shouldn't start with "Получить" | No | Info | Code smell | `standard` | diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index f91fbfa6928..382ac58cfa0 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -346,7 +346,7 @@ }, "FunctionReturnsSamePrimitive": { "description": "The function always returns the same primitive value", - "default": null, + "default": true, "type": [ "boolean", "object" diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 7dea557b8e5..22e7f39541f 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -108,7 +108,7 @@ "$ref": "parameters-schema.json#/definitions/FunctionNameStartsWithGet" }, "FunctionReturnsSamePrimitive": { - "$ref": "diagnostics-schema.json#/definitions/FunctionReturnsSamePrimitive" + "$ref": "parameters-schema.json#/definitions/FunctionReturnsSamePrimitive" }, "FunctionShouldHaveReturn": { "$ref": "parameters-schema.json#/definitions/FunctionShouldHaveReturn" From c8ca3ba1d16ac0e4a1e64c1c5b6953a9ff0c4ce4 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sun, 26 Apr 2020 08:59:12 +0700 Subject: [PATCH 151/444] =?UTF-8?q?=D0=98=D1=81=D0=BA=D0=BB=D1=8E=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B8=D0=B7=20=D0=BF=D1=80=D0=BE?= =?UTF-8?q?=D0=B2=D0=B5=D1=80=D0=BA=D0=B8=20=D0=BF=D0=BE=D0=B4=D0=BA=D0=BB?= =?UTF-8?q?=D1=8E=D1=87=D0=B0=D0=B5=D0=BC=D1=8B=D1=85=20=D1=84=D1=83=D0=BD?= =?UTF-8?q?=D0=BA=D1=86=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...unctionReturnsSamePrimitiveDiagnostic.java | 18 ++++++++++++--- ...FunctionReturnsSamePrimitiveDiagnostic.bsl | 22 ++++++++++++++++++- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java index c0dc94b38af..ba0f48586e9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java @@ -38,6 +38,7 @@ import java.util.Collection; import java.util.List; import java.util.Optional; +import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -54,6 +55,8 @@ public class FunctionReturnsSamePrimitiveDiagnostic extends AbstractVisitorDiagnostic { private static final String KEY_MESSAGE = "diagnosticMessageReturnStatement"; + private static final Pattern pattern = Pattern.compile( + "^(подключаемый|attachable)_", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { super(info); @@ -61,6 +64,17 @@ public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { @Override public ParseTree visitFunction(BSLParser.FunctionContext ctx) { + + var abortCheck = Optional.ofNullable(ctx.funcDeclaration()) + .map(BSLParser.FuncDeclarationContext::subName) + .filter(subNameContext -> pattern.matcher(subNameContext.getText()).find()) + .isPresent(); + + // Исключаем подключаемые методы + if (abortCheck) { + return ctx; + } + var tree = Trees.findAllRuleNodes(ctx, BSLParser.RULE_returnStatement); if (tree.size() > 1) { var expressions = tree.stream() @@ -100,9 +114,7 @@ private void checkPrimitiveValue( private Range getSubNameRange(ParserRuleContext ctx) { return Optional.ofNullable(Trees.getAncestorByRuleIndex(ctx, BSLParser.RULE_sub)) .map(BSLParser.SubContext.class::cast) - .map(context -> documentContext.getSymbolTree().getMethodSymbol(context)) - .filter(Optional::isPresent) - .map(Optional::get) + .flatMap(context -> documentContext.getSymbolTree().getMethodSymbol(context)) .map(MethodSymbol::getSubNameRange) .orElse(Ranges.create(ctx.getStart())); } diff --git a/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl b/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl index 66f0df2975e..67f0824d2ea 100644 --- a/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl +++ b/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl @@ -48,4 +48,24 @@ Возврат Значение; КонецЕсли; Возврат Значение; -КонецФункции \ No newline at end of file +КонецФункции + +Функция Подключаемый_КакаяТоКоманда(Команда) + + Если ЗначениеЗаполнено(ТекущаяДата) Тогда + Возврат Неопределено; + КонецЕсли; + + Возврат Неопределено; + +КонецФункции + +Function Attachable_RandomAction(Command) + + If ValueIsFilled(CurrentDate) Then + Return Undefined; + EndIf; + + Return Undefined; + +EndFunction From 4cef417ce48e4d7cb4a51bab5886da44ed343171 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sun, 26 Apr 2020 08:59:21 +0700 Subject: [PATCH 152/444] =?UTF-8?q?=D0=94=D0=BE=D0=BF=D0=BE=D0=BB=D0=BD?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/FunctionReturnsSamePrimitive.md | 15 +++++++++++++++ .../diagnostics/FunctionReturnsSamePrimitive.md | 15 +++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/docs/diagnostics/FunctionReturnsSamePrimitive.md b/docs/diagnostics/FunctionReturnsSamePrimitive.md index cbd70345b65..41eb85dc3d6 100644 --- a/docs/diagnostics/FunctionReturnsSamePrimitive.md +++ b/docs/diagnostics/FunctionReturnsSamePrimitive.md @@ -46,6 +46,21 @@ КонецПроцедуры ``` +## Особенности + +Из проверки исключаются подключаемые Функции. Например: +```bsl +Функция Подключаемый_КакаяТоКоманда(Команда) + + Если ЗначениеЗаполнено(ТекущаяДата) Тогда + Возврат Неопределено; + КонецЕсли; + + Возврат Неопределено; + +КонецФункции +``` + ## Источники +## Описание диагностики + + +## Примеры + + +## Источники + + + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Параметр конфигурационного файла + +```json +"": +``` \ No newline at end of file diff --git a/docs/en/diagnostics/CommonModuleNameClientServer.md b/docs/en/diagnostics/CommonModuleNameClientServer.md new file mode 100644 index 00000000000..4e7e0f78ada --- /dev/null +++ b/docs/en/diagnostics/CommonModuleNameClientServer.md @@ -0,0 +1,36 @@ +# + + + +## + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Parameter for config + +```json +"": +``` diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java index 9a985ae7912..efc3d229d53 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java @@ -35,6 +35,7 @@ import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import com.github._1c_syntax.bsl.parser.Tokenizer; +import com.github._1c_syntax.mdclasses.mdo.MDObjectBase; import com.github._1c_syntax.mdclasses.metadata.SupportConfiguration; import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; import com.github._1c_syntax.mdclasses.metadata.additional.SupportVariant; @@ -51,6 +52,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Optional; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; @@ -79,6 +81,7 @@ public class DocumentContext { private final Lazy diagnosticIgnoranceData = new Lazy<>(this::computeDiagnosticIgnorance, computeLock); private final Lazy metrics = new Lazy<>(this::computeMetrics, computeLock); + private final Lazy> mdObject = new Lazy<>(this::computeMdObject, computeLock); public DocumentContext(URI uri, String content, ServerContext context) { this.uri = Absolute.uri(uri); @@ -187,6 +190,10 @@ public Map getSupportVariants() { return supportVariants.getOrCompute(); } + public Optional getMdObject() { + return mdObject.getOrCompute(); + } + public void rebuild(String content) { computeLock.lock(); clear(); @@ -329,4 +336,8 @@ private DiagnosticIgnoranceComputer.Data computeDiagnosticIgnorance() { return diagnosticIgnoranceComputer.compute(); } + private Optional computeMdObject() { + return Optional.ofNullable(context.getConfiguration().getModulesByURI().get(getUri())); + } + } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java new file mode 100644 index 00000000000..9e79aad28a1 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java @@ -0,0 +1,56 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.mdclasses.mdo.MDObjectBase; +import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; +import org.antlr.v4.runtime.tree.ParseTree; + +import java.util.Optional; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.INFO, + scope = DiagnosticScope.BSL, + modules = { + ModuleType.CommonModule + }, + minutesToFix = 2, + tags = { + DiagnosticTag.STANDARD + } + +) +public class CommonModuleNameClientServerDiagnostic extends AbstractVisitorDiagnostic { + public CommonModuleNameClientServerDiagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + public ParseTree visitFile(BSLParser.FileContext ctx) { + + Optional commonModuleOptional = documentContext.getMdObject(); + + if (commonModuleOptional.isEmpty() + || !(commonModuleOptional.get() instanceof CommonModule)) { + return super.visitFile(ctx); + } + + CommonModule commonModule = (CommonModule) commonModuleOptional.get(); + + if (commonModule.isServer() + && commonModule.isClientManagedApplication() + && !commonModule.getName().endsWith("КлиентСервер")) { + diagnosticStorage.addDiagnostic(ctx.getStart()); + } + + return super.visitFile(ctx); + } + +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic_en.properties new file mode 100644 index 00000000000..66831715dfd --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage= +diagnosticName= diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic_ru.properties new file mode 100644 index 00000000000..40188ca542c --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=<Сообщение> +diagnosticName=<Имя диагностики> diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java new file mode 100644 index 00000000000..70c5e864c82 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java @@ -0,0 +1,71 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.ServerContext; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.mdclasses.mdo.MDObjectBase; +import com.github._1c_syntax.utils.Absolute; +import lombok.SneakyThrows; +import org.apache.commons.io.FileUtils; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +class CommonModuleNameClientServerDiagnosticTest extends AbstractDiagnosticTest { + CommonModuleNameClientServerDiagnosticTest() { + super(CommonModuleNameClientServerDiagnostic.class); + } + + private static final String PATH_TO_METADATA = "src/test/resources/metadata"; + private static final String PATH_TO_MODULE_FILE = "src/test/resources/metadata/CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; + + + @SneakyThrows + @Test + void test() { + + Path path = Absolute.path(PATH_TO_METADATA); + var serverContext = spy(new ServerContext(path)); + var configuration = spy(serverContext.getConfiguration()); + + Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + + var documentContext = spy(new DocumentContext( + testFile.toUri(), + FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), + serverContext + )); + + when(documentContext.getServerContext()).thenReturn(serverContext); + + when(serverContext.getConfiguration()).thenReturn(configuration); + var modules = spy(configuration.getModulesByURI()); + + when(configuration.getModulesByURI()).thenReturn(modules); + + CommonModule myModule = (CommonModule) modules.get(documentContext.getUri()); + + var spymodule = spy(myModule); + when(spymodule.isServer()).thenReturn(Boolean.TRUE); + when(spymodule.isClientManagedApplication()).thenReturn(Boolean.TRUE); + when(modules.get(documentContext.getUri())).thenReturn(spymodule); + + + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(0, 0, 0, 1); + + } + +} From ba37830972f040080aa6242215d4fa1c3f6f1953 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sat, 18 Apr 2020 09:54:34 +0300 Subject: [PATCH 161/444] =?UTF-8?q?=D1=83=D0=B7=D0=BE=D1=80=D1=8B=20=D0=B2?= =?UTF-8?q?=20=D1=82=D0=B5=D1=81=D1=82=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...monModuleNameClientServerDiagnosticTest.java | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java index 70c5e864c82..9cef18a961b 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java @@ -3,14 +3,12 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.context.ServerContext; import com.github._1c_syntax.mdclasses.mdo.CommonModule; -import com.github._1c_syntax.mdclasses.mdo.MDObjectBase; import com.github._1c_syntax.utils.Absolute; import lombok.SneakyThrows; import org.apache.commons.io.FileUtils; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; -import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; @@ -36,6 +34,7 @@ void test() { Path path = Absolute.path(PATH_TO_METADATA); var serverContext = spy(new ServerContext(path)); var configuration = spy(serverContext.getConfiguration()); + when(serverContext.getConfiguration()).thenReturn(configuration); Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); @@ -44,24 +43,20 @@ void test() { FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), serverContext )); - when(documentContext.getServerContext()).thenReturn(serverContext); - when(serverContext.getConfiguration()).thenReturn(configuration); - var modules = spy(configuration.getModulesByURI()); + var modules = spy(configuration.getModulesByURI()); when(configuration.getModulesByURI()).thenReturn(modules); - CommonModule myModule = (CommonModule) modules.get(documentContext.getUri()); + var module = spy((CommonModule) modules.get(documentContext.getUri())); - var spymodule = spy(myModule); - when(spymodule.isServer()).thenReturn(Boolean.TRUE); - when(spymodule.isClientManagedApplication()).thenReturn(Boolean.TRUE); - when(modules.get(documentContext.getUri())).thenReturn(spymodule); + when(module.isServer()).thenReturn(Boolean.TRUE); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + when(modules.get(documentContext.getUri())).thenReturn(module); List diagnostics = diagnosticInstance.getDiagnostics(documentContext); - assertThat(diagnostics).hasSize(1); assertThat(diagnostics, true) .hasRange(0, 0, 0, 1); From 5fc6de251d1d1a677ac82369162280be025d5871 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sat, 18 Apr 2020 16:03:33 +0300 Subject: [PATCH 162/444] =?UTF-8?q?=D0=BF=D0=BE=D0=BC=D0=B5=D0=BD=D1=8F?= =?UTF-8?q?=D0=BB=D0=BE=D1=81=D1=8C=20=D0=B2=D1=81=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../context/DocumentContext.java | 7 +--- ...ommonModuleNameClientServerDiagnostic.java | 37 +++++++++---------- 2 files changed, 19 insertions(+), 25 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java index efc3d229d53..2836d421a62 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java @@ -81,7 +81,6 @@ public class DocumentContext { private final Lazy diagnosticIgnoranceData = new Lazy<>(this::computeDiagnosticIgnorance, computeLock); private final Lazy metrics = new Lazy<>(this::computeMetrics, computeLock); - private final Lazy> mdObject = new Lazy<>(this::computeMdObject, computeLock); public DocumentContext(URI uri, String content, ServerContext context) { this.uri = Absolute.uri(uri); @@ -191,7 +190,7 @@ public Map getSupportVariants() { } public Optional getMdObject() { - return mdObject.getOrCompute(); + return Optional.ofNullable(getServerContext().getConfiguration().getModulesByURI().get(getUri())); } public void rebuild(String content) { @@ -336,8 +335,4 @@ private DiagnosticIgnoranceComputer.Data computeDiagnosticIgnorance() { return diagnosticIgnoranceComputer.compute(); } - private Optional computeMdObject() { - return Optional.ofNullable(context.getConfiguration().getModulesByURI().get(getUri())); - } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java index 9e79aad28a1..36a48f3f7fa 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java @@ -1,18 +1,16 @@ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; -import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.mdclasses.mdo.CommonModule; -import com.github._1c_syntax.mdclasses.mdo.MDObjectBase; import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; -import org.antlr.v4.runtime.tree.ParseTree; -import java.util.Optional; +import java.util.regex.Pattern; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, @@ -27,30 +25,31 @@ } ) -public class CommonModuleNameClientServerDiagnostic extends AbstractVisitorDiagnostic { +public class CommonModuleNameClientServerDiagnostic extends AbstractDiagnostic { + + private static final Pattern pattern = Pattern.compile( + "(КлиентСервер$|ClientServer$)", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE + ); + public CommonModuleNameClientServerDiagnostic(DiagnosticInfo info) { super(info); } @Override - public ParseTree visitFile(BSLParser.FileContext ctx) { - - Optional commonModuleOptional = documentContext.getMdObject(); + protected void check(DocumentContext documentContext) { - if (commonModuleOptional.isEmpty() - || !(commonModuleOptional.get() instanceof CommonModule)) { - return super.visitFile(ctx); + if (documentContext.getTokens().isEmpty()) { + return; } - CommonModule commonModule = (CommonModule) commonModuleOptional.get(); - - if (commonModule.isServer() - && commonModule.isClientManagedApplication() - && !commonModule.getName().endsWith("КлиентСервер")) { - diagnosticStorage.addDiagnostic(ctx.getStart()); - } + documentContext.getMdObject() + .map(CommonModule.class::cast) + .filter(CommonModule::isServer) + .filter(CommonModule::isClientManagedApplication) + .filter(commonModule -> !pattern.matcher(commonModule.getName()).matches()) + .ifPresent(commonModule -> diagnosticStorage.addDiagnostic(documentContext.getTokens().get(0))); - return super.visitFile(ctx); } } From 5dbb27ed493451025f63e556e15525ebc7509a0b Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sat, 18 Apr 2020 17:07:11 +0300 Subject: [PATCH 163/444] =?UTF-8?q?test=20=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=BD=D0=B5=D0=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...nModuleNameClientServerDiagnosticTest.java | 106 ++++++++++++++---- 1 file changed, 87 insertions(+), 19 deletions(-) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java index 9cef18a961b..c9d09a05922 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java @@ -13,12 +13,16 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; +import java.util.Optional; import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; class CommonModuleNameClientServerDiagnosticTest extends AbstractDiagnosticTest { + private CommonModule module; + private DocumentContext documentContext; + CommonModuleNameClientServerDiagnosticTest() { super(CommonModuleNameClientServerDiagnostic.class); } @@ -27,40 +31,104 @@ class CommonModuleNameClientServerDiagnosticTest extends AbstractDiagnosticTest< private static final String PATH_TO_MODULE_FILE = "src/test/resources/metadata/CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; - @SneakyThrows @Test void test() { - Path path = Absolute.path(PATH_TO_METADATA); - var serverContext = spy(new ServerContext(path)); - var configuration = spy(serverContext.getConfiguration()); - when(serverContext.getConfiguration()).thenReturn(configuration); + getDocumentContextFromFile(); - Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + // given + when(module.getName()).thenReturn("ЧтоТо"); + when(module.isServer()).thenReturn(Boolean.TRUE); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); - var documentContext = spy(new DocumentContext( - testFile.toUri(), - FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), - serverContext - )); - when(documentContext.getServerContext()).thenReturn(serverContext); + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); - var modules = spy(configuration.getModulesByURI()); - when(configuration.getModulesByURI()).thenReturn(modules); + //then + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(0, 0, 0, 1); - var module = spy((CommonModule) modules.get(documentContext.getUri())); + } + @Test + void testNegative() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТоКлиентСервер"); when(module.isServer()).thenReturn(Boolean.TRUE); when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); - when(modules.get(documentContext.getUri())).thenReturn(module); + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + // when List diagnostics = diagnosticInstance.getDiagnostics(documentContext); - assertThat(diagnostics).hasSize(1); - assertThat(diagnostics, true) - .hasRange(0, 0, 0, 1); + + //then + assertThat(diagnostics).hasSize(0); } + @Test + void testFalse() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТоКлиентСервер"); + when(module.isServer()).thenReturn(Boolean.FALSE); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @Test + void testFalse2() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТо"); + when(module.isServer()).thenReturn(Boolean.FALSE); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @SneakyThrows + void getDocumentContextFromFile() { + + Path path = Absolute.path(PATH_TO_METADATA); + Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + + ServerContext serverContext = new ServerContext(path); + var configuration = serverContext.getConfiguration(); + documentContext = spy(new DocumentContext( + testFile.toUri(), + FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), + serverContext + )); + + + module = spy((CommonModule) configuration.getModulesByURI().get(documentContext.getUri())); + + } } From 0a250d97a58923c1b7bf2f41759e15a70d7ef2a8 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sat, 18 Apr 2020 17:07:59 +0300 Subject: [PATCH 164/444] =?UTF-8?q?=D1=80=D0=B5=D1=81=D1=83=D1=80=D1=81?= =?UTF-8?q?=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CommonModuleNameClientServerDiagnostic_en.properties | 4 ++-- .../CommonModuleNameClientServerDiagnostic_ru.properties | 4 ++-- .../diagnostics/CommonModuleNameClientServerDiagnostic.bsl | 1 + 3 files changed, 5 insertions(+), 4 deletions(-) create mode 100644 src/test/resources/diagnostics/CommonModuleNameClientServerDiagnostic.bsl diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic_en.properties index 66831715dfd..9a99c2b6d43 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic_en.properties @@ -1,2 +1,2 @@ -diagnosticMessage= -diagnosticName= +diagnosticMessage=Add postfix "ClientServer" to the common module name +diagnosticName=Missed postfix "ClientServer" diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic_ru.properties index 40188ca542c..22ffdcb4b4e 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic_ru.properties @@ -1,2 +1,2 @@ -diagnosticMessage=<Сообщение> -diagnosticName=<Имя диагностики> +diagnosticMessage=Добавьте постфикс "КлиентСервер" к имени общего модуля +diagnosticName=Пропущен постфикс "КлиентСервер" diff --git a/src/test/resources/diagnostics/CommonModuleNameClientServerDiagnostic.bsl b/src/test/resources/diagnostics/CommonModuleNameClientServerDiagnostic.bsl new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/src/test/resources/diagnostics/CommonModuleNameClientServerDiagnostic.bsl @@ -0,0 +1 @@ + From 2a6cbe2ba211c5ec97ad9b8278817aa16c01766e Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sat, 18 Apr 2020 17:08:11 +0300 Subject: [PATCH 165/444] =?UTF-8?q?=D0=B4=D0=BE=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/CommonModuleNameClientServer.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/docs/diagnostics/CommonModuleNameClientServer.md b/docs/diagnostics/CommonModuleNameClientServer.md index 6fcb1ecdbe5..c1b48a96ecc 100644 --- a/docs/diagnostics/CommonModuleNameClientServer.md +++ b/docs/diagnostics/CommonModuleNameClientServer.md @@ -8,6 +8,17 @@ ## Описание диагностики +Для того чтобы избежать дублирования кода, рекомендуется создавать клиент-серверные общие модули с теми процедурами и функциями, содержание которых одинаково на сервере и на клиенте. Такие процедуры и функции размещаются в общих модулях с признаками: + +* Клиент (управляемое приложение) +* Сервер (флажок Вызов сервера сброшен) +* Клиент (обычное приложение) +* Внешнее соединение + +Общие модули этого вида именуются с постфиксом "КлиентСервер" (англ. "ClientServer"). + +Например: РаботаСФайламиКлиентСервер, ОбщегоНазначенияКлиентСервер, UsersClientServer + ## Примеры @@ -19,6 +30,8 @@ * Полезная информаця: [Отказ от использования модальных окон](https://its.1c.ru/db/metod8dev#content:5272:hdoc) * Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) --> +[Правила создания общих модулей](https://its.1c.ru/db/v8std#content:469:hdoc:2.4) + ## Сниппеты From a13d9285cc499acd096dca8b80e0fb66916fc625 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sat, 18 Apr 2020 17:10:30 +0300 Subject: [PATCH 166/444] license add --- ...ommonModuleNameClientServerDiagnostic.java | 21 +++++++++++++++++++ ...nModuleNameClientServerDiagnosticTest.java | 21 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java index 36a48f3f7fa..3a65eed696d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java @@ -1,3 +1,24 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java index c9d09a05922..46192b744cb 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java @@ -1,3 +1,24 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; From 3b70c1b93f8492605e3b5557683639a303bc0afe Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sat, 18 Apr 2020 17:57:18 +0300 Subject: [PATCH 167/444] =?UTF-8?q?=D0=A0=D0=B5=D0=B3=D1=83=D0=BB=D1=8F?= =?UTF-8?q?=D1=80=D0=BA=D0=B0=20=D0=B8=20=D1=82=D0=B5=D0=B3=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CommonModuleNameClientServerDiagnostic.java | 8 +++++--- .../CommonModuleNameClientServerDiagnosticTest.java | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java index 3a65eed696d..45a0d6e6c23 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java @@ -35,21 +35,23 @@ @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, - severity = DiagnosticSeverity.INFO, + severity = DiagnosticSeverity.MAJOR, scope = DiagnosticScope.BSL, modules = { ModuleType.CommonModule }, minutesToFix = 2, tags = { - DiagnosticTag.STANDARD + DiagnosticTag.BADPRACTICE, + DiagnosticTag.STANDARD, + DiagnosticTag.UNPREDICTABLE } ) public class CommonModuleNameClientServerDiagnostic extends AbstractDiagnostic { private static final Pattern pattern = Pattern.compile( - "(КлиентСервер$|ClientServer$)", + "^.*клиентсервер|^.*clientserver", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE ); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java index 46192b744cb..65b8d5f2cb0 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java @@ -80,7 +80,7 @@ void testNegative() { getDocumentContextFromFile(); // given - when(module.getName()).thenReturn("ЧтоТоКлиентСервер"); + when(module.getName()).thenReturn("ЧтоТоclientserver"); when(module.isServer()).thenReturn(Boolean.TRUE); when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); From 2aea4e10a00633623c0769218d1b6ba28600e0e8 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sat, 18 Apr 2020 18:22:23 +0300 Subject: [PATCH 168/444] precommit --- .../CommonModuleNameClientServer.md | 18 +++++++++--------- .../CommonModuleNameClientServer.md | 16 ++++++++-------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/docs/diagnostics/CommonModuleNameClientServer.md b/docs/diagnostics/CommonModuleNameClientServer.md index c1b48a96ecc..577cb955648 100644 --- a/docs/diagnostics/CommonModuleNameClientServer.md +++ b/docs/diagnostics/CommonModuleNameClientServer.md @@ -1,8 +1,8 @@ -# () +# Пропущен постфикс "КлиентСервер" (CommonModuleNameClientServer) - - -## +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Дефект кода` | `BSL` | `Важный` | `Да` | `2` | `badpractice`
`standard`
`unpredictable` | ## Описание диагностики @@ -33,17 +33,17 @@ [Правила создания общих модулей](https://its.1c.ru/db/v8std#content:469:hdoc:2.4) ## Сниппеты - + ### Экранирование кода ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:CommonModuleNameClientServer-off +// BSLLS:CommonModuleNameClientServer-on ``` ### Параметр конфигурационного файла ```json -"": -``` \ No newline at end of file +"CommonModuleNameClientServer": false +``` diff --git a/docs/en/diagnostics/CommonModuleNameClientServer.md b/docs/en/diagnostics/CommonModuleNameClientServer.md index 4e7e0f78ada..df3a228f51d 100644 --- a/docs/en/diagnostics/CommonModuleNameClientServer.md +++ b/docs/en/diagnostics/CommonModuleNameClientServer.md @@ -1,8 +1,8 @@ -# +# Missed postfix "ClientServer" (CommonModuleNameClientServer) - - -## +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Code smell` | `BSL` | `Major` | `Yes` | `2` | `badpractice`
`standard`
`unpredictable` | ## Description @@ -20,17 +20,17 @@ * Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) --> ## Snippets - + ### Diagnostic ignorance in code ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:CommonModuleNameClientServer-off +// BSLLS:CommonModuleNameClientServer-on ``` ### Parameter for config ```json -"": +"CommonModuleNameClientServer": false ``` From cc0b0ec7e9963417e0de286981ecbd0ebb83bf4f Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sat, 18 Apr 2020 19:43:47 +0300 Subject: [PATCH 169/444] CommonModuleNameServerCallDiagnostic --- .../diagnostics/CommonModuleNameServerCall.md | 36 +++++++ .../diagnostics/CommonModuleNameServerCall.md | 36 +++++++ .../CommonModuleNameServerCallDiagnostic.java | 48 ++++++++++ ...duleNameServerCallDiagnostic_en.properties | 2 + ...duleNameServerCallDiagnostic_ru.properties | 2 + ...monModuleNameServerCallDiagnosticTest.java | 96 +++++++++++++++++++ .../CommonModuleNameServerCallDiagnostic.bsl | 1 + 7 files changed, 221 insertions(+) create mode 100644 docs/diagnostics/CommonModuleNameServerCall.md create mode 100644 docs/en/diagnostics/CommonModuleNameServerCall.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/CommonModuleNameServerCallDiagnostic.bsl diff --git a/docs/diagnostics/CommonModuleNameServerCall.md b/docs/diagnostics/CommonModuleNameServerCall.md new file mode 100644 index 00000000000..6fcb1ecdbe5 --- /dev/null +++ b/docs/diagnostics/CommonModuleNameServerCall.md @@ -0,0 +1,36 @@ +# () + + + +## + + +## Описание диагностики + + +## Примеры + + +## Источники + + + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Параметр конфигурационного файла + +```json +"": +``` \ No newline at end of file diff --git a/docs/en/diagnostics/CommonModuleNameServerCall.md b/docs/en/diagnostics/CommonModuleNameServerCall.md new file mode 100644 index 00000000000..4e7e0f78ada --- /dev/null +++ b/docs/en/diagnostics/CommonModuleNameServerCall.md @@ -0,0 +1,36 @@ +# + + + +## + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Parameter for config + +```json +"": +``` diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java new file mode 100644 index 00000000000..32c8ab65a60 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java @@ -0,0 +1,48 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; + +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.INFO, + minutesToFix = 1, + tags = { + DiagnosticTag.STANDARD + } + +) +public class CommonModuleNameServerCallDiagnostic extends AbstractDiagnostic { + public CommonModuleNameServerCallDiagnostic(DiagnosticInfo info) { + super(info); + } + + private static final Pattern pattern = Pattern.compile( + "^.*вызовсервера|^.*servercall", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE + ); + + @Override + protected void check(DocumentContext documentContext) { + + if (documentContext.getTokens().isEmpty()) { + return; + } + + documentContext.getMdObject() + .map(CommonModule.class::cast) + .filter(CommonModule::isServer) + .filter(CommonModule::isServerCall) + .filter(commonModule -> !pattern.matcher(commonModule.getName()).matches()) + .ifPresent(commonModule -> diagnosticStorage.addDiagnostic(documentContext.getTokens().get(0))); + + } + +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic_en.properties new file mode 100644 index 00000000000..66831715dfd --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage= +diagnosticName= diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic_ru.properties new file mode 100644 index 00000000000..40188ca542c --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=<Сообщение> +diagnosticName=<Имя диагностики> diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java new file mode 100644 index 00000000000..5c07263d826 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java @@ -0,0 +1,96 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.ServerContext; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.utils.Absolute; +import lombok.SneakyThrows; +import org.apache.commons.io.FileUtils; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Optional; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +class CommonModuleNameServerCallDiagnosticTest extends AbstractDiagnosticTest { + + private CommonModule module; + private DocumentContext documentContext; + + CommonModuleNameServerCallDiagnosticTest() { + super(CommonModuleNameServerCallDiagnostic.class); + } + + private static final String PATH_TO_METADATA = "src/test/resources/metadata"; + private static final String PATH_TO_MODULE_FILE = "src/test/resources/metadata/CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; + + @Test + void test() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТо"); + when(module.isServer()).thenReturn(Boolean.TRUE); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + when(module.isServerCall()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(0, 0, 0, 1); + + } + + @Test + void TestNegative() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТоВызовСервера"); + when(module.isServer()).thenReturn(Boolean.TRUE); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + when(module.isServerCall()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @SneakyThrows + void getDocumentContextFromFile() { + + Path path = Absolute.path(PATH_TO_METADATA); + Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + + ServerContext serverContext = new ServerContext(path); + var configuration = serverContext.getConfiguration(); + documentContext = spy(new DocumentContext( + testFile.toUri(), + FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), + serverContext + )); + + + module = spy((CommonModule) configuration.getModulesByURI().get(documentContext.getUri())); + + } +} diff --git a/src/test/resources/diagnostics/CommonModuleNameServerCallDiagnostic.bsl b/src/test/resources/diagnostics/CommonModuleNameServerCallDiagnostic.bsl new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/src/test/resources/diagnostics/CommonModuleNameServerCallDiagnostic.bsl @@ -0,0 +1 @@ + From 5ca7c57febb10902da5d6e26da14aa286a620536 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sat, 18 Apr 2020 22:13:32 +0300 Subject: [PATCH 170/444] abstract common module --- .../AbstractCommonModuleNameDiagnostic.java | 32 ++++++++++++ ...ommonModuleNameClientServerDiagnostic.java | 27 +++------- .../CommonModuleNameServerCallDiagnostic.java | 51 +++++++++++-------- 3 files changed, 69 insertions(+), 41 deletions(-) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java new file mode 100644 index 00000000000..d4d417f58ac --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java @@ -0,0 +1,32 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; + +import java.util.regex.Pattern; + +abstract class AbstractCommonModuleNameDiagnostic extends AbstractDiagnostic { + + Pattern pattern; + + public AbstractCommonModuleNameDiagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + protected void check(DocumentContext documentContext) { + if (documentContext.getTokens().isEmpty()) { + return; + } + + documentContext.getMdObject() + .map(CommonModule.class::cast) + .filter(this::flagsCheck) + .filter(commonModule -> !pattern.matcher(commonModule.getName()).matches()) + .ifPresent(commonModule -> diagnosticStorage.addDiagnostic(documentContext.getTokens().get(0))); + } + + protected abstract boolean flagsCheck(CommonModule commonModule); + +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java index 45a0d6e6c23..7f400be95f6 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java @@ -21,7 +21,6 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; @@ -48,31 +47,19 @@ } ) -public class CommonModuleNameClientServerDiagnostic extends AbstractDiagnostic { +public class CommonModuleNameClientServerDiagnostic extends AbstractCommonModuleNameDiagnostic { - private static final Pattern pattern = Pattern.compile( - "^.*клиентсервер|^.*clientserver", - Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE - ); public CommonModuleNameClientServerDiagnostic(DiagnosticInfo info) { super(info); + pattern = Pattern.compile( + "^.*клиентсервер|^.*clientserver", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE + ); } @Override - protected void check(DocumentContext documentContext) { - - if (documentContext.getTokens().isEmpty()) { - return; - } - - documentContext.getMdObject() - .map(CommonModule.class::cast) - .filter(CommonModule::isServer) - .filter(CommonModule::isClientManagedApplication) - .filter(commonModule -> !pattern.matcher(commonModule.getName()).matches()) - .ifPresent(commonModule -> diagnosticStorage.addDiagnostic(documentContext.getTokens().get(0))); - + protected boolean flagsCheck(CommonModule commonModule) { + return commonModule.isServer() && commonModule.isClientManagedApplication(); } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java index 32c8ab65a60..38b5da120bd 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java @@ -1,6 +1,26 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; @@ -19,30 +39,19 @@ } ) -public class CommonModuleNameServerCallDiagnostic extends AbstractDiagnostic { +public class CommonModuleNameServerCallDiagnostic extends AbstractCommonModuleNameDiagnostic { + public CommonModuleNameServerCallDiagnostic(DiagnosticInfo info) { super(info); - } - private static final Pattern pattern = Pattern.compile( - "^.*вызовсервера|^.*servercall", - Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE - ); + pattern = Pattern.compile( + "^.*вызовсервера|^.*servercall", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE + ); + } @Override - protected void check(DocumentContext documentContext) { - - if (documentContext.getTokens().isEmpty()) { - return; - } - - documentContext.getMdObject() - .map(CommonModule.class::cast) - .filter(CommonModule::isServer) - .filter(CommonModule::isServerCall) - .filter(commonModule -> !pattern.matcher(commonModule.getName()).matches()) - .ifPresent(commonModule -> diagnosticStorage.addDiagnostic(documentContext.getTokens().get(0))); - + protected boolean flagsCheck(CommonModule commonModule) { + return commonModule.isServer() && commonModule.isServerCall(); } - } From 5279aaf1db75a7b4e2d6c42c4fe3b71f32d589aa Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sat, 18 Apr 2020 22:14:10 +0300 Subject: [PATCH 171/444] precommit --- .../diagnostics/CommonModuleNameServerCall.md | 18 ++++++++-------- .../diagnostics/CommonModuleNameServerCall.md | 16 +++++++------- .../configuration/parameters-schema.json | 10 +++++++++ .../languageserver/configuration/schema.json | 3 +++ ...duleNameServerCallDiagnostic_en.properties | 4 ++-- ...duleNameServerCallDiagnostic_ru.properties | 4 ++-- ...monModuleNameServerCallDiagnosticTest.java | 21 +++++++++++++++++++ 7 files changed, 55 insertions(+), 21 deletions(-) diff --git a/docs/diagnostics/CommonModuleNameServerCall.md b/docs/diagnostics/CommonModuleNameServerCall.md index 6fcb1ecdbe5..cee74ccebff 100644 --- a/docs/diagnostics/CommonModuleNameServerCall.md +++ b/docs/diagnostics/CommonModuleNameServerCall.md @@ -1,8 +1,8 @@ -# () +# Пропущен постфикс "ВызовСервера" (CommonModuleNameServerCall) - - -## +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Дефект кода` | `BSL`
`OS` | `Информационный` | `Да` | `1` | `standard` | ## Описание диагностики @@ -20,17 +20,17 @@ * Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) --> ## Сниппеты - + ### Экранирование кода ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:CommonModuleNameServerCall-off +// BSLLS:CommonModuleNameServerCall-on ``` ### Параметр конфигурационного файла ```json -"": -``` \ No newline at end of file +"CommonModuleNameServerCall": false +``` diff --git a/docs/en/diagnostics/CommonModuleNameServerCall.md b/docs/en/diagnostics/CommonModuleNameServerCall.md index 4e7e0f78ada..c0cdb13e6cd 100644 --- a/docs/en/diagnostics/CommonModuleNameServerCall.md +++ b/docs/en/diagnostics/CommonModuleNameServerCall.md @@ -1,8 +1,8 @@ -# +# Missed postfix "ServerCall" (CommonModuleNameServerCall) - - -## +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Code smell` | `BSL`
`OS` | `Info` | `Yes` | `1` | `standard` | ## Description @@ -20,17 +20,17 @@ * Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) --> ## Snippets - + ### Diagnostic ignorance in code ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:CommonModuleNameServerCall-off +// BSLLS:CommonModuleNameServerCall-on ``` ### Parameter for config ```json -"": +"CommonModuleNameServerCall": false ``` diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index a6dcbbd3085..ddbe4995680 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -106,6 +106,16 @@ "title": "CommonModuleAssign", "$id": "#/definitions/CommonModuleAssign" }, + "CommonModuleNameServerCall": { + "description": "Missed postfix \"ServerCall\"", + "default": null, + "type": [ + "boolean", + "object" + ], + "title": "Missed postfix \"ServerCall\"", + "$id": "#/definitions/CommonModuleNameServerCall" + }, "CompilationDirectiveLost": { "description": "Methods compilation directive", "default": true, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 20141ed863e..17587c88bec 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -47,6 +47,9 @@ "CommonModuleAssign": { "$ref": "parameters-schema.json#/definitions/CommonModuleAssign" }, + "CommonModuleNameServerCall": { + "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameServerCall" + }, "CompilationDirectiveLost": { "$ref": "parameters-schema.json#/definitions/CompilationDirectiveLost" }, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic_en.properties index 66831715dfd..d50bed3faf4 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic_en.properties @@ -1,2 +1,2 @@ -diagnosticMessage= -diagnosticName= +diagnosticMessage=Add postfix "ServerCall" to the common module name +diagnosticName=Missed postfix "ServerCall" diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic_ru.properties index 40188ca542c..102dccde8d9 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic_ru.properties @@ -1,2 +1,2 @@ -diagnosticMessage=<Сообщение> -diagnosticName=<Имя диагностики> +diagnosticMessage=Добавьте постфикс "ВызовСервера" к имени общего модуля +diagnosticName=Пропущен постфикс "ВызовСервера" diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java index 5c07263d826..72d87133481 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java @@ -1,3 +1,24 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; From 1346289815e0f7760ff8bce1cee225ed58f25938 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sat, 18 Apr 2020 22:44:47 +0300 Subject: [PATCH 172/444] CommonModuleNameClientDiagnstic --- docs/diagnostics/CommonModuleNameClient.md | 36 +++++ docs/en/diagnostics/CommonModuleNameClient.md | 36 +++++ .../AbstractCommonModuleNameDiagnostic.java | 21 +++ .../CommonModuleNameClientDiagnostic.java | 60 ++++++++ ...onModuleNameClientDiagnostic_en.properties | 2 + ...onModuleNameClientDiagnostic_ru.properties | 2 + .../CommonModuleNameClientDiagnosticTest.java | 138 ++++++++++++++++++ .../CommonModuleNameClientDiagnostic.bsl | 1 + 8 files changed, 296 insertions(+) create mode 100644 docs/diagnostics/CommonModuleNameClient.md create mode 100644 docs/en/diagnostics/CommonModuleNameClient.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/CommonModuleNameClientDiagnostic.bsl diff --git a/docs/diagnostics/CommonModuleNameClient.md b/docs/diagnostics/CommonModuleNameClient.md new file mode 100644 index 00000000000..950369d208c --- /dev/null +++ b/docs/diagnostics/CommonModuleNameClient.md @@ -0,0 +1,36 @@ +# Пропущен постфикс "Клиент" (CommonModuleNameClient) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Дефект кода` | `BSL`
`OS` | `Информационный` | `Да` | `1` | `standard` | + + +## Описание диагностики + + +## Примеры + + +## Источники + + + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:CommonModuleNameClient-off +// BSLLS:CommonModuleNameClient-on +``` + +### Параметр конфигурационного файла + +```json +"CommonModuleNameClient": false +``` diff --git a/docs/en/diagnostics/CommonModuleNameClient.md b/docs/en/diagnostics/CommonModuleNameClient.md new file mode 100644 index 00000000000..8f06688fabc --- /dev/null +++ b/docs/en/diagnostics/CommonModuleNameClient.md @@ -0,0 +1,36 @@ +# Missed postfix "Client" (CommonModuleNameClient) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Code smell` | `BSL`
`OS` | `Info` | `Yes` | `1` | `standard` | + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:CommonModuleNameClient-off +// BSLLS:CommonModuleNameClient-on +``` + +### Parameter for config + +```json +"CommonModuleNameClient": false +``` diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java index d4d417f58ac..4b0b7ec5b84 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java @@ -1,3 +1,24 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java new file mode 100644 index 00000000000..320a1d39479 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java @@ -0,0 +1,60 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; + +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.INFO, + minutesToFix = 1, + tags = { + DiagnosticTag.STANDARD + } + +) +public class CommonModuleNameClientDiagnostic extends AbstractCommonModuleNameDiagnostic { + public CommonModuleNameClientDiagnostic(DiagnosticInfo info) { + super(info); + pattern = Pattern.compile( + "^.*клиент|^.*client", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE + ); + + } + + @Override + protected boolean flagsCheck(CommonModule commonModule) { + return !commonModule.isGlobal() + && commonModule.isClientManagedApplication() + && !commonModule.isServerCall(); + } + + +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic_en.properties new file mode 100644 index 00000000000..7055f617b87 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Add postfix "Client" to the common module name +diagnosticName=Missed postfix "Client" diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic_ru.properties new file mode 100644 index 00000000000..6a3923a4774 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Добавьте постфикс "Клиент" к имени общего модуля +diagnosticName=Пропущен постфикс "Клиент" diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java new file mode 100644 index 00000000000..c17a1e3bdca --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java @@ -0,0 +1,138 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.ServerContext; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.utils.Absolute; +import lombok.SneakyThrows; +import org.apache.commons.io.FileUtils; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Optional; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +class CommonModuleNameClientDiagnosticTest extends AbstractDiagnosticTest { + private DocumentContext documentContext; + private CommonModule module; + + CommonModuleNameClientDiagnosticTest() { + super(CommonModuleNameClientDiagnostic.class); + } + + private static final String PATH_TO_METADATA = "src/test/resources/metadata"; + private static final String PATH_TO_MODULE_FILE = "src/test/resources/metadata/CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; + + + @Test + void test() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТо"); + when(module.isServer()).thenReturn(Boolean.FALSE); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(0, 0, 0, 1); + + } + + @Test + void testNegative() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТоclient"); + when(module.isServer()).thenReturn(Boolean.FALSE); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @Test + void testGlobal() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТоГлобальный"); + when(module.isServer()).thenReturn(Boolean.FALSE); + when(module.isGlobal()).thenReturn(Boolean.TRUE); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + + @SneakyThrows + void getDocumentContextFromFile() { + + Path path = Absolute.path(PATH_TO_METADATA); + Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + + ServerContext serverContext = new ServerContext(path); + var configuration = serverContext.getConfiguration(); + documentContext = spy(new DocumentContext( + testFile.toUri(), + FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), + serverContext + )); + + + module = spy((CommonModule) configuration.getModulesByURI().get(documentContext.getUri())); + + } + +} diff --git a/src/test/resources/diagnostics/CommonModuleNameClientDiagnostic.bsl b/src/test/resources/diagnostics/CommonModuleNameClientDiagnostic.bsl new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/src/test/resources/diagnostics/CommonModuleNameClientDiagnostic.bsl @@ -0,0 +1 @@ + From 1f3c710db7215babeaa58ae59ca6ca4598637199 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sat, 18 Apr 2020 22:57:46 +0300 Subject: [PATCH 173/444] CommonModuleNameGlobalDiagnostic --- docs/diagnostics/CommonModuleNameGlobal.md | 36 +++++ docs/en/diagnostics/CommonModuleNameGlobal.md | 36 +++++ .../CommonModuleNameGlobalDiagnostic.java | 55 ++++++++ .../configuration/parameters-schema.json | 10 ++ .../languageserver/configuration/schema.json | 3 + ...onModuleNameGlobalDiagnostic_en.properties | 2 + ...onModuleNameGlobalDiagnostic_ru.properties | 2 + .../CommonModuleNameGlobalDiagnosticTest.java | 132 ++++++++++++++++++ .../CommonModuleNameGlobalDiagnostic.bsl | 1 + 9 files changed, 277 insertions(+) create mode 100644 docs/diagnostics/CommonModuleNameGlobal.md create mode 100644 docs/en/diagnostics/CommonModuleNameGlobal.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/CommonModuleNameGlobalDiagnostic.bsl diff --git a/docs/diagnostics/CommonModuleNameGlobal.md b/docs/diagnostics/CommonModuleNameGlobal.md new file mode 100644 index 00000000000..0905c595bb0 --- /dev/null +++ b/docs/diagnostics/CommonModuleNameGlobal.md @@ -0,0 +1,36 @@ +# Пропущен постфикс "Глобальный" (CommonModuleNameGlobal) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Дефект кода` | `BSL`
`OS` | `Информационный` | `Да` | `2` | `standard` | + + +## Описание диагностики + + +## Примеры + + +## Источники + + + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:CommonModuleNameGlobal-off +// BSLLS:CommonModuleNameGlobal-on +``` + +### Параметр конфигурационного файла + +```json +"CommonModuleNameGlobal": false +``` diff --git a/docs/en/diagnostics/CommonModuleNameGlobal.md b/docs/en/diagnostics/CommonModuleNameGlobal.md new file mode 100644 index 00000000000..b79370c1ce8 --- /dev/null +++ b/docs/en/diagnostics/CommonModuleNameGlobal.md @@ -0,0 +1,36 @@ +# Missed postfix "Global" (CommonModuleNameGlobal) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Code smell` | `BSL`
`OS` | `Info` | `Yes` | `2` | `standard` | + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:CommonModuleNameGlobal-off +// BSLLS:CommonModuleNameGlobal-on +``` + +### Parameter for config + +```json +"CommonModuleNameGlobal": false +``` diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java new file mode 100644 index 00000000000..cb87ee74516 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java @@ -0,0 +1,55 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; + +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.INFO, + minutesToFix = 2, + tags = { + DiagnosticTag.STANDARD + } + +) +public class CommonModuleNameGlobalDiagnostic extends AbstractCommonModuleNameDiagnostic { + public CommonModuleNameGlobalDiagnostic(DiagnosticInfo info) { + super(info); + pattern = Pattern.compile( + "^.*глобальный|^.*global", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE + ); + } + + @Override + protected boolean flagsCheck(CommonModule commonModule) { + return commonModule.isGlobal(); + } +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index ddbe4995680..5bb900e5260 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -106,6 +106,16 @@ "title": "CommonModuleAssign", "$id": "#/definitions/CommonModuleAssign" }, + "CommonModuleNameGlobal": { + "description": "Missed postfix \"Global\"", + "default": null, + "type": [ + "boolean", + "object" + ], + "title": "Missed postfix \"Global\"", + "$id": "#/definitions/CommonModuleNameGlobal" + }, "CommonModuleNameServerCall": { "description": "Missed postfix \"ServerCall\"", "default": null, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 17587c88bec..5b652c0c102 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -47,6 +47,9 @@ "CommonModuleAssign": { "$ref": "parameters-schema.json#/definitions/CommonModuleAssign" }, + "CommonModuleNameGlobal": { + "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameGlobal" + }, "CommonModuleNameServerCall": { "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameServerCall" }, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic_en.properties new file mode 100644 index 00000000000..d5523c2d58d --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Add postfix "Global" to the common module name +diagnosticName=Missed postfix "Global" diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic_ru.properties new file mode 100644 index 00000000000..d31f89caa8e --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Добавьте постфикс "Глобальный" к имени общего модуля +diagnosticName=Пропущен постфикс "Глобальный" diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnosticTest.java new file mode 100644 index 00000000000..43c3dcfdab7 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnosticTest.java @@ -0,0 +1,132 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.ServerContext; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.utils.Absolute; +import lombok.SneakyThrows; +import org.apache.commons.io.FileUtils; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Optional; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +class CommonModuleNameGlobalDiagnosticTest extends AbstractDiagnosticTest { + private DocumentContext documentContext; + private CommonModule module; + + CommonModuleNameGlobalDiagnosticTest() { + super(CommonModuleNameGlobalDiagnostic.class); + } + + private static final String PATH_TO_METADATA = "src/test/resources/metadata"; + private static final String PATH_TO_MODULE_FILE = "src/test/resources/metadata/CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; + + + @Test + void test() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТо"); + when(module.isGlobal()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(0, 0, 0, 1); + + } + + @Test + void testNegative() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТоglobal"); + when(module.isGlobal()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @Test + void testFalse() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТоКлиентСервер"); + when(module.isGlobal()).thenReturn(Boolean.FALSE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @SneakyThrows + void getDocumentContextFromFile() { + + Path path = Absolute.path(PATH_TO_METADATA); + Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + + ServerContext serverContext = new ServerContext(path); + var configuration = serverContext.getConfiguration(); + documentContext = spy(new DocumentContext( + testFile.toUri(), + FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), + serverContext + )); + + + module = spy((CommonModule) configuration.getModulesByURI().get(documentContext.getUri())); + + } +} diff --git a/src/test/resources/diagnostics/CommonModuleNameGlobalDiagnostic.bsl b/src/test/resources/diagnostics/CommonModuleNameGlobalDiagnostic.bsl new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/src/test/resources/diagnostics/CommonModuleNameGlobalDiagnostic.bsl @@ -0,0 +1 @@ + From f9fd96083924b6ff986fa82842009a730be89757 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sat, 18 Apr 2020 23:08:36 +0300 Subject: [PATCH 174/444] CommonModuleNameFullAccessDiagnostic --- .../diagnostics/CommonModuleNameFullAccess.md | 36 +++++ docs/diagnostics/index.md | 2 +- .../diagnostics/CommonModuleNameFullAccess.md | 36 +++++ .../CommonModuleNameFullAccessDiagnostic.java | 56 ++++++++ .../configuration/parameters-schema.json | 10 ++ .../languageserver/configuration/schema.json | 3 + ...duleNameFullAccessDiagnostic_en.properties | 2 + ...duleNameFullAccessDiagnostic_ru.properties | 2 + ...monModuleNameFullAccessDiagnosticTest.java | 133 ++++++++++++++++++ .../CommonModuleNameFullAccessDiagnostic.bsl | 1 + 10 files changed, 280 insertions(+), 1 deletion(-) create mode 100644 docs/diagnostics/CommonModuleNameFullAccess.md create mode 100644 docs/en/diagnostics/CommonModuleNameFullAccess.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/CommonModuleNameFullAccessDiagnostic.bsl diff --git a/docs/diagnostics/CommonModuleNameFullAccess.md b/docs/diagnostics/CommonModuleNameFullAccess.md new file mode 100644 index 00000000000..7c704e4417f --- /dev/null +++ b/docs/diagnostics/CommonModuleNameFullAccess.md @@ -0,0 +1,36 @@ +# Пропущен постфикс "ПолныеПрава" (CommonModuleNameFullAccess) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Дефект кода` | `BSL`
`OS` | `Информационный` | `Да` | `1` | `standard` | + + +## Описание диагностики + + +## Примеры + + +## Источники + + + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:CommonModuleNameFullAccess-off +// BSLLS:CommonModuleNameFullAccess-on +``` + +### Параметр конфигурационного файла + +```json +"CommonModuleNameFullAccess": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 784ac601b59..cb2ffb16ed1 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -10,7 +10,7 @@ Общее количество: **94** -* Дефект кода: **59** +* Дефект кода: **60** * Уязвимость: **2** * Ошибка: **31** * Потенциальная уязвимость: **2** diff --git a/docs/en/diagnostics/CommonModuleNameFullAccess.md b/docs/en/diagnostics/CommonModuleNameFullAccess.md new file mode 100644 index 00000000000..ca6cffcb8f0 --- /dev/null +++ b/docs/en/diagnostics/CommonModuleNameFullAccess.md @@ -0,0 +1,36 @@ +# Missed postfix "FullAccess" (CommonModuleNameFullAccess) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Code smell` | `BSL`
`OS` | `Info` | `Yes` | `1` | `standard` | + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:CommonModuleNameFullAccess-off +// BSLLS:CommonModuleNameFullAccess-on +``` + +### Parameter for config + +```json +"CommonModuleNameFullAccess": false +``` diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java new file mode 100644 index 00000000000..c433fee6e58 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java @@ -0,0 +1,56 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; + +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.INFO, + minutesToFix = 1, + tags = { + DiagnosticTag.STANDARD + } + +) +public class CommonModuleNameFullAccessDiagnostic extends AbstractCommonModuleNameDiagnostic { + public CommonModuleNameFullAccessDiagnostic(DiagnosticInfo info) { + super(info); + + pattern = Pattern.compile( + "^.*полныеправа|^.*fullaccess", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE + ); + } + + @Override + protected boolean flagsCheck(CommonModule commonModule) { + return commonModule.isPrivileged(); + } +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index 5bb900e5260..7705686ef53 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -106,6 +106,16 @@ "title": "CommonModuleAssign", "$id": "#/definitions/CommonModuleAssign" }, + "CommonModuleNameFullAccess": { + "description": "Missed postfix \"FullAccess\"", + "default": null, + "type": [ + "boolean", + "object" + ], + "title": "Missed postfix \"FullAccess\"", + "$id": "#/definitions/CommonModuleNameFullAccess" + }, "CommonModuleNameGlobal": { "description": "Missed postfix \"Global\"", "default": null, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 5b652c0c102..6da332fac34 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -47,6 +47,9 @@ "CommonModuleAssign": { "$ref": "parameters-schema.json#/definitions/CommonModuleAssign" }, + "CommonModuleNameFullAccess": { + "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameFullAccess" + }, "CommonModuleNameGlobal": { "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameGlobal" }, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic_en.properties new file mode 100644 index 00000000000..b47ed7c26b1 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Add postfix "FullAccess" to the common module name +diagnosticName=Missed postfix "FullAccess" diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic_ru.properties new file mode 100644 index 00000000000..fe09f0f76f7 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Добавьте постфикс "ПолныеПрава" к имени общего модуля +diagnosticName=Пропущен постфикс "ПолныеПрава" diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnosticTest.java new file mode 100644 index 00000000000..00702ba0fd5 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnosticTest.java @@ -0,0 +1,133 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.ServerContext; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.utils.Absolute; +import lombok.SneakyThrows; +import org.apache.commons.io.FileUtils; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Optional; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +class CommonModuleNameFullAccessDiagnosticTest extends AbstractDiagnosticTest { + private DocumentContext documentContext; + private CommonModule module; + + CommonModuleNameFullAccessDiagnosticTest() { + super(CommonModuleNameFullAccessDiagnostic.class); + } + + + private static final String PATH_TO_METADATA = "src/test/resources/metadata"; + private static final String PATH_TO_MODULE_FILE = "src/test/resources/metadata/CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; + + + @Test + void test() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТо"); + when(module.isPrivileged()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(0, 0, 0, 1); + + } + + @Test + void testNegative() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТоFullAccess"); + when(module.isPrivileged()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @Test + void testFalse() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТоКлиентСервер"); + when(module.isPrivileged()).thenReturn(Boolean.FALSE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @SneakyThrows + void getDocumentContextFromFile() { + + Path path = Absolute.path(PATH_TO_METADATA); + Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + + ServerContext serverContext = new ServerContext(path); + var configuration = serverContext.getConfiguration(); + documentContext = spy(new DocumentContext( + testFile.toUri(), + FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), + serverContext + )); + + + module = spy((CommonModule) configuration.getModulesByURI().get(documentContext.getUri())); + + } +} diff --git a/src/test/resources/diagnostics/CommonModuleNameFullAccessDiagnostic.bsl b/src/test/resources/diagnostics/CommonModuleNameFullAccessDiagnostic.bsl new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/src/test/resources/diagnostics/CommonModuleNameFullAccessDiagnostic.bsl @@ -0,0 +1 @@ + From 2958098074abd213efdc02f2bcc426db14a902a4 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sat, 18 Apr 2020 23:27:46 +0300 Subject: [PATCH 175/444] CommonModuleNameCashedDiagnostic --- docs/diagnostics/CommonModuleNameCached.md | 36 ++++++ docs/diagnostics/index.md | 2 +- docs/en/diagnostics/CommonModuleNameCached.md | 36 ++++++ .../CommonModuleNameCachedDiagnostic.java | 59 +++++++++ ...onModuleNameCachedDiagnostic_en.properties | 2 + ...onModuleNameCachedDiagnostic_ru.properties | 2 + .../CommonModuleNameCachedDiagnosticTest.java | 115 ++++++++++++++++++ .../CommonModuleNameCachedDiagnostic.bsl | 1 + 8 files changed, 252 insertions(+), 1 deletion(-) create mode 100644 docs/diagnostics/CommonModuleNameCached.md create mode 100644 docs/en/diagnostics/CommonModuleNameCached.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/CommonModuleNameCachedDiagnostic.bsl diff --git a/docs/diagnostics/CommonModuleNameCached.md b/docs/diagnostics/CommonModuleNameCached.md new file mode 100644 index 00000000000..2bbb3a06a74 --- /dev/null +++ b/docs/diagnostics/CommonModuleNameCached.md @@ -0,0 +1,36 @@ +# Пропущен постфикс "ПовтИсп" (CommonModuleNameCached) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Дефект кода` | `BSL`
`OS` | `Информационный` | `Да` | `1` | `standard` | + + +## Описание диагностики + + +## Примеры + + +## Источники + + + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:CommonModuleNameCached-off +// BSLLS:CommonModuleNameCached-on +``` + +### Параметр конфигурационного файла + +```json +"CommonModuleNameCached": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index cb2ffb16ed1..0a65db8f9a1 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -10,7 +10,7 @@ Общее количество: **94** -* Дефект кода: **60** +* Дефект кода: **61** * Уязвимость: **2** * Ошибка: **31** * Потенциальная уязвимость: **2** diff --git a/docs/en/diagnostics/CommonModuleNameCached.md b/docs/en/diagnostics/CommonModuleNameCached.md new file mode 100644 index 00000000000..b0eb59c7bed --- /dev/null +++ b/docs/en/diagnostics/CommonModuleNameCached.md @@ -0,0 +1,36 @@ +# Missed postfix "Cached" (CommonModuleNameCached) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Code smell` | `BSL`
`OS` | `Info` | `Yes` | `1` | `standard` | + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:CommonModuleNameCached-off +// BSLLS:CommonModuleNameCached-on +``` + +### Parameter for config + +```json +"CommonModuleNameCached": false +``` diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java new file mode 100644 index 00000000000..1b5b8d64d87 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java @@ -0,0 +1,59 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.mdclasses.metadata.additional.ReturnValueReuse; + +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.INFO, + minutesToFix = 1, + tags = { + DiagnosticTag.STANDARD + } + +) +public class CommonModuleNameCachedDiagnostic extends AbstractCommonModuleNameDiagnostic { + public CommonModuleNameCachedDiagnostic(DiagnosticInfo info) { + super(info); + pattern = Pattern.compile( + "^.*повтисп|^.*сached", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE + ); + + } + + @Override + protected boolean flagsCheck(CommonModule commonModule) { + return commonModule.getReturnValuesReuse() == ReturnValueReuse.DURING_REQUEST + || commonModule.getReturnValuesReuse() == ReturnValueReuse.DURING_SESSION; + } + +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic_en.properties new file mode 100644 index 00000000000..d8e489ec3b3 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Add postfix "Cached" to the common module name +diagnosticName=Missed postfix "Cached" diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic_ru.properties new file mode 100644 index 00000000000..312d3e4833e --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Добавьте постфикс "ПовтИсп" к имени общего модуля +diagnosticName=Пропущен постфикс "ПовтИсп" diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java new file mode 100644 index 00000000000..eee3b62e4f1 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java @@ -0,0 +1,115 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.ServerContext; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.mdclasses.metadata.additional.ReturnValueReuse; +import com.github._1c_syntax.utils.Absolute; +import lombok.SneakyThrows; +import org.apache.commons.io.FileUtils; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Optional; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +class CommonModuleNameCachedDiagnosticTest extends AbstractDiagnosticTest { + private CommonModule module; + private DocumentContext documentContext; + + CommonModuleNameCachedDiagnosticTest() { + super(CommonModuleNameCachedDiagnostic.class); + } + + private static final String PATH_TO_METADATA = "src/test/resources/metadata"; + private static final String PATH_TO_MODULE_FILE = "src/test/resources/metadata/CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; + + + @Test + void test() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТо"); + when(module.getReturnValuesReuse()).thenReturn(ReturnValueReuse.DURING_REQUEST); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(0, 0, 0, 1); + + } + + @Test + void testNegative() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТоПовтИсп"); + when(module.getReturnValuesReuse()).thenReturn(ReturnValueReuse.DURING_REQUEST); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @SneakyThrows + void getDocumentContextFromFile() { + + Path path = Absolute.path(PATH_TO_METADATA); + Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + + ServerContext serverContext = new ServerContext(path); + var configuration = serverContext.getConfiguration(); + documentContext = spy(new DocumentContext( + testFile.toUri(), + FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), + serverContext + )); + + + module = spy((CommonModule) configuration.getModulesByURI().get(documentContext.getUri())); + + } + +} diff --git a/src/test/resources/diagnostics/CommonModuleNameCachedDiagnostic.bsl b/src/test/resources/diagnostics/CommonModuleNameCachedDiagnostic.bsl new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/src/test/resources/diagnostics/CommonModuleNameCachedDiagnostic.bsl @@ -0,0 +1 @@ + From 85a0f9ba3148b0592c6f73d3bb726c78a34bfc46 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sun, 19 Apr 2020 00:06:50 +0300 Subject: [PATCH 176/444] CommonModuleGlobalClientDiagnostic --- .../CommonModuleNameGlobalClient.md | 36 +++++ .../CommonModuleNameGlobalClient.md | 36 +++++ ...ommonModuleNameGlobalClientDiagnostic.java | 55 +++++++ ...leNameGlobalClientDiagnostic_en.properties | 2 + ...leNameGlobalClientDiagnostic_ru.properties | 2 + ...nModuleNameGlobalClientDiagnosticTest.java | 134 ++++++++++++++++++ ...CommonModuleNameGlobalClientDiagnostic.bsl | 1 + 7 files changed, 266 insertions(+) create mode 100644 docs/diagnostics/CommonModuleNameGlobalClient.md create mode 100644 docs/en/diagnostics/CommonModuleNameGlobalClient.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/CommonModuleNameGlobalClientDiagnostic.bsl diff --git a/docs/diagnostics/CommonModuleNameGlobalClient.md b/docs/diagnostics/CommonModuleNameGlobalClient.md new file mode 100644 index 00000000000..6fcb1ecdbe5 --- /dev/null +++ b/docs/diagnostics/CommonModuleNameGlobalClient.md @@ -0,0 +1,36 @@ +# () + + + +## + + +## Описание диагностики + + +## Примеры + + +## Источники + + + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Параметр конфигурационного файла + +```json +"": +``` \ No newline at end of file diff --git a/docs/en/diagnostics/CommonModuleNameGlobalClient.md b/docs/en/diagnostics/CommonModuleNameGlobalClient.md new file mode 100644 index 00000000000..4e7e0f78ada --- /dev/null +++ b/docs/en/diagnostics/CommonModuleNameGlobalClient.md @@ -0,0 +1,36 @@ +# + + + +## + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Parameter for config + +```json +"": +``` diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java new file mode 100644 index 00000000000..750328d5013 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java @@ -0,0 +1,55 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; + +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.INFO, + minutesToFix = 1, + tags = { + DiagnosticTag.ERROR + } + +) +public class CommonModuleNameGlobalClientDiagnostic extends AbstractCommonModuleNameDiagnostic { + public CommonModuleNameGlobalClientDiagnostic(DiagnosticInfo info) { + super(info); + pattern = Pattern.compile( + "!?клиент|!?client", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE + ); + } + + @Override + protected boolean flagsCheck(CommonModule commonModule) { + return commonModule.isGlobal() && commonModule.isClientManagedApplication(); + } +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic_en.properties new file mode 100644 index 00000000000..2c9b9e3e1f0 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Remove postfix "Client" +diagnosticName=Global module with postfix "Client" diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic_ru.properties new file mode 100644 index 00000000000..314049182e2 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Удалите постфикс "Клиент" у глобального модуля +diagnosticName=Глобальный модуль с постфиксом "Клиент" diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java new file mode 100644 index 00000000000..4afd3b392ca --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java @@ -0,0 +1,134 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.ServerContext; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.utils.Absolute; +import lombok.SneakyThrows; +import org.apache.commons.io.FileUtils; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Optional; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +class CommonModuleNameGlobalClientDiagnosticTest extends AbstractDiagnosticTest { + private CommonModule module; + private DocumentContext documentContext; + + CommonModuleNameGlobalClientDiagnosticTest() { + super(CommonModuleNameGlobalClientDiagnostic.class); + } + + private static final String PATH_TO_METADATA = "src/test/resources/metadata"; + private static final String PATH_TO_MODULE_FILE = "src/test/resources/metadata/CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; + + + @Test + void test() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТоКлиентГлобальный"); + when(module.isGlobal()).thenReturn(Boolean.TRUE); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(0, 0, 0, 1); + + } + + @Test + void testNegative() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТоglobal"); + when(module.isGlobal()).thenReturn(Boolean.TRUE); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @Test + void testFalse() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТоКлиентГлобальный"); + when(module.isGlobal()).thenReturn(Boolean.FALSE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @SneakyThrows + void getDocumentContextFromFile() { + + Path path = Absolute.path(PATH_TO_METADATA); + Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + + ServerContext serverContext = new ServerContext(path); + var configuration = serverContext.getConfiguration(); + documentContext = spy(new DocumentContext( + testFile.toUri(), + FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), + serverContext + )); + + + module = spy((CommonModule) configuration.getModulesByURI().get(documentContext.getUri())); + + } +} diff --git a/src/test/resources/diagnostics/CommonModuleNameGlobalClientDiagnostic.bsl b/src/test/resources/diagnostics/CommonModuleNameGlobalClientDiagnostic.bsl new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/src/test/resources/diagnostics/CommonModuleNameGlobalClientDiagnostic.bsl @@ -0,0 +1 @@ + From a4c9866724e012ba3d510d806c1c4a6ae8000a0b Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sun, 19 Apr 2020 00:13:05 +0300 Subject: [PATCH 177/444] test empty file --- .../CommonModuleNameCachedDiagnosticTest.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java index eee3b62e4f1..16f5f29188a 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java @@ -93,6 +93,17 @@ void testNegative() { } + @Test + void testEmptyFile() { + + // when + List diagnostics = getDiagnostics(); + + //then + assertThat(diagnostics).hasSize(0); + + } + @SneakyThrows void getDocumentContextFromFile() { From d54c5a72df2c04a175ae1c19797d9353e2eb5a7e Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sun, 19 Apr 2020 00:30:28 +0300 Subject: [PATCH 178/444] regexp fix --- .../diagnostics/CommonModuleNameGlobalClientDiagnostic.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java index 750328d5013..8cd5f2cd3b0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java @@ -43,7 +43,7 @@ public class CommonModuleNameGlobalClientDiagnostic extends AbstractCommonModule public CommonModuleNameGlobalClientDiagnostic(DiagnosticInfo info) { super(info); pattern = Pattern.compile( - "!?клиент|!?client", + "^(?>(?!Клиент|client).)*$", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE ); } From 8427d107835a78f5cba724057c4685fd56262574 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sun, 19 Apr 2020 00:31:45 +0300 Subject: [PATCH 179/444] precommit --- .../CommonModuleNameGlobalClient.md | 18 +++++++++--------- docs/diagnostics/index.md | 4 ++-- .../CommonModuleNameGlobalClient.md | 16 ++++++++-------- docs/en/diagnostics/index.md | 2 +- .../configuration/parameters-schema.json | 10 ++++++++++ .../languageserver/configuration/schema.json | 3 +++ 6 files changed, 33 insertions(+), 20 deletions(-) diff --git a/docs/diagnostics/CommonModuleNameGlobalClient.md b/docs/diagnostics/CommonModuleNameGlobalClient.md index 6fcb1ecdbe5..d00e2263fca 100644 --- a/docs/diagnostics/CommonModuleNameGlobalClient.md +++ b/docs/diagnostics/CommonModuleNameGlobalClient.md @@ -1,8 +1,8 @@ -# () +# Глобальный модуль с постфиксом "Клиент" (CommonModuleNameGlobalClient) - - -## +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Дефект кода` | `BSL`
`OS` | `Информационный` | `Да` | `1` | `error` | ## Описание диагностики @@ -20,17 +20,17 @@ * Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) --> ## Сниппеты - + ### Экранирование кода ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:CommonModuleNameGlobalClient-off +// BSLLS:CommonModuleNameGlobalClient-on ``` ### Параметр конфигурационного файла ```json -"": -``` \ No newline at end of file +"CommonModuleNameGlobalClient": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 0a65db8f9a1..3d83ffd03c8 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,9 +8,9 @@ ## Список реализованных диагностик -Общее количество: **94** +Общее количество: **95** -* Дефект кода: **61** +* Дефект кода: **62** * Уязвимость: **2** * Ошибка: **31** * Потенциальная уязвимость: **2** diff --git a/docs/en/diagnostics/CommonModuleNameGlobalClient.md b/docs/en/diagnostics/CommonModuleNameGlobalClient.md index 4e7e0f78ada..f6d3069371c 100644 --- a/docs/en/diagnostics/CommonModuleNameGlobalClient.md +++ b/docs/en/diagnostics/CommonModuleNameGlobalClient.md @@ -1,8 +1,8 @@ -# +# Global module with postfix "Client" (CommonModuleNameGlobalClient) - - -## +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Code smell` | `BSL`
`OS` | `Info` | `Yes` | `1` | `error` | ## Description @@ -20,17 +20,17 @@ * Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) --> ## Snippets - + ### Diagnostic ignorance in code ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:CommonModuleNameGlobalClient-off +// BSLLS:CommonModuleNameGlobalClient-on ``` ### Parameter for config ```json -"": +"CommonModuleNameGlobalClient": false ``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 5088bbd207c..249cde8c4b7 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,7 +8,7 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **94** +Total: **95** * Error: **31** * Code smell: **59** diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index 7705686ef53..2e520d21339 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -126,6 +126,16 @@ "title": "Missed postfix \"Global\"", "$id": "#/definitions/CommonModuleNameGlobal" }, + "CommonModuleNameGlobalClient": { + "description": "Global module with postfix \"Client\"", + "default": null, + "type": [ + "boolean", + "object" + ], + "title": "Global module with postfix \"Client\"", + "$id": "#/definitions/CommonModuleNameGlobalClient" + }, "CommonModuleNameServerCall": { "description": "Missed postfix \"ServerCall\"", "default": null, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 6da332fac34..d283d142a5b 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -53,6 +53,9 @@ "CommonModuleNameGlobal": { "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameGlobal" }, + "CommonModuleNameGlobalClient": { + "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameGlobalClient" + }, "CommonModuleNameServerCall": { "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameServerCall" }, From 3c66ea93ae264e6f9aaee7f9c198008935642bbc Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sun, 19 Apr 2020 09:17:58 +0300 Subject: [PATCH 180/444] =?UTF-8?q?patter=20=D0=B2=20super?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCommonModuleNameDiagnostic.java | 10 ++++++++-- .../CommonModuleNameCachedDiagnostic.java | 12 ++++-------- .../CommonModuleNameClientDiagnostic.java | 12 ++++-------- .../CommonModuleNameClientServerDiagnostic.java | 9 ++------- .../CommonModuleNameFullAccessDiagnostic.java | 12 ++++-------- .../CommonModuleNameGlobalClientDiagnostic.java | 11 ++++------- .../CommonModuleNameGlobalDiagnostic.java | 11 ++++------- .../CommonModuleNameServerCallDiagnostic.java | 11 +++-------- 8 files changed, 33 insertions(+), 55 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java index 4b0b7ec5b84..cdd27ce8fc9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java @@ -29,10 +29,16 @@ abstract class AbstractCommonModuleNameDiagnostic extends AbstractDiagnostic { - Pattern pattern; + private final Pattern pattern; - public AbstractCommonModuleNameDiagnostic(DiagnosticInfo info) { + public AbstractCommonModuleNameDiagnostic(DiagnosticInfo info, String regexp) { super(info); + + pattern = Pattern.compile( + regexp, + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE + ); + } @Override diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java index 1b5b8d64d87..a16b2a88ff3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java @@ -29,8 +29,6 @@ import com.github._1c_syntax.mdclasses.mdo.CommonModule; import com.github._1c_syntax.mdclasses.metadata.additional.ReturnValueReuse; -import java.util.regex.Pattern; - @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, severity = DiagnosticSeverity.INFO, @@ -41,13 +39,11 @@ ) public class CommonModuleNameCachedDiagnostic extends AbstractCommonModuleNameDiagnostic { - public CommonModuleNameCachedDiagnostic(DiagnosticInfo info) { - super(info); - pattern = Pattern.compile( - "^.*повтисп|^.*сached", - Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE - ); + private static final String REGEXP = "^.*повтисп|^.*сached"; + + public CommonModuleNameCachedDiagnostic(DiagnosticInfo info) { + super(info, REGEXP); } @Override diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java index 320a1d39479..0f9951caabf 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java @@ -28,8 +28,6 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.mdclasses.mdo.CommonModule; -import java.util.regex.Pattern; - @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, severity = DiagnosticSeverity.INFO, @@ -40,13 +38,11 @@ ) public class CommonModuleNameClientDiagnostic extends AbstractCommonModuleNameDiagnostic { - public CommonModuleNameClientDiagnostic(DiagnosticInfo info) { - super(info); - pattern = Pattern.compile( - "^.*клиент|^.*client", - Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE - ); + private static final String REGEXP = "^.*клиент|^.*client"; + + public CommonModuleNameClientDiagnostic(DiagnosticInfo info) { + super(info, REGEXP); } @Override diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java index 7f400be95f6..3c7add55a04 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java @@ -30,8 +30,6 @@ import com.github._1c_syntax.mdclasses.mdo.CommonModule; import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; -import java.util.regex.Pattern; - @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, severity = DiagnosticSeverity.MAJOR, @@ -49,13 +47,10 @@ ) public class CommonModuleNameClientServerDiagnostic extends AbstractCommonModuleNameDiagnostic { + private static final String REGEXP = "^.*клиентсервер|^.*clientserver"; public CommonModuleNameClientServerDiagnostic(DiagnosticInfo info) { - super(info); - pattern = Pattern.compile( - "^.*клиентсервер|^.*clientserver", - Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE - ); + super(info, REGEXP); } @Override diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java index c433fee6e58..1b96b35483b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java @@ -28,8 +28,6 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.mdclasses.mdo.CommonModule; -import java.util.regex.Pattern; - @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, severity = DiagnosticSeverity.INFO, @@ -40,13 +38,11 @@ ) public class CommonModuleNameFullAccessDiagnostic extends AbstractCommonModuleNameDiagnostic { - public CommonModuleNameFullAccessDiagnostic(DiagnosticInfo info) { - super(info); - pattern = Pattern.compile( - "^.*полныеправа|^.*fullaccess", - Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE - ); + private static final String REGEXP = "^.*полныеправа|^.*fullaccess"; + + public CommonModuleNameFullAccessDiagnostic(DiagnosticInfo info) { + super(info, REGEXP); } @Override diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java index 8cd5f2cd3b0..96fce574156 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java @@ -28,8 +28,6 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.mdclasses.mdo.CommonModule; -import java.util.regex.Pattern; - @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, severity = DiagnosticSeverity.INFO, @@ -40,12 +38,11 @@ ) public class CommonModuleNameGlobalClientDiagnostic extends AbstractCommonModuleNameDiagnostic { + + private static final String REGEXP = "^(?>(?!Клиент|client).)*$"; + public CommonModuleNameGlobalClientDiagnostic(DiagnosticInfo info) { - super(info); - pattern = Pattern.compile( - "^(?>(?!Клиент|client).)*$", - Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE - ); + super(info, REGEXP); } @Override diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java index cb87ee74516..ba8efed3d39 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java @@ -28,8 +28,6 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.mdclasses.mdo.CommonModule; -import java.util.regex.Pattern; - @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, severity = DiagnosticSeverity.INFO, @@ -40,12 +38,11 @@ ) public class CommonModuleNameGlobalDiagnostic extends AbstractCommonModuleNameDiagnostic { + + private static final String REGEXP = "^.*глобальный|^.*global"; + public CommonModuleNameGlobalDiagnostic(DiagnosticInfo info) { - super(info); - pattern = Pattern.compile( - "^.*глобальный|^.*global", - Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE - ); + super(info, REGEXP); } @Override diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java index 38b5da120bd..b4e33348e4f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java @@ -28,8 +28,6 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.mdclasses.mdo.CommonModule; -import java.util.regex.Pattern; - @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, severity = DiagnosticSeverity.INFO, @@ -41,13 +39,10 @@ ) public class CommonModuleNameServerCallDiagnostic extends AbstractCommonModuleNameDiagnostic { - public CommonModuleNameServerCallDiagnostic(DiagnosticInfo info) { - super(info); + private static final String REGEXP = "^.*вызовсервера|^.*servercall"; - pattern = Pattern.compile( - "^.*вызовсервера|^.*servercall", - Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE - ); + public CommonModuleNameServerCallDiagnostic(DiagnosticInfo info) { + super(info, REGEXP); } @Override From f0a71a1eaa649c15d8c26db6e49d32dd9af4c974 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sun, 19 Apr 2020 09:37:26 +0300 Subject: [PATCH 181/444] Metadata --- .../CommonModuleNameCachedDiagnostic.java | 15 +++++++++++---- .../CommonModuleNameClientDiagnostic.java | 16 ++++++++++++---- ...CommonModuleNameClientServerDiagnostic.java | 5 ++--- .../CommonModuleNameFullAccessDiagnostic.java | 18 +++++++++++++----- ...CommonModuleNameGlobalClientDiagnostic.java | 13 +++++++++---- .../CommonModuleNameGlobalDiagnostic.java | 16 ++++++++++++---- .../CommonModuleNameServerCallDiagnostic.java | 15 +++++++++++---- 7 files changed, 70 insertions(+), 28 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java index a16b2a88ff3..3504fe46350 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java @@ -23,20 +23,27 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; import com.github._1c_syntax.mdclasses.metadata.additional.ReturnValueReuse; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, - severity = DiagnosticSeverity.INFO, - minutesToFix = 1, + severity = DiagnosticSeverity.MAJOR, + scope = DiagnosticScope.BSL, + modules = { + ModuleType.CommonModule + }, + minutesToFix = 5, tags = { - DiagnosticTag.STANDARD + DiagnosticTag.STANDARD, + DiagnosticTag.BADPRACTICE, + DiagnosticTag.UNPREDICTABLE } - ) public class CommonModuleNameCachedDiagnostic extends AbstractCommonModuleNameDiagnostic { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java index 0f9951caabf..73322a59bd3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java @@ -23,19 +23,27 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, - severity = DiagnosticSeverity.INFO, - minutesToFix = 1, + severity = DiagnosticSeverity.MINOR, + scope = DiagnosticScope.BSL, + modules = { + ModuleType.CommonModule + }, + minutesToFix = 5, tags = { - DiagnosticTag.STANDARD + DiagnosticTag.STANDARD, + DiagnosticTag.BADPRACTICE, + DiagnosticTag.UNPREDICTABLE, + DiagnosticTag.BRAINOVERLOAD } - ) public class CommonModuleNameClientDiagnostic extends AbstractCommonModuleNameDiagnostic { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java index 3c7add55a04..ca21c1e0c0a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java @@ -37,13 +37,12 @@ modules = { ModuleType.CommonModule }, - minutesToFix = 2, + minutesToFix = 5, tags = { - DiagnosticTag.BADPRACTICE, DiagnosticTag.STANDARD, + DiagnosticTag.BADPRACTICE, DiagnosticTag.UNPREDICTABLE } - ) public class CommonModuleNameClientServerDiagnostic extends AbstractCommonModuleNameDiagnostic { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java index 1b96b35483b..7166efc6b02 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java @@ -23,19 +23,27 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; @DiagnosticMetadata( - type = DiagnosticType.CODE_SMELL, - severity = DiagnosticSeverity.INFO, - minutesToFix = 1, + type = DiagnosticType.SECURITY_HOTSPOT, + severity = DiagnosticSeverity.MAJOR, + scope = DiagnosticScope.BSL, + modules = { + ModuleType.CommonModule + }, + minutesToFix = 5, tags = { - DiagnosticTag.STANDARD + DiagnosticTag.STANDARD, + DiagnosticTag.BADPRACTICE, + DiagnosticTag.UNPREDICTABLE, + DiagnosticTag.SUSPICIOUS } - ) public class CommonModuleNameFullAccessDiagnostic extends AbstractCommonModuleNameDiagnostic { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java index 96fce574156..72a210f2f81 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java @@ -23,19 +23,24 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, - severity = DiagnosticSeverity.INFO, - minutesToFix = 1, + severity = DiagnosticSeverity.MAJOR, + scope = DiagnosticScope.BSL, + modules = { + ModuleType.CommonModule + }, + minutesToFix = 5, tags = { - DiagnosticTag.ERROR + DiagnosticTag.STANDARD } - ) public class CommonModuleNameGlobalClientDiagnostic extends AbstractCommonModuleNameDiagnostic { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java index ba8efed3d39..25e7cd03705 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java @@ -23,19 +23,27 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, - severity = DiagnosticSeverity.INFO, - minutesToFix = 2, + severity = DiagnosticSeverity.MAJOR, + scope = DiagnosticScope.BSL, + modules = { + ModuleType.CommonModule + }, + minutesToFix = 5, tags = { - DiagnosticTag.STANDARD + DiagnosticTag.STANDARD, + DiagnosticTag.BADPRACTICE, + DiagnosticTag.UNPREDICTABLE, + DiagnosticTag.BRAINOVERLOAD } - ) public class CommonModuleNameGlobalDiagnostic extends AbstractCommonModuleNameDiagnostic { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java index b4e33348e4f..433a83469f7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java @@ -23,19 +23,26 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, - severity = DiagnosticSeverity.INFO, - minutesToFix = 1, + severity = DiagnosticSeverity.MINOR, + scope = DiagnosticScope.BSL, + modules = { + ModuleType.CommonModule + }, + minutesToFix = 5, tags = { - DiagnosticTag.STANDARD + DiagnosticTag.STANDARD, + DiagnosticTag.BADPRACTICE, + DiagnosticTag.UNPREDICTABLE } - ) public class CommonModuleNameServerCallDiagnostic extends AbstractCommonModuleNameDiagnostic { From 1376750a4daa7f36e4e9b3ade52d84820761ceed Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sun, 19 Apr 2020 10:46:25 +0300 Subject: [PATCH 182/444] docs --- docs/diagnostics/CommonModuleNameCached.md | 8 ++++++++ docs/diagnostics/CommonModuleNameClient.md | 16 ++++++++++++++++ docs/diagnostics/CommonModuleNameClientServer.md | 6 +++--- docs/diagnostics/CommonModuleNameFullAccess.md | 7 +++++++ docs/diagnostics/CommonModuleNameGlobal.md | 7 +++++++ docs/diagnostics/CommonModuleNameGlobalClient.md | 12 ++++++++++++ docs/diagnostics/CommonModuleNameServerCall.md | 13 +++++++++++++ 7 files changed, 66 insertions(+), 3 deletions(-) diff --git a/docs/diagnostics/CommonModuleNameCached.md b/docs/diagnostics/CommonModuleNameCached.md index 2bbb3a06a74..83ecf2b62dd 100644 --- a/docs/diagnostics/CommonModuleNameCached.md +++ b/docs/diagnostics/CommonModuleNameCached.md @@ -8,9 +8,15 @@ ## Описание диагностики +Модули, предназначенные для реализации на сервере или на клиенте функций с повторным использованием возвращаемых +значений (на время вызова или на время сеанса), именуются с постфиксом "ПовтИсп" (англ. "Cached") +и "КлиентПовтИсп" (англ. "ClientCached") соответственно. + ## Примеры +РаботаСФайламиКлиентПовтИсп, UsersInternalCached + ## Источники +[Стандарт: Правила создания общих модулей](https://its.1c.ru/db/v8std#content:469:hdoc:3.2.3) + ## Сниппеты diff --git a/docs/diagnostics/CommonModuleNameClient.md b/docs/diagnostics/CommonModuleNameClient.md index 950369d208c..3d36702f8d8 100644 --- a/docs/diagnostics/CommonModuleNameClient.md +++ b/docs/diagnostics/CommonModuleNameClient.md @@ -8,9 +8,23 @@ ## Описание диагностики +Клиентские общие модули содержат клиентскую бизнес-логику (функциональность, определенную только для клиента) + и имеют признаки: + +* Клиент (управляемое приложение) +* Клиент (обычное приложение) + +Исключение составляют случаи, когда клиентские процедуры и функции должны быть доступны только в режиме управляемого +приложения (только в режиме обычного приложения или только в режиме внешнего соединения). +В таких случаях, допустима иная комбинация двух этих признаков. + +Клиентские общие модули именуются с постфиксом "Клиент" (англ. "Client" ). Кроме случая - когда стоит флаг Глобальный. + ## Примеры +РаботаСФайламиКлиент, ОбщегоНазначенияКлиент, StandardSubsystemsClient + ## Источники +[Стандарт: Тексты модулей](https://its.1c.ru/db/v8std#content:469:hdoc:2.3) + ## Сниппеты diff --git a/docs/diagnostics/CommonModuleNameClientServer.md b/docs/diagnostics/CommonModuleNameClientServer.md index 577cb955648..e467f0f329d 100644 --- a/docs/diagnostics/CommonModuleNameClientServer.md +++ b/docs/diagnostics/CommonModuleNameClientServer.md @@ -17,11 +17,11 @@ Общие модули этого вида именуются с постфиксом "КлиентСервер" (англ. "ClientServer"). -Например: РаботаСФайламиКлиентСервер, ОбщегоНазначенияКлиентСервер, UsersClientServer - ## Примеры +РаботаСФайламиКлиентСервер, ОбщегоНазначенияКлиентСервер, UsersClientServer + ## Источники -[Правила создания общих модулей](https://its.1c.ru/db/v8std#content:469:hdoc:2.4) +[Стандарт: Правила создания общих модулей](https://its.1c.ru/db/v8std#content:469:hdoc:2.4) ## Сниппеты diff --git a/docs/diagnostics/CommonModuleNameFullAccess.md b/docs/diagnostics/CommonModuleNameFullAccess.md index 7c704e4417f..7a1cc61276d 100644 --- a/docs/diagnostics/CommonModuleNameFullAccess.md +++ b/docs/diagnostics/CommonModuleNameFullAccess.md @@ -8,9 +8,14 @@ ## Описание диагностики +Модули, выполняющиеся в привилегированном режиме, имеющие признак Привилегированный, +именуются с постфиксом "ПолныеПрава" (англ. "FullAccess"). + ## Примеры +Например: РаботаСФайламиПолныеПрава, FilesFullAccess + ## Источники +[Стандарт: Тексты модулей](https://its.1c.ru/db/v8std#content:469:hdoc:3.2.2) + ## Сниппеты diff --git a/docs/diagnostics/CommonModuleNameGlobal.md b/docs/diagnostics/CommonModuleNameGlobal.md index 0905c595bb0..5a0ea8bdbca 100644 --- a/docs/diagnostics/CommonModuleNameGlobal.md +++ b/docs/diagnostics/CommonModuleNameGlobal.md @@ -8,9 +8,14 @@ ## Описание диагностики +Для глобальных модулей добавляется постфикс "Глобальный" (англ. "Global"), + в этом случае постфикс "Клиент" добавлять не следует. + ## Примеры +РаботаСФайламиГлобальный, InfobaseUpdateGlobal + ## Источники +[Стандарт: Тексты модулей](https://its.1c.ru/db/v8std#content:469:hdoc:3.2.1) + ## Сниппеты diff --git a/docs/diagnostics/CommonModuleNameGlobalClient.md b/docs/diagnostics/CommonModuleNameGlobalClient.md index d00e2263fca..e50847dae9a 100644 --- a/docs/diagnostics/CommonModuleNameGlobalClient.md +++ b/docs/diagnostics/CommonModuleNameGlobalClient.md @@ -8,9 +8,18 @@ ## Описание диагностики +Для глобальных модулей добавляется постфикс "Глобальный" (англ. "Global"), +в этом случае постфикс "Клиент" добавлять не следует. + ## Примеры +НеПравильно: +РаботаСФайламиГлобальныйКлиент, InfobaseUpdateGlobalClient + +Правильно: +РаботаСФайламиГлобальный, InfobaseUpdateGlobal + ## Источники + +[Стандарт: Тексты модулей](https://its.1c.ru/db/v8std#content:469:hdoc:3.2.1) + ## Сниппеты diff --git a/docs/diagnostics/CommonModuleNameServerCall.md b/docs/diagnostics/CommonModuleNameServerCall.md index cee74ccebff..6e23d5c9812 100644 --- a/docs/diagnostics/CommonModuleNameServerCall.md +++ b/docs/diagnostics/CommonModuleNameServerCall.md @@ -8,9 +8,20 @@ ## Описание диагностики +Серверные общие модули для вызова с клиента содержат серверные процедуры и функции, доступные для использования +из клиентского кода. Они составляют клиентский программный интерфейс сервера приложения. +Такие процедуры и функции размещаются в общих модулях с признаком: + +* Сервер (флажок Вызов сервера установлен) + +Серверные общие модули для вызова с клиента называются по общим правилам именования объектов метаданных +и должны именоваться с постфиксом "ВызовСервера" (англ. "ServerCall"). + ## Примеры +РаботаСФайламиВызовСервера, CommonServerCall + ## Источники +[Стандарт: Тексты модулей](https://its.1c.ru/db/v8std#content:469:hdoc:2.2) + ## Сниппеты From 73635a7e3c67d28a68a8f39be2361923c1363223 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Sun, 19 Apr 2020 11:31:47 +0300 Subject: [PATCH 183/444] =?UTF-8?q?=D0=A1=D0=BB=D0=B8=D1=88=D0=BA=D0=BE?= =?UTF-8?q?=D0=BC=20=D0=BC=D0=BD=D0=BE=D0=B3=D0=BE=D1=82=D0=B5=D0=B3=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/CommonModuleNameClientDiagnostic.java | 3 +-- .../diagnostics/CommonModuleNameFullAccessDiagnostic.java | 3 +-- .../diagnostics/CommonModuleNameGlobalDiagnostic.java | 1 - 3 files changed, 2 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java index 73322a59bd3..d8fa8a39f50 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java @@ -41,8 +41,7 @@ tags = { DiagnosticTag.STANDARD, DiagnosticTag.BADPRACTICE, - DiagnosticTag.UNPREDICTABLE, - DiagnosticTag.BRAINOVERLOAD + DiagnosticTag.UNPREDICTABLE } ) public class CommonModuleNameClientDiagnostic extends AbstractCommonModuleNameDiagnostic { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java index 7166efc6b02..0e97ba0d90f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java @@ -41,8 +41,7 @@ tags = { DiagnosticTag.STANDARD, DiagnosticTag.BADPRACTICE, - DiagnosticTag.UNPREDICTABLE, - DiagnosticTag.SUSPICIOUS + DiagnosticTag.UNPREDICTABLE } ) public class CommonModuleNameFullAccessDiagnostic extends AbstractCommonModuleNameDiagnostic { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java index 25e7cd03705..501cc8f47da 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java @@ -41,7 +41,6 @@ tags = { DiagnosticTag.STANDARD, DiagnosticTag.BADPRACTICE, - DiagnosticTag.UNPREDICTABLE, DiagnosticTag.BRAINOVERLOAD } ) From 8cc345d1e3507b35b14f7c4496f6fee4a5fdb0c2 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Tue, 21 Apr 2020 16:01:30 +0300 Subject: [PATCH 184/444] precommit --- docs/diagnostics/CommonModuleNameCached.md | 2 +- docs/diagnostics/CommonModuleNameClient.md | 2 +- .../CommonModuleNameClientServer.md | 2 +- .../diagnostics/CommonModuleNameFullAccess.md | 2 +- docs/diagnostics/CommonModuleNameGlobal.md | 2 +- .../CommonModuleNameGlobalClient.md | 2 +- .../diagnostics/CommonModuleNameServerCall.md | 2 +- docs/diagnostics/index.md | 11 +++++-- docs/en/diagnostics/CommonModuleNameCached.md | 2 +- docs/en/diagnostics/CommonModuleNameClient.md | 2 +- .../CommonModuleNameClientServer.md | 2 +- .../diagnostics/CommonModuleNameFullAccess.md | 2 +- docs/en/diagnostics/CommonModuleNameGlobal.md | 2 +- .../CommonModuleNameGlobalClient.md | 2 +- .../diagnostics/CommonModuleNameServerCall.md | 2 +- docs/en/diagnostics/index.md | 11 +++++-- .../configuration/parameters-schema.json | 30 +++++++++++++++++++ .../languageserver/configuration/schema.json | 9 ++++++ 18 files changed, 71 insertions(+), 18 deletions(-) diff --git a/docs/diagnostics/CommonModuleNameCached.md b/docs/diagnostics/CommonModuleNameCached.md index 83ecf2b62dd..1d8a065d602 100644 --- a/docs/diagnostics/CommonModuleNameCached.md +++ b/docs/diagnostics/CommonModuleNameCached.md @@ -2,7 +2,7 @@ | Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Дефект кода` | `BSL`
`OS` | `Информационный` | `Да` | `1` | `standard` | +| `Дефект кода` | `BSL` | `Важный` | `Да` | `5` | `standard`
`badpractice`
`unpredictable` | ## Описание диагностики diff --git a/docs/diagnostics/CommonModuleNameClient.md b/docs/diagnostics/CommonModuleNameClient.md index 3d36702f8d8..b191ae1bfb0 100644 --- a/docs/diagnostics/CommonModuleNameClient.md +++ b/docs/diagnostics/CommonModuleNameClient.md @@ -2,7 +2,7 @@ | Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Дефект кода` | `BSL`
`OS` | `Информационный` | `Да` | `1` | `standard` | +| `Дефект кода` | `BSL` | `Незначительный` | `Да` | `5` | `standard`
`badpractice`
`unpredictable` | ## Описание диагностики diff --git a/docs/diagnostics/CommonModuleNameClientServer.md b/docs/diagnostics/CommonModuleNameClientServer.md index e467f0f329d..7e0f02a37a4 100644 --- a/docs/diagnostics/CommonModuleNameClientServer.md +++ b/docs/diagnostics/CommonModuleNameClientServer.md @@ -2,7 +2,7 @@ | Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Дефект кода` | `BSL` | `Важный` | `Да` | `2` | `badpractice`
`standard`
`unpredictable` | +| `Дефект кода` | `BSL` | `Важный` | `Да` | `5` | `standard`
`badpractice`
`unpredictable` | ## Описание диагностики diff --git a/docs/diagnostics/CommonModuleNameFullAccess.md b/docs/diagnostics/CommonModuleNameFullAccess.md index 7a1cc61276d..7db398c816b 100644 --- a/docs/diagnostics/CommonModuleNameFullAccess.md +++ b/docs/diagnostics/CommonModuleNameFullAccess.md @@ -2,7 +2,7 @@ | Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Дефект кода` | `BSL`
`OS` | `Информационный` | `Да` | `1` | `standard` | +| `Потенциальная уязвимость` | `BSL` | `Важный` | `Да` | `5` | `standard`
`badpractice`
`unpredictable` | ## Описание диагностики diff --git a/docs/diagnostics/CommonModuleNameGlobal.md b/docs/diagnostics/CommonModuleNameGlobal.md index 5a0ea8bdbca..bfa956f7931 100644 --- a/docs/diagnostics/CommonModuleNameGlobal.md +++ b/docs/diagnostics/CommonModuleNameGlobal.md @@ -2,7 +2,7 @@ | Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Дефект кода` | `BSL`
`OS` | `Информационный` | `Да` | `2` | `standard` | +| `Дефект кода` | `BSL` | `Важный` | `Да` | `5` | `standard`
`badpractice`
`brainoverload` | ## Описание диагностики diff --git a/docs/diagnostics/CommonModuleNameGlobalClient.md b/docs/diagnostics/CommonModuleNameGlobalClient.md index e50847dae9a..406095c539e 100644 --- a/docs/diagnostics/CommonModuleNameGlobalClient.md +++ b/docs/diagnostics/CommonModuleNameGlobalClient.md @@ -2,7 +2,7 @@ | Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Дефект кода` | `BSL`
`OS` | `Информационный` | `Да` | `1` | `error` | +| `Дефект кода` | `BSL` | `Важный` | `Да` | `5` | `standard` | ## Описание диагностики diff --git a/docs/diagnostics/CommonModuleNameServerCall.md b/docs/diagnostics/CommonModuleNameServerCall.md index 6e23d5c9812..9cbf5661dfa 100644 --- a/docs/diagnostics/CommonModuleNameServerCall.md +++ b/docs/diagnostics/CommonModuleNameServerCall.md @@ -2,7 +2,7 @@ | Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Дефект кода` | `BSL`
`OS` | `Информационный` | `Да` | `1` | `standard` | +| `Дефект кода` | `BSL` | `Незначительный` | `Да` | `5` | `standard`
`badpractice`
`unpredictable` | ## Описание диагностики diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 3d83ffd03c8..0af57c0bf58 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,12 +8,12 @@ ## Список реализованных диагностик -Общее количество: **95** +Общее количество: **98** * Дефект кода: **62** * Уязвимость: **2** * Ошибка: **31** -* Потенциальная уязвимость: **2** +* Потенциальная уязвимость: **3** | Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги | | --- | --- | :-: | --- | --- | --- | @@ -25,6 +25,13 @@ | [CommentedCode](CommentedCode.md) | Закомментированный фрагмент кода | Да | Незначительный | Дефект кода | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Нарушение правил работы с транзакциями для метода 'ЗафиксироватьТранзакцию' | Да | Важный | Ошибка | `standard` | | [CommonModuleAssign](CommonModuleAssign.md) | Присвоение общему модулю | Да | Блокирующий | Ошибка | `error` | +| [CommonModuleNameCached](CommonModuleNameCached.md) | Пропущен постфикс "ПовтИсп" | Да | Важный | Дефект кода | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameClient](CommonModuleNameClient.md) | Пропущен постфикс "Клиент" | Да | Незначительный | Дефект кода | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameClientServer](CommonModuleNameClientServer.md) | Пропущен постфикс "КлиентСервер" | Да | Важный | Дефект кода | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameFullAccess](CommonModuleNameFullAccess.md) | Пропущен постфикс "ПолныеПрава" | Да | Важный | Потенциальная уязвимость | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameGlobal](CommonModuleNameGlobal.md) | Пропущен постфикс "Глобальный" | Да | Важный | Дефект кода | `standard`
`badpractice`
`brainoverload` | +| [CommonModuleNameGlobalClient](CommonModuleNameGlobalClient.md) | Глобальный модуль с постфиксом "Клиент" | Да | Важный | Дефект кода | `standard` | +| [CommonModuleNameServerCall](CommonModuleNameServerCall.md) | Пропущен постфикс "ВызовСервера" | Да | Незначительный | Дефект кода | `standard`
`badpractice`
`unpredictable` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Директивы компиляции методов | Да | Важный | Дефект кода | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Лишняя директива компиляции | Да | Важный | Дефект кода | `clumsy`
`standard`
`unpredictable` | | [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Подряд идущие пустые строки | Да | Информационный | Дефект кода | `badpractice` | diff --git a/docs/en/diagnostics/CommonModuleNameCached.md b/docs/en/diagnostics/CommonModuleNameCached.md index b0eb59c7bed..f68b7fcef4c 100644 --- a/docs/en/diagnostics/CommonModuleNameCached.md +++ b/docs/en/diagnostics/CommonModuleNameCached.md @@ -2,7 +2,7 @@ | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Code smell` | `BSL`
`OS` | `Info` | `Yes` | `1` | `standard` | +| `Code smell` | `BSL` | `Major` | `Yes` | `5` | `standard`
`badpractice`
`unpredictable` | ## Description diff --git a/docs/en/diagnostics/CommonModuleNameClient.md b/docs/en/diagnostics/CommonModuleNameClient.md index 8f06688fabc..384de32edbe 100644 --- a/docs/en/diagnostics/CommonModuleNameClient.md +++ b/docs/en/diagnostics/CommonModuleNameClient.md @@ -2,7 +2,7 @@ | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Code smell` | `BSL`
`OS` | `Info` | `Yes` | `1` | `standard` | +| `Code smell` | `BSL` | `Minor` | `Yes` | `5` | `standard`
`badpractice`
`unpredictable` | ## Description diff --git a/docs/en/diagnostics/CommonModuleNameClientServer.md b/docs/en/diagnostics/CommonModuleNameClientServer.md index df3a228f51d..f7bd46df19a 100644 --- a/docs/en/diagnostics/CommonModuleNameClientServer.md +++ b/docs/en/diagnostics/CommonModuleNameClientServer.md @@ -2,7 +2,7 @@ | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Code smell` | `BSL` | `Major` | `Yes` | `2` | `badpractice`
`standard`
`unpredictable` | +| `Code smell` | `BSL` | `Major` | `Yes` | `5` | `standard`
`badpractice`
`unpredictable` | ## Description diff --git a/docs/en/diagnostics/CommonModuleNameFullAccess.md b/docs/en/diagnostics/CommonModuleNameFullAccess.md index ca6cffcb8f0..017824cc80c 100644 --- a/docs/en/diagnostics/CommonModuleNameFullAccess.md +++ b/docs/en/diagnostics/CommonModuleNameFullAccess.md @@ -2,7 +2,7 @@ | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Code smell` | `BSL`
`OS` | `Info` | `Yes` | `1` | `standard` | +| `Security Hotspot` | `BSL` | `Major` | `Yes` | `5` | `standard`
`badpractice`
`unpredictable` | ## Description diff --git a/docs/en/diagnostics/CommonModuleNameGlobal.md b/docs/en/diagnostics/CommonModuleNameGlobal.md index b79370c1ce8..fe99c8d9d10 100644 --- a/docs/en/diagnostics/CommonModuleNameGlobal.md +++ b/docs/en/diagnostics/CommonModuleNameGlobal.md @@ -2,7 +2,7 @@ | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Code smell` | `BSL`
`OS` | `Info` | `Yes` | `2` | `standard` | +| `Code smell` | `BSL` | `Major` | `Yes` | `5` | `standard`
`badpractice`
`brainoverload` | ## Description diff --git a/docs/en/diagnostics/CommonModuleNameGlobalClient.md b/docs/en/diagnostics/CommonModuleNameGlobalClient.md index f6d3069371c..6bbc7f913b8 100644 --- a/docs/en/diagnostics/CommonModuleNameGlobalClient.md +++ b/docs/en/diagnostics/CommonModuleNameGlobalClient.md @@ -2,7 +2,7 @@ | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Code smell` | `BSL`
`OS` | `Info` | `Yes` | `1` | `error` | +| `Code smell` | `BSL` | `Major` | `Yes` | `5` | `standard` | ## Description diff --git a/docs/en/diagnostics/CommonModuleNameServerCall.md b/docs/en/diagnostics/CommonModuleNameServerCall.md index c0cdb13e6cd..16edd513e53 100644 --- a/docs/en/diagnostics/CommonModuleNameServerCall.md +++ b/docs/en/diagnostics/CommonModuleNameServerCall.md @@ -2,7 +2,7 @@ | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Code smell` | `BSL`
`OS` | `Info` | `Yes` | `1` | `standard` | +| `Code smell` | `BSL` | `Minor` | `Yes` | `5` | `standard`
`badpractice`
`unpredictable` | ## Description diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 249cde8c4b7..f910d750141 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,12 +8,12 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **95** +Total: **98** * Error: **31** * Code smell: **59** * Vulnerability: **2** -* Security Hotspot: **2** +* Security Hotspot: **3** | Key | Name| Enabled by default | Severity | Type | Tags | | --- | --- | :-: | --- | --- | --- | @@ -25,6 +25,13 @@ Total: **95** | [CommentedCode](CommentedCode.md) | Commented out code | Yes | Minor | Code smell | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Violating transaction rules for the 'CommitTransaction' method | Yes | Major | Error | `standard` | | [CommonModuleAssign](CommonModuleAssign.md) | CommonModuleAssign | Yes | Blocker | Error | `error` | +| [CommonModuleNameCached](CommonModuleNameCached.md) | Missed postfix "Cached" | Yes | Major | Code smell | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameClient](CommonModuleNameClient.md) | Missed postfix "Client" | Yes | Minor | Code smell | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameClientServer](CommonModuleNameClientServer.md) | Missed postfix "ClientServer" | Yes | Major | Code smell | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameFullAccess](CommonModuleNameFullAccess.md) | Missed postfix "FullAccess" | Yes | Major | Security Hotspot | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameGlobal](CommonModuleNameGlobal.md) | Missed postfix "Global" | Yes | Major | Code smell | `standard`
`badpractice`
`brainoverload` | +| [CommonModuleNameGlobalClient](CommonModuleNameGlobalClient.md) | Global module with postfix "Client" | Yes | Major | Code smell | `standard` | +| [CommonModuleNameServerCall](CommonModuleNameServerCall.md) | Missed postfix "ServerCall" | Yes | Minor | Code smell | `standard`
`badpractice`
`unpredictable` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Methods compilation directive | Yes | Major | Code smell | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Needless compilation directive | Yes | Major | Code smell | `clumsy`
`standard`
`unpredictable` | | [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Consecutive empty lines | Yes | Info | Code smell | `badpractice` | diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index 2e520d21339..d76007a2b66 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -106,6 +106,36 @@ "title": "CommonModuleAssign", "$id": "#/definitions/CommonModuleAssign" }, + "CommonModuleNameCached": { + "description": "Missed postfix \"Cached\"", + "default": null, + "type": [ + "boolean", + "object" + ], + "title": "Missed postfix \"Cached\"", + "$id": "#/definitions/CommonModuleNameCached" + }, + "CommonModuleNameClient": { + "description": "Missed postfix \"Client\"", + "default": null, + "type": [ + "boolean", + "object" + ], + "title": "Missed postfix \"Client\"", + "$id": "#/definitions/CommonModuleNameClient" + }, + "CommonModuleNameClientServer": { + "description": "Missed postfix \"ClientServer\"", + "default": null, + "type": [ + "boolean", + "object" + ], + "title": "Missed postfix \"ClientServer\"", + "$id": "#/definitions/CommonModuleNameClientServer" + }, "CommonModuleNameFullAccess": { "description": "Missed postfix \"FullAccess\"", "default": null, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index d283d142a5b..638c4586703 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -47,6 +47,15 @@ "CommonModuleAssign": { "$ref": "parameters-schema.json#/definitions/CommonModuleAssign" }, + "CommonModuleNameCached": { + "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameCached" + }, + "CommonModuleNameClient": { + "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameClient" + }, + "CommonModuleNameClientServer": { + "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameClientServer" + }, "CommonModuleNameFullAccess": { "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameFullAccess" }, From 10c966a642cd36ca1895e04de6fb10a50df4e83c Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Tue, 21 Apr 2020 16:18:41 +0300 Subject: [PATCH 185/444] matches -> find --- .../diagnostics/AbstractCommonModuleNameDiagnostic.java | 3 ++- .../diagnostics/CommonModuleNameCachedDiagnostic.java | 2 +- .../diagnostics/CommonModuleNameClientDiagnostic.java | 2 +- .../diagnostics/CommonModuleNameClientServerDiagnostic.java | 2 +- .../diagnostics/CommonModuleNameFullAccessDiagnostic.java | 2 +- .../diagnostics/CommonModuleNameGlobalDiagnostic.java | 2 +- .../diagnostics/CommonModuleNameServerCallDiagnostic.java | 2 +- 7 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java index cdd27ce8fc9..77b328d9aef 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java @@ -48,9 +48,10 @@ protected void check(DocumentContext documentContext) { } documentContext.getMdObject() + .filter(CommonModule.class::isInstance) .map(CommonModule.class::cast) .filter(this::flagsCheck) - .filter(commonModule -> !pattern.matcher(commonModule.getName()).matches()) + .filter(commonModule -> !pattern.matcher(commonModule.getName()).find()) .ifPresent(commonModule -> diagnosticStorage.addDiagnostic(documentContext.getTokens().get(0))); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java index 3504fe46350..cfbc384e9bb 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java @@ -47,7 +47,7 @@ ) public class CommonModuleNameCachedDiagnostic extends AbstractCommonModuleNameDiagnostic { - private static final String REGEXP = "^.*повтисп|^.*сached"; + private static final String REGEXP = "повтисп|сached"; public CommonModuleNameCachedDiagnostic(DiagnosticInfo info) { super(info, REGEXP); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java index d8fa8a39f50..4583ccf34d3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java @@ -46,7 +46,7 @@ ) public class CommonModuleNameClientDiagnostic extends AbstractCommonModuleNameDiagnostic { - private static final String REGEXP = "^.*клиент|^.*client"; + private static final String REGEXP = "клиент|client"; public CommonModuleNameClientDiagnostic(DiagnosticInfo info) { super(info, REGEXP); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java index ca21c1e0c0a..9bf906774b5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java @@ -46,7 +46,7 @@ ) public class CommonModuleNameClientServerDiagnostic extends AbstractCommonModuleNameDiagnostic { - private static final String REGEXP = "^.*клиентсервер|^.*clientserver"; + private static final String REGEXP = "клиентсервер|clientserver"; public CommonModuleNameClientServerDiagnostic(DiagnosticInfo info) { super(info, REGEXP); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java index 0e97ba0d90f..02551e89377 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java @@ -46,7 +46,7 @@ ) public class CommonModuleNameFullAccessDiagnostic extends AbstractCommonModuleNameDiagnostic { - private static final String REGEXP = "^.*полныеправа|^.*fullaccess"; + private static final String REGEXP = "полныеправа|fullaccess"; public CommonModuleNameFullAccessDiagnostic(DiagnosticInfo info) { super(info, REGEXP); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java index 501cc8f47da..90ec1b63e45 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java @@ -46,7 +46,7 @@ ) public class CommonModuleNameGlobalDiagnostic extends AbstractCommonModuleNameDiagnostic { - private static final String REGEXP = "^.*глобальный|^.*global"; + private static final String REGEXP = "глобальный|global"; public CommonModuleNameGlobalDiagnostic(DiagnosticInfo info) { super(info, REGEXP); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java index 433a83469f7..8b4af0d9dcc 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java @@ -46,7 +46,7 @@ ) public class CommonModuleNameServerCallDiagnostic extends AbstractCommonModuleNameDiagnostic { - private static final String REGEXP = "^.*вызовсервера|^.*servercall"; + private static final String REGEXP = "вызовсервера|servercall"; public CommonModuleNameServerCallDiagnostic(DiagnosticInfo info) { super(info, REGEXP); From 12563b0f45b62458e7623bfb427215855d827013 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Tue, 21 Apr 2020 19:41:59 +0300 Subject: [PATCH 186/444] =?UTF-8?q?=D0=BD=D0=B0=20=D0=BF=D0=B5=D1=80=D0=B2?= =?UTF-8?q?=D1=8B=D0=B9=20=D1=82=D0=BE=D0=BA=D0=B5=D0=BD=20=D0=B4=D0=B5?= =?UTF-8?q?=D1=84=D0=B0=D1=83=D0=BB=D1=82=20=D1=87=D0=B5=D0=BD=D0=BD=D0=B5?= =?UTF-8?q?=D0=BB=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCommonModuleNameDiagnostic.java | 4 ++-- .../CommonModuleNameCachedDiagnosticTest.java | 2 +- .../CommonModuleNameClientDiagnosticTest.java | 2 +- ...mmonModuleNameClientServerDiagnosticTest.java | 2 +- ...CommonModuleNameFullAccessDiagnosticTest.java | 2 +- ...mmonModuleNameGlobalClientDiagnosticTest.java | 2 +- .../CommonModuleNameGlobalDiagnosticTest.java | 2 +- ...CommonModuleNameServerCallDiagnosticTest.java | 2 +- .../NonStandardRegionDiagnosticTest.java | 16 ++++++++-------- .../Ext/Module.bsl" | 7 ++++++- 10 files changed, 23 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java index 77b328d9aef..f727bd45237 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java @@ -43,7 +43,7 @@ public AbstractCommonModuleNameDiagnostic(DiagnosticInfo info, String regexp) { @Override protected void check(DocumentContext documentContext) { - if (documentContext.getTokens().isEmpty()) { + if (documentContext.getTokensFromDefaultChannel().isEmpty()) { return; } @@ -52,7 +52,7 @@ protected void check(DocumentContext documentContext) { .map(CommonModule.class::cast) .filter(this::flagsCheck) .filter(commonModule -> !pattern.matcher(commonModule.getName()).find()) - .ifPresent(commonModule -> diagnosticStorage.addDiagnostic(documentContext.getTokens().get(0))); + .ifPresent(commonModule -> diagnosticStorage.addDiagnostic(documentContext.getTokensFromDefaultChannel().get(0))); } protected abstract boolean flagsCheck(CommonModule commonModule); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java index 16f5f29188a..a230339b405 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java @@ -70,7 +70,7 @@ void test() { //then assertThat(diagnostics).hasSize(1); assertThat(diagnostics, true) - .hasRange(0, 0, 0, 1); + .hasRange(5, 0, 1); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java index c17a1e3bdca..ef4511bc442 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java @@ -70,7 +70,7 @@ void test() { //then assertThat(diagnostics).hasSize(1); assertThat(diagnostics, true) - .hasRange(0, 0, 0, 1); + .hasRange(5, 0, 1); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java index 65b8d5f2cb0..2adfde03167 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java @@ -70,7 +70,7 @@ void test() { //then assertThat(diagnostics).hasSize(1); assertThat(diagnostics, true) - .hasRange(0, 0, 0, 1); + .hasRange(5, 0, 1); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnosticTest.java index 00702ba0fd5..3813afac3e9 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnosticTest.java @@ -70,7 +70,7 @@ void test() { //then assertThat(diagnostics).hasSize(1); assertThat(diagnostics, true) - .hasRange(0, 0, 0, 1); + .hasRange(5, 0, 1); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java index 4afd3b392ca..05b43b25c99 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java @@ -70,7 +70,7 @@ void test() { //then assertThat(diagnostics).hasSize(1); assertThat(diagnostics, true) - .hasRange(0, 0, 0, 1); + .hasRange(5, 0, 1); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnosticTest.java index 43c3dcfdab7..371ac661396 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnosticTest.java @@ -69,7 +69,7 @@ void test() { //then assertThat(diagnostics).hasSize(1); assertThat(diagnostics, true) - .hasRange(0, 0, 0, 1); + .hasRange(5, 0, 1); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java index 72d87133481..eef9a811986 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java @@ -71,7 +71,7 @@ void test() { //then assertThat(diagnostics).hasSize(1); assertThat(diagnostics, true) - .hasRange(0, 0, 0, 1); + .hasRange(5, 0, 1); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnosticTest.java index b9b93c99a9c..d653f9ec34e 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnosticTest.java @@ -134,14 +134,14 @@ void testCommonModule() throws IOException { assertThat(diagnostics).hasSize(8); assertThat(diagnostics, true) - .hasRange(0, 1, 27) - .hasRange(20, 1, 21) - .hasRange(28, 1, 32) - .hasRange(32, 1, 46) - .hasRange(36, 1, 63) - .hasRange(40, 1, 31) - .hasRange(44, 1, 27) - .hasRange(52, 1, 18) + .hasRange(5, 1, 27) + .hasRange(25, 1, 21) + .hasRange(33, 1, 32) + .hasRange(37, 1, 46) + .hasRange(41, 1, 63) + .hasRange(45, 1, 31) + .hasRange(49, 1, 27) + .hasRange(57, 1, 18) ; } diff --git "a/src/test/resources/metadata/CommonModules/\320\237\320\265\321\200\320\262\321\213\320\271\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\214/Ext/Module.bsl" "b/src/test/resources/metadata/CommonModules/\320\237\320\265\321\200\320\262\321\213\320\271\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\214/Ext/Module.bsl" index 7a093ced3cc..feb46be66dd 100644 --- "a/src/test/resources/metadata/CommonModules/\320\237\320\265\321\200\320\262\321\213\320\271\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\214/Ext/Module.bsl" +++ "b/src/test/resources/metadata/CommonModules/\320\237\320\265\321\200\320\262\321\213\320\271\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\214/Ext/Module.bsl" @@ -1,4 +1,9 @@ -#Область ОписаниеПеременных + +/////Описание +///// +///// + +#Область ОписаниеПеременных Перем ВалютаУчета; Перем АдресПоддержки; From 3bd9829aacb3a0ae3a4fce32db7c1c58e2d638c3 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Mon, 27 Apr 2020 13:12:30 +0300 Subject: [PATCH 187/444] Create StyleGuide.md --- docs/contributing/StyleGuide.md | 57 +++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 docs/contributing/StyleGuide.md diff --git a/docs/contributing/StyleGuide.md b/docs/contributing/StyleGuide.md new file mode 100644 index 00000000000..01d5a71ccfe --- /dev/null +++ b/docs/contributing/StyleGuide.md @@ -0,0 +1,57 @@ +# Руководство по стилю написания кода + +В данном документе собраны общие рекомендации по написанию кода в проекте BSL Language Server. + +Постарайтесь придерживаться их, и процесс ревью Вашего кода будет гладким и шелковистым (с). + +## Форматирование + +1. Весь код в модулях должен быть автоматически отформатирован. +1. Оступы - пробелами +1. Размер отступа - 2 символа. Continuous indent - тоже два символа. В IntelliJ IDEA настройка отступов по схеме 2-2-2 + +## Расположение членов класса + +1. Расположение полей, методов, модификаторов в целом должно соответствовать рекомендациям Oracle - [File organization](https://www.oracle.com/java/technologies/javase/codeconventions-fileorganization.html), и SonarSource - [Modifiers should be declared in the correct order](https://rules.sonarsource.com/java/tag/convention/RSPEC-1124) +1. Методы _рекомендуется_ размещать в следующем порядке: + 1. public методы объекта + 1. protected/package private методы объекта + 1. private методы объекта + 1. public методы класса + 1. protected/package private методы класса + 1. private методы класса + +## Статический анализ + +Код BSL Language Server автоматически проверяется на соответствие стандартам кодирования на сервисе SonarCloud - [ссылка на проект](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server). + +Список активированных правил и их настройки можно посмотреть в профиле качества [1c-syntax way](https://sonarcloud.io/organizations/1c-syntax/rules?activation=true&qprofile=AWdJBUnB2EsKsQgQiNpk). + +В силу имеющихся ограничений безопасности пулл-реквесты не из репозитория `1c-syntax/bsl-language-server` не проверяются на соответствие стандартам. После принятия пулл-реквеста рекомендуется зайти на [страницу проекта на SonarCloud](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) и просмотреть список замечаний с фильтрацией по автору. Пулл-реквест с исправлением замечаний приветствуется. + +## Линтер + +Для улучшения качества кода и предварительной проверки на соответствие стандартам рекомендуется установить в Вашу IDE плагин [SonarLint](https://www.sonarlint.org). + +Для автоматического скачивания и параметризации правил в соответствиями с настройками на SonarCloud может потребоваться "биндинг" локального проекта к проекту SonarCloud. Если в Вашей IDE не получается найти соответствующий проект на SonarCloud, обратитесь к мэйнтейнерам проекта за добавлением Вас в список "Members" на SonarCloud. + +## Логирование + +Для логирования используется библиотека `Slf4j`. Использование вывода в `System.out` и `System.err` допустимо только в исключительных случаях (например, в обработчиках cli-команд). + +Для упрощения создания экземпляра логгера рекомендуется навешивать аннотацию `@lombok.extern.slf4j.Slf4j` на объявление класса. + +## Документирование + +1. Каждый новый класс обязан иметь javadoc-описание класса. Исключение - классы, реализующие интерфейсы `BSLDiagnostic` или `QuickFixSupplier`. +1. Каждый новый package обязан иметь `package-info.java` с javadoc-описанием пакета. +1. Каждый новый публичный метод в `utils`-пакете, классах-хелперах или классах, уже имеющих javadoc-описания, обязан иметь javadoc-описание метода. + +## Внешние зависимости + +1. Подключение новых библиотек в implementation scope стоит производить аккуратно, с контролем увеличения размера итогового jar-файла. По возможности "лишние" и незадействованные суб-зависимости стоит исключать через `exclude`. +1. Явное подключение библиотеки `com.google.guava`, `Google Collections` или прочих частей библиотек семейства Guava запрещено. В случае **крайней** необходимости допустимо копирование реализации из `Guava` внутрь BSL Language Server с выполнением условий лицензии Guava. Для всего остального есть Apache Commons. +1. Прямой импорт классов `*.google.*`, а так же прочих частей библиотек Guava запрещено. Без исключений. + + +> В процессе наполнения... From 63eb898b50cdd8f81491b776ec83a51548a4a723 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Mon, 27 Apr 2020 13:12:55 +0300 Subject: [PATCH 188/444] Update index.md --- docs/contributing/index.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/contributing/index.md b/docs/contributing/index.md index 460c600d682..8f9d3a541ab 100644 --- a/docs/contributing/index.md +++ b/docs/contributing/index.md @@ -7,6 +7,7 @@ - Старт - [Настройка окружения](EnvironmentSetting.md) - [Быстрый старт](FastStart.md) + - [Руководство по стилю](StyleGuide.md) - Разработка диагностик - [Процесс (workflow) разработки диагностики](DiagnosticDevWorkFlow.md) - [Пример разработки диагностики](DiagnosticExample.md) From 59844692c03891a3a09dde85c104e9c2d8008ed1 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Mon, 27 Apr 2020 13:14:49 +0300 Subject: [PATCH 189/444] Update index.md --- docs/contributing/index.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/contributing/index.md b/docs/contributing/index.md index 8f9d3a541ab..8abaa5b9f32 100644 --- a/docs/contributing/index.md +++ b/docs/contributing/index.md @@ -5,14 +5,14 @@ ## Инструкции - Старт - - [Настройка окружения](EnvironmentSetting.md) - - [Быстрый старт](FastStart.md) - - [Руководство по стилю](StyleGuide.md) + - [Настройка окружения](EnvironmentSetting.md) + - [Быстрый старт](FastStart.md) + - [Руководство по стилю](StyleGuide.md) - Разработка диагностик - - [Процесс (workflow) разработки диагностики](DiagnosticDevWorkFlow.md) - - [Пример разработки диагностики](DiagnosticExample.md) - - [Структура диагностики, назначение и содержимое файлов](DiagnosticStructure.md) - - [Описание типов и важности диагностик](DiagnosticTypeAndSeverity.md) - - [Тэги диагностик](DiagnosticTag.md) - - [Добавление параметров диагностике](DiagnostcAddSettings.md) - - [Добавление быстрых исправлений диагностик](DiagnosticQuickFix.md) + - [Процесс (workflow) разработки диагностики](DiagnosticDevWorkFlow.md) + - [Пример разработки диагностики](DiagnosticExample.md) + - [Структура диагностики, назначение и содержимое файлов](DiagnosticStructure.md) + - [Описание типов и важности диагностик](DiagnosticTypeAndSeverity.md) + - [Тэги диагностик](DiagnosticTag.md) + - [Добавление параметров диагностике](DiagnostcAddSettings.md) + - [Добавление быстрых исправлений диагностик](DiagnosticQuickFix.md) From 742092b54eadac6e8185ef2dee66cd60149a9e04 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Mon, 27 Apr 2020 14:04:22 +0300 Subject: [PATCH 190/444] =?UTF-8?q?=D0=A2=D0=B5=D1=81=D1=82=20=D0=BD=D0=B0?= =?UTF-8?q?=20=D1=84=D0=BF=20=D0=9A=D0=BB=D0=B8=D0=B5=D0=BD=D1=82=D0=A7?= =?UTF-8?q?=D0=B5=D0=B3=D0=BE=D0=A2=D0=BE=D0=93=D0=BB=D0=BE=D0=B1=D0=B0?= =?UTF-8?q?=D0=BB=D1=8C=D0=BD=D1=8B=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...nModuleNameGlobalClientDiagnosticTest.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java index 05b43b25c99..41c9b1cc256 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java @@ -74,6 +74,29 @@ void test() { } + @Test + void testEng() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТоClientGlobal"); + when(module.isGlobal()).thenReturn(Boolean.TRUE); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(5, 0, 1); + + } + + @Test void testNegative() { @@ -113,6 +136,26 @@ void testFalse() { } + @Test + void testClientAtStart() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("КлиентЛицензированияГлобальный"); + when(module.isGlobal()).thenReturn(Boolean.TRUE); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + @SneakyThrows void getDocumentContextFromFile() { From 3d936d8606464bf8ebbe0cde125fb3ffb7641cbd Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Mon, 27 Apr 2020 17:36:57 +0300 Subject: [PATCH 191/444] fp fix --- .../diagnostics/CommonModuleNameGlobalClientDiagnostic.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java index 72a210f2f81..a3418f144c3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java @@ -44,7 +44,7 @@ ) public class CommonModuleNameGlobalClientDiagnostic extends AbstractCommonModuleNameDiagnostic { - private static final String REGEXP = "^(?>(?!Клиент|client).)*$"; + private static final String REGEXP = "^(?>(?!.+клиент|.+client).)*$"; public CommonModuleNameGlobalClientDiagnostic(DiagnosticInfo info) { super(info, REGEXP); From 4efa4334c03a40bbc4bf5dd8bfd51fa82284c0b9 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Mon, 27 Apr 2020 17:37:35 +0300 Subject: [PATCH 192/444] utils.CaseInsentivitesPatern --- build.gradle.kts | 2 +- .../AbstractCommonModuleNameDiagnostic.java | 13 ++++++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 560d4686f15..d5df81751b2 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -86,7 +86,7 @@ dependencies { exclude("org.glassfish", "javax.json") } - implementation("com.github.1c-syntax", "utils", "0.2.1") + implementation("com.github.1c-syntax", "utils", "4034e83681b") implementation("com.github.1c-syntax", "mdclasses", "86be1579c4") compileOnly("org.projectlombok", "lombok", lombok.version) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java index f727bd45237..3b54681df91 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java @@ -24,7 +24,11 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.mdclasses.mdo.MDObjectBase; +import com.github._1c_syntax.utils.CaseInsensitivePattern; +import java.util.function.Predicate; +import java.util.regex.Matcher; import java.util.regex.Pattern; abstract class AbstractCommonModuleNameDiagnostic extends AbstractDiagnostic { @@ -34,10 +38,7 @@ abstract class AbstractCommonModuleNameDiagnostic extends AbstractDiagnostic { public AbstractCommonModuleNameDiagnostic(DiagnosticInfo info, String regexp) { super(info); - pattern = Pattern.compile( - regexp, - Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE - ); + pattern = CaseInsensitivePattern.compile(regexp); } @@ -51,7 +52,9 @@ protected void check(DocumentContext documentContext) { .filter(CommonModule.class::isInstance) .map(CommonModule.class::cast) .filter(this::flagsCheck) - .filter(commonModule -> !pattern.matcher(commonModule.getName()).find()) + .map(MDObjectBase::getName) + .map(pattern::matcher) + .filter(Predicate.not(Matcher::find)) .ifPresent(commonModule -> diagnosticStorage.addDiagnostic(documentContext.getTokensFromDefaultChannel().get(0))); } From 58cf2407aa5467f408d077e43a8df92f1854daea Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Mon, 27 Apr 2020 17:37:52 +0300 Subject: [PATCH 193/444] tests --- .../CommonModuleNameCachedDiagnostic.java | 2 +- .../CommonModuleNameCachedDiagnosticTest.java | 20 ++++++++++ ...nModuleNameGlobalClientDiagnosticTest.java | 40 +++++++++++++++++++ 3 files changed, 61 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java index cfbc384e9bb..b586efc8ba1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java @@ -47,7 +47,7 @@ ) public class CommonModuleNameCachedDiagnostic extends AbstractCommonModuleNameDiagnostic { - private static final String REGEXP = "повтисп|сached"; + private static final String REGEXP = "повнорноеиспользование|повтисп|сached"; public CommonModuleNameCachedDiagnostic(DiagnosticInfo info) { super(info, REGEXP); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java index a230339b405..1e5ccc8cf06 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java @@ -74,6 +74,25 @@ void test() { } + @Test + void testSession() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТоПовтИсп"); + when(module.getReturnValuesReuse()).thenReturn(ReturnValueReuse.DURING_SESSION); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + @Test void testNegative() { @@ -93,6 +112,7 @@ void testNegative() { } + @Test void testEmptyFile() { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java index 41c9b1cc256..eb4980d0cd5 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java @@ -156,6 +156,46 @@ void testClientAtStart() { } + @Test + void testClientAtStartEng() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ClientЛицензированияГлобальный"); + when(module.isGlobal()).thenReturn(Boolean.FALSE); + when(module.isClientManagedApplication()).thenReturn(Boolean.FALSE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @Test + void testClient() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ClientЛицензированияГлобальный"); + when(module.isGlobal()).thenReturn(Boolean.TRUE); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + @SneakyThrows void getDocumentContextFromFile() { From 7aa3a3b9f354f0e75b00be014e2dcd9fd2b26b80 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Mon, 27 Apr 2020 17:38:27 +0300 Subject: [PATCH 194/444] precommit --- docs/diagnostics/index.md | 4 ++-- docs/en/diagnostics/index.md | 4 ++-- .../configuration/parameters-schema.json | 14 +++++++------- .../bsl/languageserver/configuration/schema.json | 14 +++++++------- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 0af57c0bf58..811b796be66 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,9 +8,9 @@ ## Список реализованных диагностик -Общее количество: **98** +Общее количество: **101** -* Дефект кода: **62** +* Дефект кода: **65** * Уязвимость: **2** * Ошибка: **31** * Потенциальная уязвимость: **3** diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index f910d750141..e7561eff8e2 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,10 +8,10 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **98** +Total: **101** * Error: **31** -* Code smell: **59** +* Code smell: **65** * Vulnerability: **2** * Security Hotspot: **3** diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index d76007a2b66..9be08e89978 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -108,7 +108,7 @@ }, "CommonModuleNameCached": { "description": "Missed postfix \"Cached\"", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -118,7 +118,7 @@ }, "CommonModuleNameClient": { "description": "Missed postfix \"Client\"", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -128,7 +128,7 @@ }, "CommonModuleNameClientServer": { "description": "Missed postfix \"ClientServer\"", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -138,7 +138,7 @@ }, "CommonModuleNameFullAccess": { "description": "Missed postfix \"FullAccess\"", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -148,7 +148,7 @@ }, "CommonModuleNameGlobal": { "description": "Missed postfix \"Global\"", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -158,7 +158,7 @@ }, "CommonModuleNameGlobalClient": { "description": "Global module with postfix \"Client\"", - "default": null, + "default": true, "type": [ "boolean", "object" @@ -168,7 +168,7 @@ }, "CommonModuleNameServerCall": { "description": "Missed postfix \"ServerCall\"", - "default": null, + "default": true, "type": [ "boolean", "object" diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 638c4586703..7b857252e49 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -48,25 +48,25 @@ "$ref": "parameters-schema.json#/definitions/CommonModuleAssign" }, "CommonModuleNameCached": { - "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameCached" + "$ref": "parameters-schema.json#/definitions/CommonModuleNameCached" }, "CommonModuleNameClient": { - "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameClient" + "$ref": "parameters-schema.json#/definitions/CommonModuleNameClient" }, "CommonModuleNameClientServer": { - "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameClientServer" + "$ref": "parameters-schema.json#/definitions/CommonModuleNameClientServer" }, "CommonModuleNameFullAccess": { - "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameFullAccess" + "$ref": "parameters-schema.json#/definitions/CommonModuleNameFullAccess" }, "CommonModuleNameGlobal": { - "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameGlobal" + "$ref": "parameters-schema.json#/definitions/CommonModuleNameGlobal" }, "CommonModuleNameGlobalClient": { - "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameGlobalClient" + "$ref": "parameters-schema.json#/definitions/CommonModuleNameGlobalClient" }, "CommonModuleNameServerCall": { - "$ref": "diagnostics-schema.json#/definitions/CommonModuleNameServerCall" + "$ref": "parameters-schema.json#/definitions/CommonModuleNameServerCall" }, "CompilationDirectiveLost": { "$ref": "parameters-schema.json#/definitions/CompilationDirectiveLost" From af8af0c6798d3a4902d590b55c777a1da3fccf25 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Tue, 28 Apr 2020 00:02:18 +0700 Subject: [PATCH 195/444] =?UTF-8?q?=D0=9F=D0=B0=D1=80=D0=B0=D0=BC=D0=B5?= =?UTF-8?q?=D1=82=D1=80=20"=D0=9F=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D1=8F?= =?UTF-8?q?=D1=82=D1=8C=20=D0=BF=D0=BE=D0=B4=D0=BA=D0=BB=D1=8E=D1=87=D0=B0?= =?UTF-8?q?=D0=B5=D0=BC=D1=8B=D0=B5=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4=D1=8B?= =?UTF-8?q?"=20=D0=B8=20=D0=B4=D0=BE=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=BA?= =?UTF-8?q?=D0=B0=20=D1=82=D0=B5=D1=81=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...unctionReturnsSamePrimitiveDiagnostic.java | 26 +++++++---- ...ionReturnsSamePrimitiveDiagnosticTest.java | 43 ++++++++++++++----- ...FunctionReturnsSamePrimitiveDiagnostic.bsl | 10 +++++ 3 files changed, 61 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java index 5176fc3fb2a..010a338418c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java @@ -24,6 +24,7 @@ import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticParameter; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; @@ -59,6 +60,14 @@ public class FunctionReturnsSamePrimitiveDiagnostic extends AbstractVisitorDiagn private static final Pattern pattern = Pattern.compile( "^(подключаемый|attachable)_", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); + private static final boolean CHECK_ATTACHABLE_METHODS = true; + + @DiagnosticParameter( + type = Boolean.class, + defaultValue = "" + CHECK_ATTACHABLE_METHODS + ) + private boolean checkAttachableMethods = CHECK_ATTACHABLE_METHODS; + public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { super(info); } @@ -66,14 +75,15 @@ public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { @Override public ParseTree visitFunction(BSLParser.FunctionContext ctx) { - var abortCheck = Optional.ofNullable(ctx.funcDeclaration()) - .map(BSLParser.FuncDeclarationContext::subName) - .filter(subNameContext -> pattern.matcher(subNameContext.getText()).find()) - .isPresent(); - - // Исключаем подключаемые методы - if (abortCheck) { - return ctx; + if (checkAttachableMethods) { + // Исключаем подключаемые методы + var abortCheck = Optional.ofNullable(ctx.funcDeclaration()) + .map(BSLParser.FuncDeclarationContext::subName) + .filter(subNameContext -> pattern.matcher(subNameContext.getText()).find()) + .isPresent(); + if (abortCheck) { + return ctx; + } } var tree = Trees.findAllRuleNodes(ctx, BSLParser.RULE_returnStatement); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java index b4d1a3cd769..7bc3af568ce 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java @@ -21,11 +21,11 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; -import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; import java.util.List; +import java.util.Map; import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; @@ -37,16 +37,39 @@ class FunctionReturnsSamePrimitiveDiagnosticTest extends AbstractDiagnosticTest< @Test void test() { - List diagnostics = getDiagnostics(); + List diagnostics; + Map configuration; - assertThat(diagnostics) - .hasSize(3) - .anyMatch(diagnostic -> diagnostic.getRange().equals( - Ranges.create(0, 8, 0, 23))) - .anyMatch(diagnostic -> diagnostic.getRange().equals( - Ranges.create(25, 8, 25, 14))) - .anyMatch(diagnostic -> diagnostic.getRange().equals( - Ranges.create(35, 8, 35, 17))); + // Проверяем срабатывания с параметрами по умолчанию + // when + configuration = diagnosticInstance.getInfo().getDefaultConfiguration(); + diagnosticInstance.configure(configuration); + diagnostics = getDiagnostics(); + + // then + assertThat(diagnostics, true) + .hasSize(4) + .hasRange(0, 8, 23) + .hasRange(25, 8, 14) + .hasRange(35, 8, 17) + .hasRange(62, 8, 22); + + // Проверяем с выключенным параметром checkAttachableMethods + // when + configuration = diagnosticInstance.getInfo().getDefaultConfiguration(); + configuration.put("checkAttachableMethods", false); + diagnosticInstance.configure(configuration); + diagnostics = getDiagnostics(); + + // then + assertThat(diagnostics, true) + .hasSize(6) + .hasRange(0, 8, 23) + .hasRange(25, 8, 14) + .hasRange(35, 8, 17) + .hasRange(52, 8, 35) + .hasRange(62, 8, 22) + .hasRange(72, 9, 32); } } diff --git a/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl b/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl index 046db69df92..d2d1c8ca1ce 100644 --- a/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl +++ b/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl @@ -60,6 +60,16 @@ КонецФункции +Функция КакаяТоКоманда(Команда) // <- ошибка + + Если ЗначениеЗаполнено(ТекущаяДата) Тогда + Возврат Null; + КонецЕсли; + + Возврат NULL; + +КонецФункции + Function Attachable_RandomAction(Command) If ValueIsFilled(CurrentDate) Then From 406078f2faa521663e0bc245bd226ab56d355776 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Tue, 28 Apr 2020 00:03:01 +0700 Subject: [PATCH 196/444] =?UTF-8?q?=D0=9F=D1=80=D0=B5=D0=BA=D0=BE=D0=BC?= =?UTF-8?q?=D0=BC=D0=B8=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/FunctionReturnsSamePrimitive.md | 10 +++++++++- docs/en/diagnostics/FunctionReturnsSamePrimitive.md | 10 +++++++++- .../configuration/parameters-schema.json | 8 ++++++++ .../bsl/languageserver/configuration/schema.json | 3 --- ...unctionReturnsSamePrimitiveDiagnostic_en.properties | 1 + ...unctionReturnsSamePrimitiveDiagnostic_ru.properties | 1 + 6 files changed, 28 insertions(+), 5 deletions(-) diff --git a/docs/diagnostics/FunctionReturnsSamePrimitive.md b/docs/diagnostics/FunctionReturnsSamePrimitive.md index 41eb85dc3d6..03bc179021a 100644 --- a/docs/diagnostics/FunctionReturnsSamePrimitive.md +++ b/docs/diagnostics/FunctionReturnsSamePrimitive.md @@ -4,6 +4,12 @@ | :-: | :-: | :-: | :-: | :-: | :-: | | `Ошибка` | `BSL`
`OS` | `Важный` | `Да` | `5` | `design`
`badpractice` | +## Параметры + +| Имя | Тип | Описание | Значение по умолчанию | +| :-: | :-: | :-- | :-: | +| `checkAttachableMethods` | `Булево` | ```Проверять подключаемые методы``` | ```true``` | + ## Описание диагностики @@ -82,5 +88,7 @@ ### Параметр конфигурационного файла ```json -"FunctionReturnsSamePrimitive": false +"FunctionReturnsSamePrimitive": { + "checkAttachableMethods": true +} ``` diff --git a/docs/en/diagnostics/FunctionReturnsSamePrimitive.md b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md index 01ac1e2515f..d78f5bf2663 100644 --- a/docs/en/diagnostics/FunctionReturnsSamePrimitive.md +++ b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md @@ -4,6 +4,12 @@ | :-: | :-: | :-: | :-: | :-: | :-: | | `Error` | `BSL`
`OS` | `Major` | `Yes` | `5` | `design`
`badpractice` | +## Parameters + +| Name | Type | Description | Default value | +| :-: | :-: | :-- | :-: | +| `checkAttachableMethods` | `Boolean` | ```Check attachable methods``` | ```true``` | + ## Description @@ -82,5 +88,7 @@ EndFunction ### Parameter for config ```json -"FunctionReturnsSamePrimitive": false +"FunctionReturnsSamePrimitive": { + "checkAttachableMethods": true +} ``` diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index 2830240940e..f20a2b36c8c 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -362,6 +362,14 @@ "object" ], "title": "The function always returns the same primitive value", + "properties": { + "checkAttachableMethods": { + "description": "Check attachable methods", + "default": true, + "type": "boolean", + "title": "Check attachable methods" + } + }, "$id": "#/definitions/FunctionReturnsSamePrimitive" }, "FunctionShouldHaveReturn": { diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 4f0285d425d..5fa984b3ec9 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -113,9 +113,6 @@ "FunctionReturnsSamePrimitive": { "$ref": "parameters-schema.json#/definitions/FunctionReturnsSamePrimitive" }, - "FunctionReturnsSamePrimitive": { - "$ref": "diagnostics-schema.json#/definitions/FunctionReturnsSamePrimitive" - }, "FunctionShouldHaveReturn": { "$ref": "parameters-schema.json#/definitions/FunctionShouldHaveReturn" }, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties index fb0ac7ddbfc..d7f0db77485 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties @@ -1,3 +1,4 @@ diagnosticMessage=Check that the same primitive value is returned in the function diagnosticName=The function always returns the same primitive value diagnosticMessageReturnStatement=Repeat return value +checkAttachableMethods=Check attachable methods diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties index 2ac2ec79e1b..3143159f75c 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties @@ -1,3 +1,4 @@ diagnosticMessage=Проверьте правильность возврата одного и того же примитивного значения в функции diagnosticName=Функция всегда возвращает одно и то же примитивное значение diagnosticMessageReturnStatement=Повтор возвращаемого значения +checkAttachableMethods=Проверять подключаемые методы From ccbc9212c28de9a81e4c5c5319079e0cc9a87894 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Tue, 28 Apr 2020 10:38:29 +0700 Subject: [PATCH 197/444] =?UTF-8?q?=D0=BE=D0=BF=D1=86=D0=B8=D1=8F=20=D0=BD?= =?UTF-8?q?=D0=B0=20=D1=80=D0=B5=D0=B3=D0=B8=D1=81=D1=82=D1=80=20=D0=B4?= =?UTF-8?q?=D0=BB=D1=8F=20=D1=81=D1=82=D1=80=D0=BE=D0=BA,=20=D1=80=D0=B5?= =?UTF-8?q?=D0=BD=D0=B5=D0=B9=D0=BC=20=D0=BE=D0=BF=D1=86=D0=B8=D0=B8=20?= =?UTF-8?q?=D0=BF=D0=BE=20=D0=BF=D0=BE=D0=B4=D0=BA=D0=BB=D1=8E=D1=87=D0=B0?= =?UTF-8?q?=D0=B5=D0=BC=D1=8B=D0=BC,=20=D1=80=D0=B0=D1=81=D1=88=D0=B8?= =?UTF-8?q?=D1=80=D0=B5=D0=BD=D1=8B=20=D1=82=D0=B5=D1=81=D1=82=D1=8B.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FunctionReturnsSamePrimitive.md | 6 ++- .../FunctionReturnsSamePrimitive.md | 6 ++- ...unctionReturnsSamePrimitiveDiagnostic.java | 40 ++++++++++++------- .../configuration/parameters-schema.json | 12 ++++-- ...turnsSamePrimitiveDiagnostic_en.properties | 3 +- ...turnsSamePrimitiveDiagnostic_ru.properties | 3 +- ...ionReturnsSamePrimitiveDiagnosticTest.java | 29 +++++++++++--- ...FunctionReturnsSamePrimitiveDiagnostic.bsl | 7 ++-- 8 files changed, 72 insertions(+), 34 deletions(-) diff --git a/docs/diagnostics/FunctionReturnsSamePrimitive.md b/docs/diagnostics/FunctionReturnsSamePrimitive.md index 03bc179021a..fe18bf533df 100644 --- a/docs/diagnostics/FunctionReturnsSamePrimitive.md +++ b/docs/diagnostics/FunctionReturnsSamePrimitive.md @@ -8,7 +8,8 @@ | Имя | Тип | Описание | Значение по умолчанию | | :-: | :-: | :-- | :-: | -| `checkAttachableMethods` | `Булево` | ```Проверять подключаемые методы``` | ```true``` | +| `skipAttachable` | `Булево` | ```Не учитывать подключаемые методы``` | ```true``` | +| `caseSensitiveForString` | `Булево` | ```Учитывать регистр в строковых значениях``` | ```false``` | ## Описание диагностики @@ -89,6 +90,7 @@ ```json "FunctionReturnsSamePrimitive": { - "checkAttachableMethods": true + "skipAttachable": true, + "caseSensitiveForString": false } ``` diff --git a/docs/en/diagnostics/FunctionReturnsSamePrimitive.md b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md index d78f5bf2663..b51a70af555 100644 --- a/docs/en/diagnostics/FunctionReturnsSamePrimitive.md +++ b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md @@ -8,7 +8,8 @@ | Name | Type | Description | Default value | | :-: | :-: | :-- | :-: | -| `checkAttachableMethods` | `Boolean` | ```Check attachable methods``` | ```true``` | +| `skipAttachable` | `Boolean` | ```Ignore attachable methods``` | ```true``` | +| `caseSensitiveForString` | `Boolean` | ```Case sensitive for strings``` | ```false``` | ## Description @@ -89,6 +90,7 @@ EndFunction ```json "FunctionReturnsSamePrimitive": { - "checkAttachableMethods": true + "skipAttachable": true, + "caseSensitiveForString": false } ``` diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java index 010a338418c..0f6f2e754ae 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java @@ -60,13 +60,20 @@ public class FunctionReturnsSamePrimitiveDiagnostic extends AbstractVisitorDiagn private static final Pattern pattern = Pattern.compile( "^(подключаемый|attachable)_", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); - private static final boolean CHECK_ATTACHABLE_METHODS = true; + private static final boolean SKIP_ATTACHABLE = true; + private static final boolean CASE_SENSITIVE_FOR_STRING = false; @DiagnosticParameter( type = Boolean.class, - defaultValue = "" + CHECK_ATTACHABLE_METHODS + defaultValue = "" + SKIP_ATTACHABLE ) - private boolean checkAttachableMethods = CHECK_ATTACHABLE_METHODS; + private boolean skipAttachable = SKIP_ATTACHABLE; + + @DiagnosticParameter( + type = Boolean.class, + defaultValue = "" + CASE_SENSITIVE_FOR_STRING + ) + private boolean caseSensitiveForString = CASE_SENSITIVE_FOR_STRING; public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { super(info); @@ -75,7 +82,7 @@ public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { @Override public ParseTree visitFunction(BSLParser.FunctionContext ctx) { - if (checkAttachableMethods) { + if (skipAttachable) { // Исключаем подключаемые методы var abortCheck = Optional.ofNullable(ctx.funcDeclaration()) .map(BSLParser.FuncDeclarationContext::subName) @@ -108,16 +115,12 @@ public ParseTree visitFunction(BSLParser.FunctionContext ctx) { private void checkPrimitiveValue( BSLParser.FunctionContext ctx, Collection tree, List expressions) { - var set = expressions.stream() - .map((BSLParser.ExpressionContext expression) -> { - var text = expression.getText(); - if (Trees.findAllRuleNodes(expression, BSLParser.RULE_string).isEmpty()) { - text = text.toUpperCase(Locale.ENGLISH); - } - return text; - }) - .collect(Collectors.toSet()); - if (set.size() == 1) { + var count = expressions.stream() + .map(this::getExpressionText) + .distinct() + .count(); + + if (count == 1) { var relatedInformation = tree.stream() .map(BSLParser.ReturnStatementContext.class::cast) .map(statement -> RelatedInformation.create( @@ -125,11 +128,18 @@ private void checkPrimitiveValue( Ranges.create(statement.getStart()), info.getResourceString(KEY_MESSAGE))) .collect(Collectors.toList()); - diagnosticStorage.addDiagnostic(getSubNameRange(ctx), info.getMessage(), relatedInformation); + diagnosticStorage.addDiagnostic(getSubNameRange(ctx), relatedInformation); } } + private String getExpressionText(BSLParser.ExpressionContext expression) { + if (caseSensitiveForString && Trees.nodeContains(expression, BSLParser.RULE_string)) { + return expression.getText(); + } + return expression.getText().toUpperCase(Locale.ENGLISH); + } + private Range getSubNameRange(ParserRuleContext ctx) { return Optional.ofNullable(Trees.getAncestorByRuleIndex(ctx, BSLParser.RULE_sub)) .map(BSLParser.SubContext.class::cast) diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index f20a2b36c8c..2c6ba1dd70d 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -363,11 +363,17 @@ ], "title": "The function always returns the same primitive value", "properties": { - "checkAttachableMethods": { - "description": "Check attachable methods", + "skipAttachable": { + "description": "Ignore attachable methods", "default": true, "type": "boolean", - "title": "Check attachable methods" + "title": "Ignore attachable methods" + }, + "caseSensitiveForString": { + "description": "Case sensitive for strings", + "default": false, + "type": "boolean", + "title": "Case sensitive for strings" } }, "$id": "#/definitions/FunctionReturnsSamePrimitive" diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties index d7f0db77485..4be88d7f729 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties @@ -1,4 +1,5 @@ diagnosticMessage=Check that the same primitive value is returned in the function diagnosticName=The function always returns the same primitive value diagnosticMessageReturnStatement=Repeat return value -checkAttachableMethods=Check attachable methods +skipAttachable=Ignore attachable methods +caseSensitiveForString=Case sensitive for strings diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties index 3143159f75c..eadc148c869 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties @@ -1,4 +1,5 @@ diagnosticMessage=Проверьте правильность возврата одного и того же примитивного значения в функции diagnosticName=Функция всегда возвращает одно и то же примитивное значение diagnosticMessageReturnStatement=Повтор возвращаемого значения -checkAttachableMethods=Проверять подключаемые методы +skipAttachable=Не учитывать подключаемые методы +caseSensitiveForString=Учитывать регистр в строковых значениях diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java index 7bc3af568ce..00fd8cafb34 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java @@ -48,28 +48,45 @@ void test() { // then assertThat(diagnostics, true) - .hasSize(4) + .hasSize(5) .hasRange(0, 8, 23) .hasRange(25, 8, 14) .hasRange(35, 8, 17) - .hasRange(62, 8, 22); + .hasRange(62, 8, 22) + .hasRange(82, 8, 32); - // Проверяем с выключенным параметром checkAttachableMethods + // Проверяем с выключенным параметром skipAttachable // when configuration = diagnosticInstance.getInfo().getDefaultConfiguration(); - configuration.put("checkAttachableMethods", false); + configuration.put("skipAttachable", false); diagnosticInstance.configure(configuration); diagnostics = getDiagnostics(); // then assertThat(diagnostics, true) - .hasSize(6) + .hasSize(7) .hasRange(0, 8, 23) .hasRange(25, 8, 14) .hasRange(35, 8, 17) .hasRange(52, 8, 35) .hasRange(62, 8, 22) - .hasRange(72, 9, 32); + .hasRange(72, 9, 32) + .hasRange(82, 8, 32); + + // Проверяем с включенным параметром caseSensitiveForString + // when + configuration = diagnosticInstance.getInfo().getDefaultConfiguration(); + configuration.put("caseSensitiveForString", true); + diagnosticInstance.configure(configuration); + diagnostics = getDiagnostics(); + + // then + assertThat(diagnostics, true) + .hasSize(4) + .hasRange(0, 8, 23) + .hasRange(25, 8, 14) + .hasRange(35, 8, 17) + .hasRange(62, 8, 22); } } diff --git a/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl b/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl index d2d1c8ca1ce..df2cf3995b3 100644 --- a/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl +++ b/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl @@ -50,7 +50,7 @@ Возврат Значение; КонецФункции -Функция Подключаемый_КакаяТоКоманда(Команда) +Функция Подключаемый_КакаяТоКоманда(Команда) // <- ошибки (опционально) Если ЗначениеЗаполнено(ТекущаяДата) Тогда Возврат Null; @@ -70,7 +70,7 @@ КонецФункции -Function Attachable_RandomAction(Command) +Function Attachable_RandomAction(Command) // <- ошибки (опционально) If ValueIsFilled(CurrentDate) Then Return Undefined; @@ -80,8 +80,7 @@ Function Attachable_RandomAction(Command) EndFunction -// тут нет ошибки -Функция ПроверкаРегистраДляСтрок() +Функция ПроверкаРегистраДляСтрок() // <- ошибки (опционально) Тип = 1; Если Тип = 1 Тогда From e78235cee50d99f5f0ab7bac98002239ff3fd5de Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sat, 25 Apr 2020 23:29:52 +0700 Subject: [PATCH 198/444] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B2=D0=BE=D0=B5=20?= =?UTF-8?q?=D0=BF=D1=80=D0=B8=D0=B1=D0=BB=D0=B8=D0=B6=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...unctionReturnsSamePrimitiveDiagnostic.java | 68 +++++++++++++++++++ ...turnsSamePrimitiveDiagnostic_en.properties | 2 + ...turnsSamePrimitiveDiagnostic_ru.properties | 2 + ...ionReturnsSamePrimitiveDiagnosticTest.java | 23 +++++++ .../FunctionReturnsSameValueDiagnostic.bsl | 52 ++++++++++++++ 5 files changed, 147 insertions(+) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java new file mode 100644 index 00000000000..6c7c1c750b4 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java @@ -0,0 +1,68 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.languageserver.utils.RelatedInformation; +import com.github._1c_syntax.bsl.languageserver.utils.Trees; +import com.github._1c_syntax.bsl.parser.BSLLexer; +import com.github._1c_syntax.bsl.parser.BSLParser; +import org.antlr.v4.runtime.tree.ParseTree; +import org.checkerframework.checker.nullness.Opt; +import org.eclipse.lsp4j.DiagnosticRelatedInformation; + +import javax.tools.Diagnostic; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collector; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@DiagnosticMetadata( + type = DiagnosticType.ERROR, + severity = DiagnosticSeverity.INFO, + minutesToFix = 1, + tags = { + DiagnosticTag.BADPRACTICE + } + +) +public class FunctionReturnsSamePrimitiveDiagnostic extends AbstractVisitorDiagnostic { + public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + public ParseTree visitFunction(BSLParser.FunctionContext ctx) { + var tree = Trees.findAllRuleNodes(ctx, BSLParser.RULE_returnStatement); + if (tree.size() > 1){ + var set = tree.stream() + .map(BSLParser.ReturnStatementContext.class::cast) + .map(BSLParser.ReturnStatementContext::expression) + .flatMap(Stream::ofNullable) + .map(BSLParser.ExpressionContext::getText) + .collect(Collectors.toSet()); + if (set.size() == 1) { + var relatedInformation = tree.stream() + .map(BSLParser.ReturnStatementContext.class::cast) + .map(statement -> + RelatedInformation.create( + documentContext.getUri(), + Ranges.create(statement.getStart()), + info.getMessage())) + .collect(Collectors.toList()); + diagnosticStorage.addDiagnostic(ctx.funcDeclaration(), info.getMessage(), relatedInformation); + } + } + return ctx; + } +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties new file mode 100644 index 00000000000..66831715dfd --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage= +diagnosticName= diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties new file mode 100644 index 00000000000..df22ba92595 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Проверьте правильность возврата одного и того жк значения в функции +diagnosticName=Функция всегда возвращает одно и то же значение diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java new file mode 100644 index 00000000000..1517ec60634 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java @@ -0,0 +1,23 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class FunctionReturnsSamePrimitiveDiagnosticTest extends AbstractDiagnosticTest { + FunctionReturnsSamePrimitiveDiagnosticTest() { + super(FunctionReturnsSamePrimitiveDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(4); + + } +} diff --git a/src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl b/src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl new file mode 100644 index 00000000000..c8e246d08f3 --- /dev/null +++ b/src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl @@ -0,0 +1,52 @@ +Функция ПроверитьСтроку(Знач СтрокаТаблицы) // <-- ошибка + Если ЭтоХорошаяСтрока(СтрокаТаблицы) Тогда + ДелаемЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + Возврат Истина; + ИначеЕсли ЭтоТожеНеплохаяСтрока(СтрокаТаблицы) Тогда + ДелаемДругоеЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + Возврат Истина; + Иначе + Возврат Истина; + КонецЕсли; +КонецФункции + +Функция БудемТестироватьФункциональность() + Возврат Ложь; +КонецФункции + +Функция ВернутьСтроку() + Возврат "Истина"; +КонецФункции + +Процедура СделаемЧтоНибудь() + Значение = Истина; + Возврат; +КонецПроцедуры + +Функция Метод1() // <-- ошибка + Значение = "Фича"; + Если Фича = "Дирижабль" Тогда + Возврат "Фича"; + ИначеЕсли Фича = "Ага" Тогда + Возврат "Фича"; + КонецЕсли; + Возврат "Фича"; +КонецФункции + +Функция СтавкаНДС(Ставка) // <-- ошибка + Значение = 20; + Если Ставка = "Ставка18" Тогда + Возврат 20; + КонецЕсли; + Возврат 20; +КонецФункции + +// надо бы подумать как правильно диагностировать +// по идее ошибка +Функция СтавкаНДС2(Ставка) + Значение = 20; + Если Ставка = "Ставка18" Тогда + Возврат Значение; + КонецЕсли; + Возврат Значение; +КонецФункции \ No newline at end of file From 3a8ad5cb8452122a925bd3ed985a6e3e3c025203 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sun, 26 Apr 2020 01:23:36 +0700 Subject: [PATCH 199/444] =?UTF-8?q?=D0=98=D1=81=D0=BA=D0=BB=D1=8E=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BD=D0=B5=20=D0=BF=D1=80=D0=B8?= =?UTF-8?q?=D0=BC=D0=B8=D1=82=D0=B8=D0=B2=D0=BE=D0=B2,=20=D0=B4=D0=BE?= =?UTF-8?q?=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5=D0=BD=D0=B0=20=D0=B4=D0=BE=D0=BA?= =?UTF-8?q?=D1=83=D0=BC=D0=B5=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D1=8F=20=D0=BD?= =?UTF-8?q?=D0=B0=20ru,=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B8=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5=20=D0=B8=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=20=D1=84=D0=B0=D0=B9=D0=BB=D0=B0=20=D0=BA=D0=B5=D0=B9?= =?UTF-8?q?=D1=81=D0=B0=20=D0=B4=D0=BB=D1=8F=20=D1=82=D0=B5=D1=81=D1=82?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FunctionReturnsSamePrimitive.md | 71 ++++++++++++++ .../FunctionReturnsSamePrimitive.md | 36 +++++++ ...unctionReturnsSamePrimitiveDiagnostic.java | 96 +++++++++++++------ ...turnsSamePrimitiveDiagnostic_en.properties | 5 +- ...turnsSamePrimitiveDiagnostic_ru.properties | 5 +- ...ionReturnsSamePrimitiveDiagnosticTest.java | 10 +- ...unctionReturnsSamePrimitiveDiagnostic.bsl} | 3 +- 7 files changed, 192 insertions(+), 34 deletions(-) create mode 100644 docs/diagnostics/FunctionReturnsSamePrimitive.md create mode 100644 docs/en/diagnostics/FunctionReturnsSamePrimitive.md rename src/test/resources/diagnostics/{FunctionReturnsSameValueDiagnostic.bsl => FunctionReturnsSamePrimitiveDiagnostic.bsl} (94%) diff --git a/docs/diagnostics/FunctionReturnsSamePrimitive.md b/docs/diagnostics/FunctionReturnsSamePrimitive.md new file mode 100644 index 00000000000..464ba00e5f5 --- /dev/null +++ b/docs/diagnostics/FunctionReturnsSamePrimitive.md @@ -0,0 +1,71 @@ +# Функция всегда возвращает одно и то же примитивное значение () + + + +## + + +## Описание диагностики + + +Функция не должна возвращать одно и тоже примитивное значение. Если результат функции не учитывается - то нужно функцию +переписать на процедуру. + +## Примеры + + +Плохо: +```bsl +Функция ПроверитьСтроку(Знач СтрокаТаблицы) + + Если ЭтоХорошаяСтрока(СтрокаТаблицы) Тогда + ДелаемЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + Возврат Истина; + ИначеЕсли ЭтоТожеНеплохаяСтрока(СтрокаТаблицы) Тогда + ДелаемДругоеЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + Возврат Истина; + Иначе + Возврат Истина; + КонецЕсли; + +КонецФункции +``` + +Хорошо: +```bsl +Процедура ПроверитьСтроку(Знач СтрокаТаблицы) + + Если ЭтоХорошаяСтрока(СтрокаТаблицы) Тогда + ДелаемЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + ИначеЕсли ЭтоТожеНеплохаяСтрока(СтрокаТаблицы) Тогда + ДелаемДругоеЧтоТоЧтобыНеРугаласьПроверкаНаПовтор(); + Иначе + ДелаемЧтотоДругоеИзВеткиИначе(); + КонецЕсли; + +КонецПроцедуры +``` + +## Источники + + + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Параметр конфигурационного файла + +```json +"": +``` \ No newline at end of file diff --git a/docs/en/diagnostics/FunctionReturnsSamePrimitive.md b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md new file mode 100644 index 00000000000..4e7e0f78ada --- /dev/null +++ b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md @@ -0,0 +1,36 @@ +# + + + +## + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Parameter for config + +```json +"": +``` diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java index 6c7c1c750b4..c0dc94b38af 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java @@ -1,5 +1,27 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; @@ -8,35 +30,31 @@ import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import com.github._1c_syntax.bsl.languageserver.utils.RelatedInformation; import com.github._1c_syntax.bsl.languageserver.utils.Trees; -import com.github._1c_syntax.bsl.parser.BSLLexer; import com.github._1c_syntax.bsl.parser.BSLParser; +import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; -import org.checkerframework.checker.nullness.Opt; -import org.eclipse.lsp4j.DiagnosticRelatedInformation; +import org.eclipse.lsp4j.Range; -import javax.tools.Diagnostic; -import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; import java.util.List; -import java.util.Objects; import java.util.Optional; -import java.util.Set; -import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.Stream; @DiagnosticMetadata( type = DiagnosticType.ERROR, - severity = DiagnosticSeverity.INFO, - minutesToFix = 1, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 5, tags = { + DiagnosticTag.DESIGN, DiagnosticTag.BADPRACTICE } ) public class FunctionReturnsSamePrimitiveDiagnostic extends AbstractVisitorDiagnostic { + + private static final String KEY_MESSAGE = "diagnosticMessageReturnStatement"; + public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { super(info); } @@ -44,25 +62,49 @@ public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { @Override public ParseTree visitFunction(BSLParser.FunctionContext ctx) { var tree = Trees.findAllRuleNodes(ctx, BSLParser.RULE_returnStatement); - if (tree.size() > 1){ - var set = tree.stream() + if (tree.size() > 1) { + var expressions = tree.stream() .map(BSLParser.ReturnStatementContext.class::cast) .map(BSLParser.ReturnStatementContext::expression) .flatMap(Stream::ofNullable) - .map(BSLParser.ExpressionContext::getText) - .collect(Collectors.toSet()); - if (set.size() == 1) { - var relatedInformation = tree.stream() - .map(BSLParser.ReturnStatementContext.class::cast) - .map(statement -> - RelatedInformation.create( - documentContext.getUri(), - Ranges.create(statement.getStart()), - info.getMessage())) - .collect(Collectors.toList()); - diagnosticStorage.addDiagnostic(ctx.funcDeclaration(), info.getMessage(), relatedInformation); - } + .collect(Collectors.toList()); + + expressions.stream() + .map(expression -> Trees.findAllRuleNodes(expression, BSLParser.RULE_complexIdentifier)) + .filter(Collection::isEmpty) + .findAny() + .ifPresent( + parseTrees -> checkPrimitiveValue(ctx, tree, expressions) + ); } return ctx; } + + private void checkPrimitiveValue( + BSLParser.FunctionContext ctx, Collection tree, List expressions) { + + var set = expressions.stream().map(BSLParser.ExpressionContext::getText).collect(Collectors.toSet()); + if (set.size() == 1) { + var relatedInformation = tree.stream() + .map(BSLParser.ReturnStatementContext.class::cast) + .map(statement -> RelatedInformation.create( + documentContext.getUri(), + Ranges.create(statement.getStart()), + info.getResourceString(KEY_MESSAGE))) + .collect(Collectors.toList()); + diagnosticStorage.addDiagnostic(getSubNameRange(ctx), info.getMessage(), relatedInformation); + } + + } + + private Range getSubNameRange(ParserRuleContext ctx) { + return Optional.ofNullable(Trees.getAncestorByRuleIndex(ctx, BSLParser.RULE_sub)) + .map(BSLParser.SubContext.class::cast) + .map(context -> documentContext.getSymbolTree().getMethodSymbol(context)) + .filter(Optional::isPresent) + .map(Optional::get) + .map(MethodSymbol::getSubNameRange) + .orElse(Ranges.create(ctx.getStart())); + } + } diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties index 66831715dfd..fb0ac7ddbfc 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties @@ -1,2 +1,3 @@ -diagnosticMessage= -diagnosticName= +diagnosticMessage=Check that the same primitive value is returned in the function +diagnosticName=The function always returns the same primitive value +diagnosticMessageReturnStatement=Repeat return value diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties index df22ba92595..2ac2ec79e1b 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties @@ -1,2 +1,3 @@ -diagnosticMessage=Проверьте правильность возврата одного и того жк значения в функции -diagnosticName=Функция всегда возвращает одно и то же значение +diagnosticMessage=Проверьте правильность возврата одного и того же примитивного значения в функции +diagnosticName=Функция всегда возвращает одно и то же примитивное значение +diagnosticMessageReturnStatement=Повтор возвращаемого значения diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java index 1517ec60634..1af20cc2524 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java @@ -1,5 +1,6 @@ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; @@ -17,7 +18,14 @@ void test() { List diagnostics = getDiagnostics(); - assertThat(diagnostics).hasSize(4); + assertThat(diagnostics) + .hasSize(3) + .anyMatch(diagnostic -> diagnostic.getRange().equals( + Ranges.create(0, 8, 0, 23))) + .anyMatch(diagnostic -> diagnostic.getRange().equals( + Ranges.create(25, 8, 25, 14))) + .anyMatch(diagnostic -> diagnostic.getRange().equals( + Ranges.create(35, 8, 35, 17))); } } diff --git a/src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl b/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl similarity index 94% rename from src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl rename to src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl index c8e246d08f3..66f0df2975e 100644 --- a/src/test/resources/diagnostics/FunctionReturnsSameValueDiagnostic.bsl +++ b/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl @@ -41,8 +41,7 @@ Возврат 20; КонецФункции -// надо бы подумать как правильно диагностировать -// по идее ошибка +// здесь нет ошибки, т.к. проверка только на примитивы Функция СтавкаНДС2(Ставка) Значение = 20; Если Ставка = "Ставка18" Тогда From e2f0d2777eb05e17622e2369ff509b16e240555e Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Tue, 28 Apr 2020 13:21:12 +0700 Subject: [PATCH 200/444] no message --- .../FunctionReturnsSamePrimitive.md | 18 +++---- docs/diagnostics/index.md | 22 ++------ .../FunctionReturnsSamePrimitive.md | 51 ++++++++++++++++--- docs/en/diagnostics/index.md | 22 ++------ .../configuration/parameters-schema.json | 10 ++++ .../languageserver/configuration/schema.json | 3 ++ ...ionReturnsSamePrimitiveDiagnosticTest.java | 21 ++++++++ 7 files changed, 96 insertions(+), 51 deletions(-) diff --git a/docs/diagnostics/FunctionReturnsSamePrimitive.md b/docs/diagnostics/FunctionReturnsSamePrimitive.md index 464ba00e5f5..cbd70345b65 100644 --- a/docs/diagnostics/FunctionReturnsSamePrimitive.md +++ b/docs/diagnostics/FunctionReturnsSamePrimitive.md @@ -1,8 +1,8 @@ -# Функция всегда возвращает одно и то же примитивное значение () +# Функция всегда возвращает одно и то же примитивное значение (FunctionReturnsSamePrimitive) - - -## +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Ошибка` | `BSL`
`OS` | `Важный` | `Да` | `5` | `design`
`badpractice` | ## Описание диагностики @@ -55,17 +55,17 @@ * Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) --> ## Сниппеты - + ### Экранирование кода ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:FunctionReturnsSamePrimitive-off +// BSLLS:FunctionReturnsSamePrimitive-on ``` ### Параметр конфигурационного файла ```json -"": -``` \ No newline at end of file +"FunctionReturnsSamePrimitive": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 811b796be66..0fab59f2d5f 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,12 +8,12 @@ ## Список реализованных диагностик -Общее количество: **101** +Общее количество: **89** -* Дефект кода: **65** +* Дефект кода: **55** * Уязвимость: **2** -* Ошибка: **31** -* Потенциальная уязвимость: **3** +* Ошибка: **30** +* Потенциальная уязвимость: **2** | Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги | | --- | --- | :-: | --- | --- | --- | @@ -24,35 +24,23 @@ | [CognitiveComplexity](CognitiveComplexity.md) | Когнитивная сложность | Да | Критичный | Дефект кода | `brainoverload` | | [CommentedCode](CommentedCode.md) | Закомментированный фрагмент кода | Да | Незначительный | Дефект кода | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Нарушение правил работы с транзакциями для метода 'ЗафиксироватьТранзакцию' | Да | Важный | Ошибка | `standard` | -| [CommonModuleAssign](CommonModuleAssign.md) | Присвоение общему модулю | Да | Блокирующий | Ошибка | `error` | -| [CommonModuleNameCached](CommonModuleNameCached.md) | Пропущен постфикс "ПовтИсп" | Да | Важный | Дефект кода | `standard`
`badpractice`
`unpredictable` | -| [CommonModuleNameClient](CommonModuleNameClient.md) | Пропущен постфикс "Клиент" | Да | Незначительный | Дефект кода | `standard`
`badpractice`
`unpredictable` | -| [CommonModuleNameClientServer](CommonModuleNameClientServer.md) | Пропущен постфикс "КлиентСервер" | Да | Важный | Дефект кода | `standard`
`badpractice`
`unpredictable` | -| [CommonModuleNameFullAccess](CommonModuleNameFullAccess.md) | Пропущен постфикс "ПолныеПрава" | Да | Важный | Потенциальная уязвимость | `standard`
`badpractice`
`unpredictable` | -| [CommonModuleNameGlobal](CommonModuleNameGlobal.md) | Пропущен постфикс "Глобальный" | Да | Важный | Дефект кода | `standard`
`badpractice`
`brainoverload` | -| [CommonModuleNameGlobalClient](CommonModuleNameGlobalClient.md) | Глобальный модуль с постфиксом "Клиент" | Да | Важный | Дефект кода | `standard` | -| [CommonModuleNameServerCall](CommonModuleNameServerCall.md) | Пропущен постфикс "ВызовСервера" | Да | Незначительный | Дефект кода | `standard`
`badpractice`
`unpredictable` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Директивы компиляции методов | Да | Важный | Дефект кода | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Лишняя директива компиляции | Да | Важный | Дефект кода | `clumsy`
`standard`
`unpredictable` | -| [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Подряд идущие пустые строки | Да | Информационный | Дефект кода | `badpractice` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Выполнение запроса в цикле | Да | Критичный | Ошибка | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Цикломатическая сложность | Да | Критичный | Дефект кода | `brainoverload` | -| [DataExchangeLoading](DataExchangeLoading.md) | Отсутствует проверка признака ОбменДанными.Загрузка в обработчике событий объекта | Да | Критичный | Ошибка | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Удаление элемента при обходе коллекции посредством оператора "Для каждого ... Из ... Цикл" | Да | Важный | Ошибка | `standard`
`error` | -| [DeprecatedAttributes8312](DeprecatedAttributes8312.md) | Устаревшие объекты платформы 8.3.12 | Да | Информационный | Дефект кода | `deprecated` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Использование устаревшего метода "ТекущаяДата" | Да | Важный | Ошибка | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Использование устаревшего метода "Найти" | Да | Незначительный | Дефект кода | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Ограничение на использование устаревшего метода "Сообщить" | Да | Незначительный | Дефект кода | `standard`
`deprecated` | -| [DeprecatedMethods8310](DeprecatedMethods8310.md) | Использование устаревшего метода клиентского приложения | Да | Информационный | Дефект кода | `deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Устаревшее использование типа "УправляемаяФорма" | Да | Информационный | Дефект кода | `standard`
`deprecated` | | [DuplicateRegion](DuplicateRegion.md) | Повторяющиеся разделы модуля | Да | Информационный | Дефект кода | `standard` | | [EmptyCodeBlock](EmptyCodeBlock.md) | Пустой блок кода | Да | Важный | Дефект кода | `badpractice`
`suspicious` | | [EmptyRegion](EmptyRegion.md) | Область не должна быть пустой | Да | Информационный | Дефект кода | `standard` | | [EmptyStatement](EmptyStatement.md) | Пустой оператор | Да | Информационный | Дефект кода | `badpractice` | -| [ExcessiveAutoTestCheck](ExcessiveAutoTestCheck.md) | Избыточная проверка параметра АвтоТест | Да | Незначительный | Дефект кода | `standard`
`deprecated` | | [ExtraCommas](ExtraCommas.md) | Запятые без указания параметра в конце вызова метода | Да | Важный | Дефект кода | `standard`
`badpractice` | | [FormDataToValue](FormDataToValue.md) | Использование метода ДанныеФормыВЗначение | Да | Информационный | Дефект кода | `badpractice` | | [FunctionNameStartsWithGet](FunctionNameStartsWithGet.md) | Имя функции не должно начинаться с "Получить" | Нет | Информационный | Дефект кода | `standard` | +| [FunctionReturnsSamePrimitive](FunctionReturnsSamePrimitive.md) | Функция всегда возвращает одно и то же примитивное значение | Да | Важный | Ошибка | `design`
`badpractice` | | [FunctionShouldHaveReturn](FunctionShouldHaveReturn.md) | Функция должна содержать возврат | Да | Важный | Ошибка | `suspicious`
`unpredictable` | | [GetFormMethod](GetFormMethod.md) | Использование метода ПолучитьФорму | Да | Важный | Ошибка | `error` | | [IdenticalExpressions](IdenticalExpressions.md) | Одинаковые выражения слева и справа от "foo" оператора | Да | Важный | Ошибка | `suspicious` | diff --git a/docs/en/diagnostics/FunctionReturnsSamePrimitive.md b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md index 4e7e0f78ada..a7b5d484497 100644 --- a/docs/en/diagnostics/FunctionReturnsSamePrimitive.md +++ b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md @@ -1,16 +1,51 @@ -# +# The function always returns the same primitive value (FunctionReturnsSamePrimitive) - - -## +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Error` | `BSL`
`OS` | `Major` | `Yes` | `5` | `design`
`badpractice` | ## Description +A function should not return the same primitive value. If the result of the function isn't use into code, then you need the function +rewrite to the procedure. + ## Examples +Bad: +```bsl +Function CheckString(Val RowTable) + + If ItsGoodString(RowTable) Then + ActionGood(); + Return True; + ElsIf ItsNodBadString(RowTable) Then + ActionNoBad(); + Return True; + Else + Return True; + EndIf; + +EndFunction +``` + +Good: +```bsl +Function CheckString(Val RowTable) + + If ItsGoodString(RowTable) Then + ActionGood(); + ElsIf ItsNodBadString(RowTable) Then + ActionNoBad(); + Else + ActionElse(); + EndIf; + +EndFunction +``` + ## Sources ## Snippets - + ### Diagnostic ignorance in code ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:FunctionReturnsSamePrimitive-off +// BSLLS:FunctionReturnsSamePrimitive-on ``` ### Parameter for config ```json -"": +"FunctionReturnsSamePrimitive": false ``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index e7561eff8e2..b22ab4029d5 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,12 +8,12 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **101** +Total: **89** -* Error: **31** -* Code smell: **65** +* Error: **30** +* Code smell: **55** * Vulnerability: **2** -* Security Hotspot: **3** +* Security Hotspot: **2** | Key | Name| Enabled by default | Severity | Type | Tags | | --- | --- | :-: | --- | --- | --- | @@ -24,35 +24,23 @@ Total: **101** | [CognitiveComplexity](CognitiveComplexity.md) | Cognitive complexity | Yes | Critical | Code smell | `brainoverload` | | [CommentedCode](CommentedCode.md) | Commented out code | Yes | Minor | Code smell | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Violating transaction rules for the 'CommitTransaction' method | Yes | Major | Error | `standard` | -| [CommonModuleAssign](CommonModuleAssign.md) | CommonModuleAssign | Yes | Blocker | Error | `error` | -| [CommonModuleNameCached](CommonModuleNameCached.md) | Missed postfix "Cached" | Yes | Major | Code smell | `standard`
`badpractice`
`unpredictable` | -| [CommonModuleNameClient](CommonModuleNameClient.md) | Missed postfix "Client" | Yes | Minor | Code smell | `standard`
`badpractice`
`unpredictable` | -| [CommonModuleNameClientServer](CommonModuleNameClientServer.md) | Missed postfix "ClientServer" | Yes | Major | Code smell | `standard`
`badpractice`
`unpredictable` | -| [CommonModuleNameFullAccess](CommonModuleNameFullAccess.md) | Missed postfix "FullAccess" | Yes | Major | Security Hotspot | `standard`
`badpractice`
`unpredictable` | -| [CommonModuleNameGlobal](CommonModuleNameGlobal.md) | Missed postfix "Global" | Yes | Major | Code smell | `standard`
`badpractice`
`brainoverload` | -| [CommonModuleNameGlobalClient](CommonModuleNameGlobalClient.md) | Global module with postfix "Client" | Yes | Major | Code smell | `standard` | -| [CommonModuleNameServerCall](CommonModuleNameServerCall.md) | Missed postfix "ServerCall" | Yes | Minor | Code smell | `standard`
`badpractice`
`unpredictable` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Methods compilation directive | Yes | Major | Code smell | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Needless compilation directive | Yes | Major | Code smell | `clumsy`
`standard`
`unpredictable` | -| [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Consecutive empty lines | Yes | Info | Code smell | `badpractice` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Execution query on cycle | Yes | Critical | Error | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Cyclomatic complexity | Yes | Critical | Code smell | `brainoverload` | -| [DataExchangeLoading](DataExchangeLoading.md) | There is no check for the attribute DataExchange.Load in the object's event handler | Yes | Critical | Error | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Deleting an item when iterating through collection using the operator "For each ... In ... Do" | Yes | Major | Error | `standard`
`error` | -| [DeprecatedAttributes8312](DeprecatedAttributes8312.md) | Deprecated 8.3.12 platform features. | Yes | Info | Code smell | `deprecated` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Using of the deprecated method "CurrentDate" | Yes | Major | Error | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Using of the deprecated method "Find" | Yes | Minor | Code smell | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Restriction on the use of deprecated "Message" method | Yes | Minor | Code smell | `standard`
`deprecated` | -| [DeprecatedMethods8310](DeprecatedMethods8310.md) | Deprecated client application method. | Yes | Info | Code smell | `deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Deprecated ManagedForm type | Yes | Info | Code smell | `standard`
`deprecated` | | [DuplicateRegion](DuplicateRegion.md) | Duplicate regions | Yes | Info | Code smell | `standard` | | [EmptyCodeBlock](EmptyCodeBlock.md) | Empty code block | Yes | Major | Code smell | `badpractice`
`suspicious` | | [EmptyRegion](EmptyRegion.md) | The region should not be empty | Yes | Info | Code smell | `standard` | | [EmptyStatement](EmptyStatement.md) | Empty statement | Yes | Info | Code smell | `badpractice` | -| [ExcessiveAutoTestCheck](ExcessiveAutoTestCheck.md) | Excessive AutoTest Check | Yes | Minor | Code smell | `standard`
`deprecated` | | [ExtraCommas](ExtraCommas.md) | Commas without a parameter at the end of a method call | Yes | Major | Code smell | `standard`
`badpractice` | | [FormDataToValue](FormDataToValue.md) | FormDataToValue method call | Yes | Info | Code smell | `badpractice` | | [FunctionNameStartsWithGet](FunctionNameStartsWithGet.md) | Function name shouldn't start with "Получить" | No | Info | Code smell | `standard` | +| [FunctionReturnsSamePrimitive](FunctionReturnsSamePrimitive.md) | The function always returns the same primitive value | Yes | Major | Error | `design`
`badpractice` | | [FunctionShouldHaveReturn](FunctionShouldHaveReturn.md) | The function should have return | Yes | Major | Error | `suspicious`
`unpredictable` | | [GetFormMethod](GetFormMethod.md) | GetForm method call | Yes | Major | Error | `error` | | [IdenticalExpressions](IdenticalExpressions.md) | There are identical sub-expressions to the left and to the right of the "foo" operator | Yes | Major | Error | `suspicious` | diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index 9be08e89978..415ffffb029 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -424,6 +424,16 @@ "title": "Function name shouldn't start with \"\u041f\u043e\u043b\u0443\u0447\u0438\u0442\u044c\"", "$id": "#/definitions/FunctionNameStartsWithGet" }, + "FunctionReturnsSamePrimitive": { + "description": "The function always returns the same primitive value", + "default": null, + "type": [ + "boolean", + "object" + ], + "title": "The function always returns the same primitive value", + "$id": "#/definitions/FunctionReturnsSamePrimitive" + }, "FunctionShouldHaveReturn": { "description": "The function should have return", "default": true, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 7b857252e49..613e032d3f2 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -131,6 +131,9 @@ "FunctionNameStartsWithGet": { "$ref": "parameters-schema.json#/definitions/FunctionNameStartsWithGet" }, + "FunctionReturnsSamePrimitive": { + "$ref": "diagnostics-schema.json#/definitions/FunctionReturnsSamePrimitive" + }, "FunctionShouldHaveReturn": { "$ref": "parameters-schema.json#/definitions/FunctionShouldHaveReturn" }, diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java index 1af20cc2524..b4d1a3cd769 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java @@ -1,3 +1,24 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; From c666ebf83d77160d59ec3c4c31e559356d1a952b Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sun, 26 Apr 2020 02:14:16 +0700 Subject: [PATCH 201/444] =?UTF-8?q?+=20=D0=BF=D1=80=D0=B5=D0=BA=D0=BE?= =?UTF-8?q?=D0=BC=D0=BC=D0=B8=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/index.md | 11 ++++++++--- docs/en/diagnostics/index.md | 11 ++++++++--- .../configuration/parameters-schema.json | 2 +- .../bsl/languageserver/configuration/schema.json | 2 +- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 0fab59f2d5f..2dfbde26f8d 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,11 +8,11 @@ ## Список реализованных диагностик -Общее количество: **89** +Общее количество: **94** -* Дефект кода: **55** +* Дефект кода: **58** * Уязвимость: **2** -* Ошибка: **30** +* Ошибка: **32** * Потенциальная уязвимость: **2** | Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги | @@ -24,19 +24,24 @@ | [CognitiveComplexity](CognitiveComplexity.md) | Когнитивная сложность | Да | Критичный | Дефект кода | `brainoverload` | | [CommentedCode](CommentedCode.md) | Закомментированный фрагмент кода | Да | Незначительный | Дефект кода | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Нарушение правил работы с транзакциями для метода 'ЗафиксироватьТранзакцию' | Да | Важный | Ошибка | `standard` | +| [CommonModuleAssign](CommonModuleAssign.md) | Присвоение общему модулю | Да | Блокирующий | Ошибка | `error` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Директивы компиляции методов | Да | Важный | Дефект кода | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Лишняя директива компиляции | Да | Важный | Дефект кода | `clumsy`
`standard`
`unpredictable` | +| [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Подряд идущие пустые строки | Да | Информационный | Дефект кода | `badpractice` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Выполнение запроса в цикле | Да | Критичный | Ошибка | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Цикломатическая сложность | Да | Критичный | Дефект кода | `brainoverload` | +| [DataExchangeLoading](DataExchangeLoading.md) | Отсутствует проверка признака ОбменДанными.Загрузка в обработчике событий объекта | Да | Критичный | Ошибка | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Удаление элемента при обходе коллекции посредством оператора "Для каждого ... Из ... Цикл" | Да | Важный | Ошибка | `standard`
`error` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Использование устаревшего метода "ТекущаяДата" | Да | Важный | Ошибка | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Использование устаревшего метода "Найти" | Да | Незначительный | Дефект кода | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Ограничение на использование устаревшего метода "Сообщить" | Да | Незначительный | Дефект кода | `standard`
`deprecated` | +| [DeprecatedMethods8310](DeprecatedMethods8310.md) | Использование устаревшего метода клиентского приложения | Да | Информационный | Дефект кода | `deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Устаревшее использование типа "УправляемаяФорма" | Да | Информационный | Дефект кода | `standard`
`deprecated` | | [DuplicateRegion](DuplicateRegion.md) | Повторяющиеся разделы модуля | Да | Информационный | Дефект кода | `standard` | | [EmptyCodeBlock](EmptyCodeBlock.md) | Пустой блок кода | Да | Важный | Дефект кода | `badpractice`
`suspicious` | | [EmptyRegion](EmptyRegion.md) | Область не должна быть пустой | Да | Информационный | Дефект кода | `standard` | | [EmptyStatement](EmptyStatement.md) | Пустой оператор | Да | Информационный | Дефект кода | `badpractice` | +| [ExcessiveAutoTestCheck](ExcessiveAutoTestCheck.md) | Избыточная проверка параметра АвтоТест | Да | Незначительный | Дефект кода | `standard`
`deprecated` | | [ExtraCommas](ExtraCommas.md) | Запятые без указания параметра в конце вызова метода | Да | Важный | Дефект кода | `standard`
`badpractice` | | [FormDataToValue](FormDataToValue.md) | Использование метода ДанныеФормыВЗначение | Да | Информационный | Дефект кода | `badpractice` | | [FunctionNameStartsWithGet](FunctionNameStartsWithGet.md) | Имя функции не должно начинаться с "Получить" | Нет | Информационный | Дефект кода | `standard` | diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index b22ab4029d5..2f31a4424d4 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,10 +8,10 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **89** +Total: **94** -* Error: **30** -* Code smell: **55** +* Error: **32** +* Code smell: **58** * Vulnerability: **2** * Security Hotspot: **2** @@ -24,19 +24,24 @@ Total: **89** | [CognitiveComplexity](CognitiveComplexity.md) | Cognitive complexity | Yes | Critical | Code smell | `brainoverload` | | [CommentedCode](CommentedCode.md) | Commented out code | Yes | Minor | Code smell | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Violating transaction rules for the 'CommitTransaction' method | Yes | Major | Error | `standard` | +| [CommonModuleAssign](CommonModuleAssign.md) | CommonModuleAssign | Yes | Blocker | Error | `error` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Methods compilation directive | Yes | Major | Code smell | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Needless compilation directive | Yes | Major | Code smell | `clumsy`
`standard`
`unpredictable` | +| [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Consecutive empty lines | Yes | Info | Code smell | `badpractice` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Execution query on cycle | Yes | Critical | Error | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Cyclomatic complexity | Yes | Critical | Code smell | `brainoverload` | +| [DataExchangeLoading](DataExchangeLoading.md) | There is no check for the attribute DataExchange.Load in the object's event handler | Yes | Critical | Error | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Deleting an item when iterating through collection using the operator "For each ... In ... Do" | Yes | Major | Error | `standard`
`error` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Using of the deprecated method "CurrentDate" | Yes | Major | Error | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Using of the deprecated method "Find" | Yes | Minor | Code smell | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Restriction on the use of deprecated "Message" method | Yes | Minor | Code smell | `standard`
`deprecated` | +| [DeprecatedMethods8310](DeprecatedMethods8310.md) | Deprecated client application method. | Yes | Info | Code smell | `deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Deprecated ManagedForm type | Yes | Info | Code smell | `standard`
`deprecated` | | [DuplicateRegion](DuplicateRegion.md) | Duplicate regions | Yes | Info | Code smell | `standard` | | [EmptyCodeBlock](EmptyCodeBlock.md) | Empty code block | Yes | Major | Code smell | `badpractice`
`suspicious` | | [EmptyRegion](EmptyRegion.md) | The region should not be empty | Yes | Info | Code smell | `standard` | | [EmptyStatement](EmptyStatement.md) | Empty statement | Yes | Info | Code smell | `badpractice` | +| [ExcessiveAutoTestCheck](ExcessiveAutoTestCheck.md) | Excessive AutoTest Check | Yes | Minor | Code smell | `standard`
`deprecated` | | [ExtraCommas](ExtraCommas.md) | Commas without a parameter at the end of a method call | Yes | Major | Code smell | `standard`
`badpractice` | | [FormDataToValue](FormDataToValue.md) | FormDataToValue method call | Yes | Info | Code smell | `badpractice` | | [FunctionNameStartsWithGet](FunctionNameStartsWithGet.md) | Function name shouldn't start with "Получить" | No | Info | Code smell | `standard` | diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index 415ffffb029..973b4fb13c8 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -426,7 +426,7 @@ }, "FunctionReturnsSamePrimitive": { "description": "The function always returns the same primitive value", - "default": null, + "default": true, "type": [ "boolean", "object" diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 613e032d3f2..dd5960db17f 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -132,7 +132,7 @@ "$ref": "parameters-schema.json#/definitions/FunctionNameStartsWithGet" }, "FunctionReturnsSamePrimitive": { - "$ref": "diagnostics-schema.json#/definitions/FunctionReturnsSamePrimitive" + "$ref": "parameters-schema.json#/definitions/FunctionReturnsSamePrimitive" }, "FunctionShouldHaveReturn": { "$ref": "parameters-schema.json#/definitions/FunctionShouldHaveReturn" From c5f53a5ce08e5aaa27d7edf843c73b9cc478e613 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sun, 26 Apr 2020 01:38:38 +0700 Subject: [PATCH 202/444] =?UTF-8?q?=D0=94=D0=BE=D0=BF=D0=BE=D0=BB=D0=BD?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D1=82=D0=B0=D1=86=D0=B8=D1=8F,=20=D0=B7=D0=B0=D0=BF=D1=83?= =?UTF-8?q?=D1=89=D0=B5=D0=BD=20=D0=BF=D1=80=D0=B5=D0=BA=D0=BE=D0=BC=D0=BC?= =?UTF-8?q?=D0=B8=D1=82,=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=BF=D0=BE=D1=82=D0=B5=D1=80=D1=8F=D0=BD=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F=20=D0=BB=D0=B8=D1=86=D0=B5=D0=BD=D0=B7=D0=B8=D1=8F?= =?UTF-8?q?=20=D0=B2=20=D1=84=D0=B0=D0=B9=D0=BB=D0=B5=20=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=B0.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/index.md | 11 +- docs/en/diagnostics/index.md | 11 +- .../configuration/parameters-schema.json | 332 +++++------------- .../languageserver/configuration/schema.json | 3 + 4 files changed, 102 insertions(+), 255 deletions(-) diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 2dfbde26f8d..0fab59f2d5f 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,11 +8,11 @@ ## Список реализованных диагностик -Общее количество: **94** +Общее количество: **89** -* Дефект кода: **58** +* Дефект кода: **55** * Уязвимость: **2** -* Ошибка: **32** +* Ошибка: **30** * Потенциальная уязвимость: **2** | Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги | @@ -24,24 +24,19 @@ | [CognitiveComplexity](CognitiveComplexity.md) | Когнитивная сложность | Да | Критичный | Дефект кода | `brainoverload` | | [CommentedCode](CommentedCode.md) | Закомментированный фрагмент кода | Да | Незначительный | Дефект кода | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Нарушение правил работы с транзакциями для метода 'ЗафиксироватьТранзакцию' | Да | Важный | Ошибка | `standard` | -| [CommonModuleAssign](CommonModuleAssign.md) | Присвоение общему модулю | Да | Блокирующий | Ошибка | `error` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Директивы компиляции методов | Да | Важный | Дефект кода | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Лишняя директива компиляции | Да | Важный | Дефект кода | `clumsy`
`standard`
`unpredictable` | -| [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Подряд идущие пустые строки | Да | Информационный | Дефект кода | `badpractice` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Выполнение запроса в цикле | Да | Критичный | Ошибка | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Цикломатическая сложность | Да | Критичный | Дефект кода | `brainoverload` | -| [DataExchangeLoading](DataExchangeLoading.md) | Отсутствует проверка признака ОбменДанными.Загрузка в обработчике событий объекта | Да | Критичный | Ошибка | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Удаление элемента при обходе коллекции посредством оператора "Для каждого ... Из ... Цикл" | Да | Важный | Ошибка | `standard`
`error` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Использование устаревшего метода "ТекущаяДата" | Да | Важный | Ошибка | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Использование устаревшего метода "Найти" | Да | Незначительный | Дефект кода | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Ограничение на использование устаревшего метода "Сообщить" | Да | Незначительный | Дефект кода | `standard`
`deprecated` | -| [DeprecatedMethods8310](DeprecatedMethods8310.md) | Использование устаревшего метода клиентского приложения | Да | Информационный | Дефект кода | `deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Устаревшее использование типа "УправляемаяФорма" | Да | Информационный | Дефект кода | `standard`
`deprecated` | | [DuplicateRegion](DuplicateRegion.md) | Повторяющиеся разделы модуля | Да | Информационный | Дефект кода | `standard` | | [EmptyCodeBlock](EmptyCodeBlock.md) | Пустой блок кода | Да | Важный | Дефект кода | `badpractice`
`suspicious` | | [EmptyRegion](EmptyRegion.md) | Область не должна быть пустой | Да | Информационный | Дефект кода | `standard` | | [EmptyStatement](EmptyStatement.md) | Пустой оператор | Да | Информационный | Дефект кода | `badpractice` | -| [ExcessiveAutoTestCheck](ExcessiveAutoTestCheck.md) | Избыточная проверка параметра АвтоТест | Да | Незначительный | Дефект кода | `standard`
`deprecated` | | [ExtraCommas](ExtraCommas.md) | Запятые без указания параметра в конце вызова метода | Да | Важный | Дефект кода | `standard`
`badpractice` | | [FormDataToValue](FormDataToValue.md) | Использование метода ДанныеФормыВЗначение | Да | Информационный | Дефект кода | `badpractice` | | [FunctionNameStartsWithGet](FunctionNameStartsWithGet.md) | Имя функции не должно начинаться с "Получить" | Нет | Информационный | Дефект кода | `standard` | diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 2f31a4424d4..b22ab4029d5 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,10 +8,10 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **94** +Total: **89** -* Error: **32** -* Code smell: **58** +* Error: **30** +* Code smell: **55** * Vulnerability: **2** * Security Hotspot: **2** @@ -24,24 +24,19 @@ Total: **94** | [CognitiveComplexity](CognitiveComplexity.md) | Cognitive complexity | Yes | Critical | Code smell | `brainoverload` | | [CommentedCode](CommentedCode.md) | Commented out code | Yes | Minor | Code smell | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Violating transaction rules for the 'CommitTransaction' method | Yes | Major | Error | `standard` | -| [CommonModuleAssign](CommonModuleAssign.md) | CommonModuleAssign | Yes | Blocker | Error | `error` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Methods compilation directive | Yes | Major | Code smell | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Needless compilation directive | Yes | Major | Code smell | `clumsy`
`standard`
`unpredictable` | -| [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Consecutive empty lines | Yes | Info | Code smell | `badpractice` | | [CreateQueryInCycle](CreateQueryInCycle.md) | Execution query on cycle | Yes | Critical | Error | `performance` | | [CyclomaticComplexity](CyclomaticComplexity.md) | Cyclomatic complexity | Yes | Critical | Code smell | `brainoverload` | -| [DataExchangeLoading](DataExchangeLoading.md) | There is no check for the attribute DataExchange.Load in the object's event handler | Yes | Critical | Error | `standard`
`badpractice`
`unpredictable` | | [DeletingCollectionItem](DeletingCollectionItem.md) | Deleting an item when iterating through collection using the operator "For each ... In ... Do" | Yes | Major | Error | `standard`
`error` | | [DeprecatedCurrentDate](DeprecatedCurrentDate.md) | Using of the deprecated method "CurrentDate" | Yes | Major | Error | `standard`
`deprecated`
`unpredictable` | | [DeprecatedFind](DeprecatedFind.md) | Using of the deprecated method "Find" | Yes | Minor | Code smell | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Restriction on the use of deprecated "Message" method | Yes | Minor | Code smell | `standard`
`deprecated` | -| [DeprecatedMethods8310](DeprecatedMethods8310.md) | Deprecated client application method. | Yes | Info | Code smell | `deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Deprecated ManagedForm type | Yes | Info | Code smell | `standard`
`deprecated` | | [DuplicateRegion](DuplicateRegion.md) | Duplicate regions | Yes | Info | Code smell | `standard` | | [EmptyCodeBlock](EmptyCodeBlock.md) | Empty code block | Yes | Major | Code smell | `badpractice`
`suspicious` | | [EmptyRegion](EmptyRegion.md) | The region should not be empty | Yes | Info | Code smell | `standard` | | [EmptyStatement](EmptyStatement.md) | Empty statement | Yes | Info | Code smell | `badpractice` | -| [ExcessiveAutoTestCheck](ExcessiveAutoTestCheck.md) | Excessive AutoTest Check | Yes | Minor | Code smell | `standard`
`deprecated` | | [ExtraCommas](ExtraCommas.md) | Commas without a parameter at the end of a method call | Yes | Major | Code smell | `standard`
`badpractice` | | [FormDataToValue](FormDataToValue.md) | FormDataToValue method call | Yes | Info | Code smell | `badpractice` | | [FunctionNameStartsWithGet](FunctionNameStartsWithGet.md) | Function name shouldn't start with "Получить" | No | Info | Code smell | `standard` | diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index 973b4fb13c8..a88716c7949 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -1,12 +1,12 @@ { "$schema": "http://json-schema.org/draft-07/schema", - "$id": "https://1c-syntax.github.io/bsl-language-server/configuration/parameters-schema.json", + "$id": "http://example.com/root.json", "type": "object", - "title": "BSL Language Server Configuration File. Parameters definition part", + "title": "BSL Language Server Configuration File. Diagnostic definition part", "definitions": { "BeginTransactionBeforeTryCatch": { "description": "Violating transaction rules for the 'BeginTransaction' method", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -16,7 +16,7 @@ }, "CanonicalSpellingKeywords": { "description": "Canonical keyword writing", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -26,7 +26,7 @@ }, "CodeBlockBeforeSub": { "description": "Method definitions must be placed before the module body operators", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -36,7 +36,7 @@ }, "CodeOutOfRegion": { "description": "Code out of region", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -46,7 +46,7 @@ }, "CognitiveComplexity": { "description": "Cognitive complexity", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -70,7 +70,7 @@ }, "CommentedCode": { "description": "Commented out code", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -88,7 +88,7 @@ }, "CommitTransactionOutsideTryCatch": { "description": "Violating transaction rules for the 'CommitTransaction' method", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -96,89 +96,9 @@ "title": "Violating transaction rules for the 'CommitTransaction' method", "$id": "#/definitions/CommitTransactionOutsideTryCatch" }, - "CommonModuleAssign": { - "description": "CommonModuleAssign", - "default": true, - "type": [ - "boolean", - "object" - ], - "title": "CommonModuleAssign", - "$id": "#/definitions/CommonModuleAssign" - }, - "CommonModuleNameCached": { - "description": "Missed postfix \"Cached\"", - "default": true, - "type": [ - "boolean", - "object" - ], - "title": "Missed postfix \"Cached\"", - "$id": "#/definitions/CommonModuleNameCached" - }, - "CommonModuleNameClient": { - "description": "Missed postfix \"Client\"", - "default": true, - "type": [ - "boolean", - "object" - ], - "title": "Missed postfix \"Client\"", - "$id": "#/definitions/CommonModuleNameClient" - }, - "CommonModuleNameClientServer": { - "description": "Missed postfix \"ClientServer\"", - "default": true, - "type": [ - "boolean", - "object" - ], - "title": "Missed postfix \"ClientServer\"", - "$id": "#/definitions/CommonModuleNameClientServer" - }, - "CommonModuleNameFullAccess": { - "description": "Missed postfix \"FullAccess\"", - "default": true, - "type": [ - "boolean", - "object" - ], - "title": "Missed postfix \"FullAccess\"", - "$id": "#/definitions/CommonModuleNameFullAccess" - }, - "CommonModuleNameGlobal": { - "description": "Missed postfix \"Global\"", - "default": true, - "type": [ - "boolean", - "object" - ], - "title": "Missed postfix \"Global\"", - "$id": "#/definitions/CommonModuleNameGlobal" - }, - "CommonModuleNameGlobalClient": { - "description": "Global module with postfix \"Client\"", - "default": true, - "type": [ - "boolean", - "object" - ], - "title": "Global module with postfix \"Client\"", - "$id": "#/definitions/CommonModuleNameGlobalClient" - }, - "CommonModuleNameServerCall": { - "description": "Missed postfix \"ServerCall\"", - "default": true, - "type": [ - "boolean", - "object" - ], - "title": "Missed postfix \"ServerCall\"", - "$id": "#/definitions/CommonModuleNameServerCall" - }, "CompilationDirectiveLost": { "description": "Methods compilation directive", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -188,7 +108,7 @@ }, "CompilationDirectiveNeedLess": { "description": "Needless compilation directive", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -196,27 +116,9 @@ "title": "Needless compilation directive", "$id": "#/definitions/CompilationDirectiveNeedLess" }, - "ConsecutiveEmptyLines": { - "description": "Consecutive empty lines", - "default": true, - "type": [ - "boolean", - "object" - ], - "title": "Consecutive empty lines", - "properties": { - "allowedEmptyLinesCount": { - "description": "Maximum allowed consecutive empty lines", - "default": 1, - "type": "integer", - "title": "Maximum allowed consecutive empty lines" - } - }, - "$id": "#/definitions/ConsecutiveEmptyLines" - }, "CreateQueryInCycle": { "description": "Execution query on cycle", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -226,7 +128,7 @@ }, "CyclomaticComplexity": { "description": "Cyclomatic complexity", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -248,27 +150,9 @@ }, "$id": "#/definitions/CyclomaticComplexity" }, - "DataExchangeLoading": { - "description": "There is no check for the attribute DataExchange.Load in the object's event handler", - "default": true, - "type": [ - "boolean", - "object" - ], - "title": "There is no check for the attribute DataExchange.Load in the object's event handler", - "properties": { - "findFirst": { - "description": "Check should go first", - "default": false, - "type": "boolean", - "title": "Check should go first" - } - }, - "$id": "#/definitions/DataExchangeLoading" - }, "DeletingCollectionItem": { "description": "Deleting an item when iterating through collection using the operator \"For each ... In ... Do\"", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -276,19 +160,9 @@ "title": "Deleting an item when iterating through collection using the operator \"For each ... In ... Do\"", "$id": "#/definitions/DeletingCollectionItem" }, - "DeprecatedAttributes8312": { - "description": "Deprecated 8.3.12 platform features.", - "default": true, - "type": [ - "boolean", - "object" - ], - "title": "Deprecated 8.3.12 platform features.", - "$id": "#/definitions/DeprecatedAttributes8312" - }, "DeprecatedCurrentDate": { "description": "Using of the deprecated method \"CurrentDate\"", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -298,7 +172,7 @@ }, "DeprecatedFind": { "description": "Using of the deprecated method \"Find\"", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -308,7 +182,7 @@ }, "DeprecatedMessage": { "description": "Restriction on the use of deprecated \"Message\" method", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -316,19 +190,9 @@ "title": "Restriction on the use of deprecated \"Message\" method", "$id": "#/definitions/DeprecatedMessage" }, - "DeprecatedMethods8310": { - "description": "Deprecated client application method.", - "default": true, - "type": [ - "boolean", - "object" - ], - "title": "Deprecated client application method.", - "$id": "#/definitions/DeprecatedMethods8310" - }, "DeprecatedTypeManagedForm": { "description": "Deprecated ManagedForm type", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -338,7 +202,7 @@ }, "DuplicateRegion": { "description": "Duplicate regions", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -348,7 +212,7 @@ }, "EmptyCodeBlock": { "description": "Empty code block", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -366,7 +230,7 @@ }, "EmptyRegion": { "description": "The region should not be empty", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -376,7 +240,7 @@ }, "EmptyStatement": { "description": "Empty statement", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -384,19 +248,9 @@ "title": "Empty statement", "$id": "#/definitions/EmptyStatement" }, - "ExcessiveAutoTestCheck": { - "description": "Excessive AutoTest Check", - "default": true, - "type": [ - "boolean", - "object" - ], - "title": "Excessive AutoTest Check", - "$id": "#/definitions/ExcessiveAutoTestCheck" - }, "ExtraCommas": { "description": "Commas without a parameter at the end of a method call", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -406,7 +260,7 @@ }, "FormDataToValue": { "description": "FormDataToValue method call", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -416,7 +270,7 @@ }, "FunctionNameStartsWithGet": { "description": "Function name shouldn't start with \"\u041f\u043e\u043b\u0443\u0447\u0438\u0442\u044c\"", - "default": false, + "default": null, "type": [ "boolean", "object" @@ -426,7 +280,7 @@ }, "FunctionReturnsSamePrimitive": { "description": "The function always returns the same primitive value", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -436,7 +290,7 @@ }, "FunctionShouldHaveReturn": { "description": "The function should have return", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -446,7 +300,7 @@ }, "GetFormMethod": { "description": "GetForm method call", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -456,7 +310,7 @@ }, "IdenticalExpressions": { "description": "There are identical sub-expressions to the left and to the right of the \"foo\" operator", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -466,7 +320,7 @@ }, "IfConditionComplexity": { "description": "Usage of complex expressions in the \"If\" condition", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -484,7 +338,7 @@ }, "IfElseDuplicatedCodeBlock": { "description": "Duplicated code blocks in If...Then...ElseIf... statements", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -494,7 +348,7 @@ }, "IfElseDuplicatedCondition": { "description": "Duplicated conditions in If...Then...ElseIf... statements", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -504,7 +358,7 @@ }, "IfElseIfEndsWithElse": { "description": "Else...The...ElseIf... statement should end with Else branch", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -514,7 +368,7 @@ }, "InvalidCharacterInFile": { "description": "Invalid character", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -524,7 +378,7 @@ }, "LineLength": { "description": "Line Length limit", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -542,7 +396,7 @@ }, "MagicNumber": { "description": "Magic numbers", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -566,7 +420,7 @@ }, "MethodSize": { "description": "Method size", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -584,7 +438,7 @@ }, "MissingCodeTryCatchEx": { "description": "Missing code in Raise block in \"Try ... Raise ... EndTry\"", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -602,7 +456,7 @@ }, "MissingSpace": { "description": "Missing spaces to the left or right of operators + - * / = % < > <> <= >=, and also to the right of , and ;", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -644,7 +498,7 @@ }, "MissingTemporaryFileDeletion": { "description": "Missing temporary file deletion after using", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -662,7 +516,7 @@ }, "MissingVariablesDescription": { "description": "All variables declarations must have a description", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -672,7 +526,7 @@ }, "MultilingualStringHasAllDeclaredLanguages": { "description": "There is a localized text for all languages declared in the configuration", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -690,7 +544,7 @@ }, "MultilingualStringUsingWithTemplate": { "description": "Partially localized text is used in the StrTemplate function", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -708,7 +562,7 @@ }, "NestedConstructorsInStructureDeclaration": { "description": "Nested constructors with parameters in structure declaration", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -718,7 +572,7 @@ }, "NestedFunctionInParameters": { "description": "Initialization of method and constructor parameters by calling nested methods", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -728,7 +582,7 @@ }, "NestedStatements": { "description": "Control flow statements should not be nested too deep", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -746,7 +600,7 @@ }, "NestedTernaryOperator": { "description": "Nested ternary operator", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -756,7 +610,7 @@ }, "NonExportMethodsInApiRegion": { "description": "Non export methods in API regions", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -766,7 +620,7 @@ }, "NonStandardRegion": { "description": "Non-standard region of module", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -776,7 +630,7 @@ }, "NumberOfOptionalParams": { "description": "Limit number of optional parameters in method", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -794,7 +648,7 @@ }, "NumberOfParams": { "description": "Number of parameters in method", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -812,7 +666,7 @@ }, "NumberOfValuesInStructureConstructor": { "description": "Limit on the number of property values passed to the structure constructor", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -830,7 +684,7 @@ }, "OSUsersMethod": { "description": "Using method OSUsers", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -840,7 +694,7 @@ }, "OneStatementPerLine": { "description": "One statement per line", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -850,7 +704,7 @@ }, "OrderOfParams": { "description": "Order of Parameters in method", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -860,7 +714,7 @@ }, "PairingBrokenTransaction": { "description": "Violation of pairing using methods \"BeginTransaction()\" & \"CommitTransaction()\" / \"RollbackTransaction()\"", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -870,7 +724,7 @@ }, "ParseError": { "description": "Source code parse error", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -880,7 +734,7 @@ }, "ProcedureReturnsValue": { "description": "Procedure should not return Value", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -890,7 +744,7 @@ }, "PublicMethodsDescription": { "description": "All public methods must have a description", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -908,7 +762,7 @@ }, "SelfAssign": { "description": "Variable is assigned to itself", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -918,7 +772,7 @@ }, "SelfInsertion": { "description": "Insert a collection into itself", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -928,7 +782,7 @@ }, "SemicolonPresence": { "description": "Statement should end with semicolon symbol \";\"", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -938,7 +792,7 @@ }, "SeveralCompilerDirectives": { "description": "Erroneous indication of several compilation directives", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -948,7 +802,7 @@ }, "SpaceAtStartComment": { "description": "Space at the beginning of the comment", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -966,7 +820,7 @@ }, "TempFilesDir": { "description": "TempFilesDir() method call", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -976,7 +830,7 @@ }, "TernaryOperatorUsage": { "description": "Ternary operator usage", - "default": false, + "default": null, "type": [ "boolean", "object" @@ -986,7 +840,7 @@ }, "ThisObjectAssign": { "description": "ThisObject assign", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -996,7 +850,7 @@ }, "TimeoutsInExternalResources": { "description": "Timeouts working with external resources", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1014,7 +868,7 @@ }, "TooManyReturns": { "description": "Methods should not have too many return statements", - "default": false, + "default": null, "type": [ "boolean", "object" @@ -1032,7 +886,7 @@ }, "TryNumber": { "description": "Cast to number of try catch block", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1042,7 +896,7 @@ }, "Typo": { "description": "Typo", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1050,10 +904,10 @@ "title": "Typo", "properties": { "userWordsToIgnore": { - "description": "Dictionary for excluding words (comma separated, without spaces)", + "description": "Dictionary for excluding words", "default": "", "type": "string", - "title": "Dictionary for excluding words (comma separated, without spaces)" + "title": "Dictionary for excluding words" }, "minWordLength": { "description": "Minimum length for checked words", @@ -1066,7 +920,7 @@ }, "UnaryPlusInConcatenation": { "description": "Unary Plus sign in string concatenation", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1076,7 +930,7 @@ }, "UnknownPreprocessorSymbol": { "description": "Unknown preprocessor symbol", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1086,7 +940,7 @@ }, "UnreachableCode": { "description": "Unreachable Code", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1096,7 +950,7 @@ }, "UnusedLocalMethod": { "description": "Unused local method", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1106,7 +960,7 @@ }, "UnusedParameters": { "description": "Unused parameter", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1116,7 +970,7 @@ }, "UseLessForEach": { "description": "Useless collection iteration", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1126,7 +980,7 @@ }, "UsingCancelParameter": { "description": "Using parameter \"Cancel\"", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1136,7 +990,7 @@ }, "UsingExternalCodeTools": { "description": "Using external code tools", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1146,7 +1000,7 @@ }, "UsingFindElementByString": { "description": "Using FindByName and FindByCode", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1156,7 +1010,7 @@ }, "UsingGoto": { "description": "\"goto\" statement should not be used", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1166,7 +1020,7 @@ }, "UsingHardcodeNetworkAddress": { "description": "Using hardcode ip addresses in code", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1184,7 +1038,7 @@ }, "UsingHardcodePath": { "description": "Using hardcode file paths in code", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1202,7 +1056,7 @@ }, "UsingHardcodeSecretInformation": { "description": "Storing confidential information in code", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1220,7 +1074,7 @@ }, "UsingModalWindows": { "description": "Using modal windows", - "default": false, + "default": null, "type": [ "boolean", "object" @@ -1230,7 +1084,7 @@ }, "UsingObjectNotAvailableUnix": { "description": "Using unavailable in Unix objects", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1240,7 +1094,7 @@ }, "UsingServiceTag": { "description": "Using service tags", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1258,7 +1112,7 @@ }, "UsingSynchronousCalls": { "description": "Using synchronous calls", - "default": false, + "default": null, "type": [ "boolean", "object" @@ -1268,7 +1122,7 @@ }, "UsingThisForm": { "description": "Using deprecated property \"ThisForm\"", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1278,7 +1132,7 @@ }, "WrongUseOfRollbackTransactionMethod": { "description": "Not recommended using of RollbackTransaction method", - "default": true, + "default": null, "type": [ "boolean", "object" @@ -1288,7 +1142,7 @@ }, "YoLetterUsage": { "description": "Using Russian character \"yo\" (\"\u0451\") in code", - "default": true, + "default": null, "type": [ "boolean", "object" diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index dd5960db17f..89009acb5aa 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -134,6 +134,9 @@ "FunctionReturnsSamePrimitive": { "$ref": "parameters-schema.json#/definitions/FunctionReturnsSamePrimitive" }, + "FunctionReturnsSamePrimitive": { + "$ref": "diagnostics-schema.json#/definitions/FunctionReturnsSamePrimitive" + }, "FunctionShouldHaveReturn": { "$ref": "parameters-schema.json#/definitions/FunctionShouldHaveReturn" }, From 49a71fc9f98dc5ef5100f28f06c41db5722ab952 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sun, 26 Apr 2020 08:59:12 +0700 Subject: [PATCH 203/444] =?UTF-8?q?=D0=98=D1=81=D0=BA=D0=BB=D1=8E=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B8=D0=B7=20=D0=BF=D1=80=D0=BE?= =?UTF-8?q?=D0=B2=D0=B5=D1=80=D0=BA=D0=B8=20=D0=BF=D0=BE=D0=B4=D0=BA=D0=BB?= =?UTF-8?q?=D1=8E=D1=87=D0=B0=D0=B5=D0=BC=D1=8B=D1=85=20=D1=84=D1=83=D0=BD?= =?UTF-8?q?=D0=BA=D1=86=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...unctionReturnsSamePrimitiveDiagnostic.java | 18 ++++++++++++--- ...FunctionReturnsSamePrimitiveDiagnostic.bsl | 22 ++++++++++++++++++- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java index c0dc94b38af..ba0f48586e9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java @@ -38,6 +38,7 @@ import java.util.Collection; import java.util.List; import java.util.Optional; +import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -54,6 +55,8 @@ public class FunctionReturnsSamePrimitiveDiagnostic extends AbstractVisitorDiagnostic { private static final String KEY_MESSAGE = "diagnosticMessageReturnStatement"; + private static final Pattern pattern = Pattern.compile( + "^(подключаемый|attachable)_", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { super(info); @@ -61,6 +64,17 @@ public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { @Override public ParseTree visitFunction(BSLParser.FunctionContext ctx) { + + var abortCheck = Optional.ofNullable(ctx.funcDeclaration()) + .map(BSLParser.FuncDeclarationContext::subName) + .filter(subNameContext -> pattern.matcher(subNameContext.getText()).find()) + .isPresent(); + + // Исключаем подключаемые методы + if (abortCheck) { + return ctx; + } + var tree = Trees.findAllRuleNodes(ctx, BSLParser.RULE_returnStatement); if (tree.size() > 1) { var expressions = tree.stream() @@ -100,9 +114,7 @@ private void checkPrimitiveValue( private Range getSubNameRange(ParserRuleContext ctx) { return Optional.ofNullable(Trees.getAncestorByRuleIndex(ctx, BSLParser.RULE_sub)) .map(BSLParser.SubContext.class::cast) - .map(context -> documentContext.getSymbolTree().getMethodSymbol(context)) - .filter(Optional::isPresent) - .map(Optional::get) + .flatMap(context -> documentContext.getSymbolTree().getMethodSymbol(context)) .map(MethodSymbol::getSubNameRange) .orElse(Ranges.create(ctx.getStart())); } diff --git a/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl b/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl index 66f0df2975e..67f0824d2ea 100644 --- a/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl +++ b/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl @@ -48,4 +48,24 @@ Возврат Значение; КонецЕсли; Возврат Значение; -КонецФункции \ No newline at end of file +КонецФункции + +Функция Подключаемый_КакаяТоКоманда(Команда) + + Если ЗначениеЗаполнено(ТекущаяДата) Тогда + Возврат Неопределено; + КонецЕсли; + + Возврат Неопределено; + +КонецФункции + +Function Attachable_RandomAction(Command) + + If ValueIsFilled(CurrentDate) Then + Return Undefined; + EndIf; + + Return Undefined; + +EndFunction From 0b712d412880a7757d23eb9e6c303819fad5b28c Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Sun, 26 Apr 2020 08:59:21 +0700 Subject: [PATCH 204/444] =?UTF-8?q?=D0=94=D0=BE=D0=BF=D0=BE=D0=BB=D0=BD?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/FunctionReturnsSamePrimitive.md | 15 +++++++++++++++ .../diagnostics/FunctionReturnsSamePrimitive.md | 15 +++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/docs/diagnostics/FunctionReturnsSamePrimitive.md b/docs/diagnostics/FunctionReturnsSamePrimitive.md index cbd70345b65..41eb85dc3d6 100644 --- a/docs/diagnostics/FunctionReturnsSamePrimitive.md +++ b/docs/diagnostics/FunctionReturnsSamePrimitive.md @@ -46,6 +46,21 @@ КонецПроцедуры ``` +## Особенности + +Из проверки исключаются подключаемые Функции. Например: +```bsl +Функция Подключаемый_КакаяТоКоманда(Команда) + + Если ЗначениеЗаполнено(ТекущаяДата) Тогда + Возврат Неопределено; + КонецЕсли; + + Возврат Неопределено; + +КонецФункции +``` + ## Источники ## Описание диагностики @@ -82,5 +88,7 @@ ### Параметр конфигурационного файла ```json -"FunctionReturnsSamePrimitive": false +"FunctionReturnsSamePrimitive": { + "checkAttachableMethods": true +} ``` diff --git a/docs/en/diagnostics/FunctionReturnsSamePrimitive.md b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md index 01ac1e2515f..d78f5bf2663 100644 --- a/docs/en/diagnostics/FunctionReturnsSamePrimitive.md +++ b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md @@ -4,6 +4,12 @@ | :-: | :-: | :-: | :-: | :-: | :-: | | `Error` | `BSL`
`OS` | `Major` | `Yes` | `5` | `design`
`badpractice` | +## Parameters + +| Name | Type | Description | Default value | +| :-: | :-: | :-- | :-: | +| `checkAttachableMethods` | `Boolean` | ```Check attachable methods``` | ```true``` | + ## Description @@ -82,5 +88,7 @@ EndFunction ### Parameter for config ```json -"FunctionReturnsSamePrimitive": false +"FunctionReturnsSamePrimitive": { + "checkAttachableMethods": true +} ``` diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index a88716c7949..e956f5b9869 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -286,6 +286,14 @@ "object" ], "title": "The function always returns the same primitive value", + "properties": { + "checkAttachableMethods": { + "description": "Check attachable methods", + "default": true, + "type": "boolean", + "title": "Check attachable methods" + } + }, "$id": "#/definitions/FunctionReturnsSamePrimitive" }, "FunctionShouldHaveReturn": { diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 89009acb5aa..dd5960db17f 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -134,9 +134,6 @@ "FunctionReturnsSamePrimitive": { "$ref": "parameters-schema.json#/definitions/FunctionReturnsSamePrimitive" }, - "FunctionReturnsSamePrimitive": { - "$ref": "diagnostics-schema.json#/definitions/FunctionReturnsSamePrimitive" - }, "FunctionShouldHaveReturn": { "$ref": "parameters-schema.json#/definitions/FunctionShouldHaveReturn" }, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties index fb0ac7ddbfc..d7f0db77485 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties @@ -1,3 +1,4 @@ diagnosticMessage=Check that the same primitive value is returned in the function diagnosticName=The function always returns the same primitive value diagnosticMessageReturnStatement=Repeat return value +checkAttachableMethods=Check attachable methods diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties index 2ac2ec79e1b..3143159f75c 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties @@ -1,3 +1,4 @@ diagnosticMessage=Проверьте правильность возврата одного и того же примитивного значения в функции diagnosticName=Функция всегда возвращает одно и то же примитивное значение diagnosticMessageReturnStatement=Повтор возвращаемого значения +checkAttachableMethods=Проверять подключаемые методы From 864f769df51150ef4fd28ec43c554f99ec5f8192 Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Tue, 28 Apr 2020 10:38:29 +0700 Subject: [PATCH 209/444] =?UTF-8?q?=D0=BE=D0=BF=D1=86=D0=B8=D1=8F=20=D0=BD?= =?UTF-8?q?=D0=B0=20=D1=80=D0=B5=D0=B3=D0=B8=D1=81=D1=82=D1=80=20=D0=B4?= =?UTF-8?q?=D0=BB=D1=8F=20=D1=81=D1=82=D1=80=D0=BE=D0=BA,=20=D1=80=D0=B5?= =?UTF-8?q?=D0=BD=D0=B5=D0=B9=D0=BC=20=D0=BE=D0=BF=D1=86=D0=B8=D0=B8=20?= =?UTF-8?q?=D0=BF=D0=BE=20=D0=BF=D0=BE=D0=B4=D0=BA=D0=BB=D1=8E=D1=87=D0=B0?= =?UTF-8?q?=D0=B5=D0=BC=D1=8B=D0=BC,=20=D1=80=D0=B0=D1=81=D1=88=D0=B8?= =?UTF-8?q?=D1=80=D0=B5=D0=BD=D1=8B=20=D1=82=D0=B5=D1=81=D1=82=D1=8B.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../FunctionReturnsSamePrimitive.md | 6 ++- .../FunctionReturnsSamePrimitive.md | 6 ++- ...unctionReturnsSamePrimitiveDiagnostic.java | 40 ++++++++++++------- .../configuration/parameters-schema.json | 12 ++++-- ...turnsSamePrimitiveDiagnostic_en.properties | 3 +- ...turnsSamePrimitiveDiagnostic_ru.properties | 3 +- ...ionReturnsSamePrimitiveDiagnosticTest.java | 29 +++++++++++--- ...FunctionReturnsSamePrimitiveDiagnostic.bsl | 7 ++-- 8 files changed, 72 insertions(+), 34 deletions(-) diff --git a/docs/diagnostics/FunctionReturnsSamePrimitive.md b/docs/diagnostics/FunctionReturnsSamePrimitive.md index 03bc179021a..fe18bf533df 100644 --- a/docs/diagnostics/FunctionReturnsSamePrimitive.md +++ b/docs/diagnostics/FunctionReturnsSamePrimitive.md @@ -8,7 +8,8 @@ | Имя | Тип | Описание | Значение по умолчанию | | :-: | :-: | :-- | :-: | -| `checkAttachableMethods` | `Булево` | ```Проверять подключаемые методы``` | ```true``` | +| `skipAttachable` | `Булево` | ```Не учитывать подключаемые методы``` | ```true``` | +| `caseSensitiveForString` | `Булево` | ```Учитывать регистр в строковых значениях``` | ```false``` | ## Описание диагностики @@ -89,6 +90,7 @@ ```json "FunctionReturnsSamePrimitive": { - "checkAttachableMethods": true + "skipAttachable": true, + "caseSensitiveForString": false } ``` diff --git a/docs/en/diagnostics/FunctionReturnsSamePrimitive.md b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md index d78f5bf2663..b51a70af555 100644 --- a/docs/en/diagnostics/FunctionReturnsSamePrimitive.md +++ b/docs/en/diagnostics/FunctionReturnsSamePrimitive.md @@ -8,7 +8,8 @@ | Name | Type | Description | Default value | | :-: | :-: | :-- | :-: | -| `checkAttachableMethods` | `Boolean` | ```Check attachable methods``` | ```true``` | +| `skipAttachable` | `Boolean` | ```Ignore attachable methods``` | ```true``` | +| `caseSensitiveForString` | `Boolean` | ```Case sensitive for strings``` | ```false``` | ## Description @@ -89,6 +90,7 @@ EndFunction ```json "FunctionReturnsSamePrimitive": { - "checkAttachableMethods": true + "skipAttachable": true, + "caseSensitiveForString": false } ``` diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java index 010a338418c..0f6f2e754ae 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java @@ -60,13 +60,20 @@ public class FunctionReturnsSamePrimitiveDiagnostic extends AbstractVisitorDiagn private static final Pattern pattern = Pattern.compile( "^(подключаемый|attachable)_", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); - private static final boolean CHECK_ATTACHABLE_METHODS = true; + private static final boolean SKIP_ATTACHABLE = true; + private static final boolean CASE_SENSITIVE_FOR_STRING = false; @DiagnosticParameter( type = Boolean.class, - defaultValue = "" + CHECK_ATTACHABLE_METHODS + defaultValue = "" + SKIP_ATTACHABLE ) - private boolean checkAttachableMethods = CHECK_ATTACHABLE_METHODS; + private boolean skipAttachable = SKIP_ATTACHABLE; + + @DiagnosticParameter( + type = Boolean.class, + defaultValue = "" + CASE_SENSITIVE_FOR_STRING + ) + private boolean caseSensitiveForString = CASE_SENSITIVE_FOR_STRING; public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { super(info); @@ -75,7 +82,7 @@ public FunctionReturnsSamePrimitiveDiagnostic(DiagnosticInfo info) { @Override public ParseTree visitFunction(BSLParser.FunctionContext ctx) { - if (checkAttachableMethods) { + if (skipAttachable) { // Исключаем подключаемые методы var abortCheck = Optional.ofNullable(ctx.funcDeclaration()) .map(BSLParser.FuncDeclarationContext::subName) @@ -108,16 +115,12 @@ public ParseTree visitFunction(BSLParser.FunctionContext ctx) { private void checkPrimitiveValue( BSLParser.FunctionContext ctx, Collection tree, List expressions) { - var set = expressions.stream() - .map((BSLParser.ExpressionContext expression) -> { - var text = expression.getText(); - if (Trees.findAllRuleNodes(expression, BSLParser.RULE_string).isEmpty()) { - text = text.toUpperCase(Locale.ENGLISH); - } - return text; - }) - .collect(Collectors.toSet()); - if (set.size() == 1) { + var count = expressions.stream() + .map(this::getExpressionText) + .distinct() + .count(); + + if (count == 1) { var relatedInformation = tree.stream() .map(BSLParser.ReturnStatementContext.class::cast) .map(statement -> RelatedInformation.create( @@ -125,11 +128,18 @@ private void checkPrimitiveValue( Ranges.create(statement.getStart()), info.getResourceString(KEY_MESSAGE))) .collect(Collectors.toList()); - diagnosticStorage.addDiagnostic(getSubNameRange(ctx), info.getMessage(), relatedInformation); + diagnosticStorage.addDiagnostic(getSubNameRange(ctx), relatedInformation); } } + private String getExpressionText(BSLParser.ExpressionContext expression) { + if (caseSensitiveForString && Trees.nodeContains(expression, BSLParser.RULE_string)) { + return expression.getText(); + } + return expression.getText().toUpperCase(Locale.ENGLISH); + } + private Range getSubNameRange(ParserRuleContext ctx) { return Optional.ofNullable(Trees.getAncestorByRuleIndex(ctx, BSLParser.RULE_sub)) .map(BSLParser.SubContext.class::cast) diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index e956f5b9869..5a73d19b09b 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -287,11 +287,17 @@ ], "title": "The function always returns the same primitive value", "properties": { - "checkAttachableMethods": { - "description": "Check attachable methods", + "skipAttachable": { + "description": "Ignore attachable methods", "default": true, "type": "boolean", - "title": "Check attachable methods" + "title": "Ignore attachable methods" + }, + "caseSensitiveForString": { + "description": "Case sensitive for strings", + "default": false, + "type": "boolean", + "title": "Case sensitive for strings" } }, "$id": "#/definitions/FunctionReturnsSamePrimitive" diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties index d7f0db77485..4be88d7f729 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_en.properties @@ -1,4 +1,5 @@ diagnosticMessage=Check that the same primitive value is returned in the function diagnosticName=The function always returns the same primitive value diagnosticMessageReturnStatement=Repeat return value -checkAttachableMethods=Check attachable methods +skipAttachable=Ignore attachable methods +caseSensitiveForString=Case sensitive for strings diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties index 3143159f75c..eadc148c869 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic_ru.properties @@ -1,4 +1,5 @@ diagnosticMessage=Проверьте правильность возврата одного и того же примитивного значения в функции diagnosticName=Функция всегда возвращает одно и то же примитивное значение diagnosticMessageReturnStatement=Повтор возвращаемого значения -checkAttachableMethods=Проверять подключаемые методы +skipAttachable=Не учитывать подключаемые методы +caseSensitiveForString=Учитывать регистр в строковых значениях diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java index 7bc3af568ce..00fd8cafb34 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java @@ -48,28 +48,45 @@ void test() { // then assertThat(diagnostics, true) - .hasSize(4) + .hasSize(5) .hasRange(0, 8, 23) .hasRange(25, 8, 14) .hasRange(35, 8, 17) - .hasRange(62, 8, 22); + .hasRange(62, 8, 22) + .hasRange(82, 8, 32); - // Проверяем с выключенным параметром checkAttachableMethods + // Проверяем с выключенным параметром skipAttachable // when configuration = diagnosticInstance.getInfo().getDefaultConfiguration(); - configuration.put("checkAttachableMethods", false); + configuration.put("skipAttachable", false); diagnosticInstance.configure(configuration); diagnostics = getDiagnostics(); // then assertThat(diagnostics, true) - .hasSize(6) + .hasSize(7) .hasRange(0, 8, 23) .hasRange(25, 8, 14) .hasRange(35, 8, 17) .hasRange(52, 8, 35) .hasRange(62, 8, 22) - .hasRange(72, 9, 32); + .hasRange(72, 9, 32) + .hasRange(82, 8, 32); + + // Проверяем с включенным параметром caseSensitiveForString + // when + configuration = diagnosticInstance.getInfo().getDefaultConfiguration(); + configuration.put("caseSensitiveForString", true); + diagnosticInstance.configure(configuration); + diagnostics = getDiagnostics(); + + // then + assertThat(diagnostics, true) + .hasSize(4) + .hasRange(0, 8, 23) + .hasRange(25, 8, 14) + .hasRange(35, 8, 17) + .hasRange(62, 8, 22); } } diff --git a/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl b/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl index d2d1c8ca1ce..df2cf3995b3 100644 --- a/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl +++ b/src/test/resources/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.bsl @@ -50,7 +50,7 @@ Возврат Значение; КонецФункции -Функция Подключаемый_КакаяТоКоманда(Команда) +Функция Подключаемый_КакаяТоКоманда(Команда) // <- ошибки (опционально) Если ЗначениеЗаполнено(ТекущаяДата) Тогда Возврат Null; @@ -70,7 +70,7 @@ КонецФункции -Function Attachable_RandomAction(Command) +Function Attachable_RandomAction(Command) // <- ошибки (опционально) If ValueIsFilled(CurrentDate) Then Return Undefined; @@ -80,8 +80,7 @@ Function Attachable_RandomAction(Command) EndFunction -// тут нет ошибки -Функция ПроверкаРегистраДляСтрок() +Функция ПроверкаРегистраДляСтрок() // <- ошибки (опционально) Тип = 1; Если Тип = 1 Тогда From 44b704ea4cbe07b7784cd36fa534f17ca753ed2b Mon Sep 17 00:00:00 2001 From: Tymko Oleg Date: Tue, 28 Apr 2020 13:31:09 +0700 Subject: [PATCH 210/444] =?UTF-8?q?=D0=B0=D0=BA=D1=82=D1=83=D0=B0=D0=BB?= =?UTF-8?q?=D0=B8=D0=B7=D0=B0=D1=86=D0=B8=D1=8F=20precommit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/index.md | 13 +++- docs/en/diagnostics/index.md | 14 +++- .../configuration/parameters-schema.json | 70 +++++++++++++++++++ 3 files changed, 91 insertions(+), 6 deletions(-) diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 6b75e3691b3..208bf744d25 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,12 +8,12 @@ ## Список реализованных диагностик -Общее количество: **94** +Общее количество: **102** -* Дефект кода: **59** +* Дефект кода: **65** * Уязвимость: **2** * Ошибка: **32** -* Потенциальная уязвимость: **2** +* Потенциальная уязвимость: **3** | Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги | | --- | --- | :-: | --- | --- | --- | @@ -25,6 +25,13 @@ | [CommentedCode](CommentedCode.md) | Закомментированный фрагмент кода | Да | Незначительный | Дефект кода | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Нарушение правил работы с транзакциями для метода 'ЗафиксироватьТранзакцию' | Да | Важный | Ошибка | `standard` | | [CommonModuleAssign](CommonModuleAssign.md) | Присвоение общему модулю | Да | Блокирующий | Ошибка | `error` | +| [CommonModuleNameCached](CommonModuleNameCached.md) | Пропущен постфикс "ПовтИсп" | Да | Важный | Дефект кода | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameClient](CommonModuleNameClient.md) | Пропущен постфикс "Клиент" | Да | Незначительный | Дефект кода | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameClientServer](CommonModuleNameClientServer.md) | Пропущен постфикс "КлиентСервер" | Да | Важный | Дефект кода | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameFullAccess](CommonModuleNameFullAccess.md) | Пропущен постфикс "ПолныеПрава" | Да | Важный | Потенциальная уязвимость | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameGlobal](CommonModuleNameGlobal.md) | Пропущен постфикс "Глобальный" | Да | Важный | Дефект кода | `standard`
`badpractice`
`brainoverload` | +| [CommonModuleNameGlobalClient](CommonModuleNameGlobalClient.md) | Глобальный модуль с постфиксом "Клиент" | Да | Важный | Дефект кода | `standard` | +| [CommonModuleNameServerCall](CommonModuleNameServerCall.md) | Пропущен постфикс "ВызовСервера" | Да | Незначительный | Дефект кода | `standard`
`badpractice`
`unpredictable` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Директивы компиляции методов | Да | Важный | Дефект кода | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Лишняя директива компиляции | Да | Важный | Дефект кода | `clumsy`
`standard`
`unpredictable` | | [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Подряд идущие пустые строки | Да | Информационный | Дефект кода | `badpractice` | diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index e72223b389b..5ece9f38a77 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,11 +8,12 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **94** +Total: **102** + * Error: **32** -* Code smell: **59** +* Code smell: **65** * Vulnerability: **2** -* Security Hotspot: **2** +* Security Hotspot: **3** | Key | Name| Enabled by default | Severity | Type | Tags | | --- | --- | :-: | --- | --- | --- | @@ -24,6 +25,13 @@ Total: **94** | [CommentedCode](CommentedCode.md) | Commented out code | Yes | Minor | Code smell | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Violating transaction rules for the 'CommitTransaction' method | Yes | Major | Error | `standard` | | [CommonModuleAssign](CommonModuleAssign.md) | CommonModuleAssign | Yes | Blocker | Error | `error` | +| [CommonModuleNameCached](CommonModuleNameCached.md) | Missed postfix "Cached" | Yes | Major | Code smell | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameClient](CommonModuleNameClient.md) | Missed postfix "Client" | Yes | Minor | Code smell | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameClientServer](CommonModuleNameClientServer.md) | Missed postfix "ClientServer" | Yes | Major | Code smell | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameFullAccess](CommonModuleNameFullAccess.md) | Missed postfix "FullAccess" | Yes | Major | Security Hotspot | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameGlobal](CommonModuleNameGlobal.md) | Missed postfix "Global" | Yes | Major | Code smell | `standard`
`badpractice`
`brainoverload` | +| [CommonModuleNameGlobalClient](CommonModuleNameGlobalClient.md) | Global module with postfix "Client" | Yes | Major | Code smell | `standard` | +| [CommonModuleNameServerCall](CommonModuleNameServerCall.md) | Missed postfix "ServerCall" | Yes | Minor | Code smell | `standard`
`badpractice`
`unpredictable` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Methods compilation directive | Yes | Major | Code smell | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Needless compilation directive | Yes | Major | Code smell | `clumsy`
`standard`
`unpredictable` | | [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Consecutive empty lines | Yes | Info | Code smell | `badpractice` | diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index 2c6ba1dd70d..3b2b537e167 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -106,6 +106,76 @@ "title": "CommonModuleAssign", "$id": "#/definitions/CommonModuleAssign" }, + "CommonModuleNameCached": { + "description": "Missed postfix \"Cached\"", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Missed postfix \"Cached\"", + "$id": "#/definitions/CommonModuleNameCached" + }, + "CommonModuleNameClient": { + "description": "Missed postfix \"Client\"", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Missed postfix \"Client\"", + "$id": "#/definitions/CommonModuleNameClient" + }, + "CommonModuleNameClientServer": { + "description": "Missed postfix \"ClientServer\"", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Missed postfix \"ClientServer\"", + "$id": "#/definitions/CommonModuleNameClientServer" + }, + "CommonModuleNameFullAccess": { + "description": "Missed postfix \"FullAccess\"", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Missed postfix \"FullAccess\"", + "$id": "#/definitions/CommonModuleNameFullAccess" + }, + "CommonModuleNameGlobal": { + "description": "Missed postfix \"Global\"", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Missed postfix \"Global\"", + "$id": "#/definitions/CommonModuleNameGlobal" + }, + "CommonModuleNameGlobalClient": { + "description": "Global module with postfix \"Client\"", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Global module with postfix \"Client\"", + "$id": "#/definitions/CommonModuleNameGlobalClient" + }, + "CommonModuleNameServerCall": { + "description": "Missed postfix \"ServerCall\"", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Missed postfix \"ServerCall\"", + "$id": "#/definitions/CommonModuleNameServerCall" + }, "CompilationDirectiveLost": { "description": "Methods compilation directive", "default": true, From 90d7637f654b34b172959ee1bd6cc069c08680f7 Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Tue, 28 Apr 2020 10:57:03 +0300 Subject: [PATCH 211/444] =?UTF-8?q?=D0=9D=D0=BE=D0=B2=D0=B0=D1=8F=20=D0=B4?= =?UTF-8?q?=D0=B8=D0=B0=D0=B3=D0=BD=D0=BE=D1=81=D1=82=D0=B8=D0=BA=D0=B0:?= =?UTF-8?q?=20=D0=97=D0=B0=D0=BF=D1=80=D0=B5=D1=82=20=D0=BD=D0=B0=20=D0=B8?= =?UTF-8?q?=D1=81=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=A0=D0=BE=D0=BB=D1=8C=D0=94=D0=BE=D1=81=D1=82?= =?UTF-8?q?=D1=83=D0=BF=D0=BD=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/IsInRoleMethodDiagnostic.md | 49 ++++++ .../diagnostics/IsInRoleMethodDiagnostic.md | 49 ++++++ .../IsInRoleMethodDiagnosticDiagnostic.java | 140 ++++++++++++++++++ ...leMethodDiagnosticDiagnostic_en.properties | 2 + ...leMethodDiagnosticDiagnostic_ru.properties | 2 + ...sInRoleMethodDiagnosticDiagnosticTest.java | 26 ++++ .../IsInRoleMethodDiagnosticDiagnostic.bsl | 41 +++++ 7 files changed, 309 insertions(+) create mode 100644 docs/diagnostics/IsInRoleMethodDiagnostic.md create mode 100644 docs/en/diagnostics/IsInRoleMethodDiagnostic.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/IsInRoleMethodDiagnosticDiagnostic.bsl diff --git a/docs/diagnostics/IsInRoleMethodDiagnostic.md b/docs/diagnostics/IsInRoleMethodDiagnostic.md new file mode 100644 index 00000000000..899e854b314 --- /dev/null +++ b/docs/diagnostics/IsInRoleMethodDiagnostic.md @@ -0,0 +1,49 @@ +# () + + + +## + + +## Описание диагностики + +Для проверки прав доступа в коде следует использовать метод ПравоДоступа. + +В тех случаях, где роль не дает никаких прав на объекты метаданных, а служит только для определения того или иного дополнительного права, +следует использовать метод РольДоступна. При использовании в конфигурации Библиотеки стандартных подсистем (БСП) следует +использовать функцию РолиДоступны общего модуля Пользователи. +## Примеры + +``` +Неправильно: +Если РольДоступна("ДобавлениеИзменениеСтранМира") Тогда ... +Если РольДоступна("ПросмотрОтчетаПопулярныеСтраны") Тогда +``` +``` +Правильно: +Если ПравоДоступа("Редактирование", Метаданные.Справочники.СтраныМира) Тогда ... +Если ПравоДоступа("Просмотр", Метаданные.Отчеты.ПопулярныеСтраны) Тогда ... +``` +## Источники + + +* Источник: [Стандарт: Проверка прав доступа](https://its.1c.ru/db/v8std#content:737:hdoc) +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Параметр конфигурационного файла + +```json +"": +``` \ No newline at end of file diff --git a/docs/en/diagnostics/IsInRoleMethodDiagnostic.md b/docs/en/diagnostics/IsInRoleMethodDiagnostic.md new file mode 100644 index 00000000000..d2c5089cd87 --- /dev/null +++ b/docs/en/diagnostics/IsInRoleMethodDiagnostic.md @@ -0,0 +1,49 @@ +# + + + +## + + +## Description + +To check access rights in the code, use the AccessRight method. + +When a role does not grant access rights to metadata objects and defines an additional access right only, +use the IsInRole method. If Standard Subsystems Library is used in a configuration, +use the RolesAvailable function of the Users common module. +## Examples + +``` +Incorrect: +If IsInRole("AddChangeWorldCountries") Then ... +If IsInRole("ViewPopularCountriesReport") Then ... +``` +``` +Correct example: +If AccessRight("Edit", Metadata.Catalogs.WorldCountries) Then ... +If AccessRight("View", Metadata.Reports.PopularCountries) Then ... +``` +## Sources + + +Source: [Standard: Checking access rights](https://support.1ci.com/hc/en-us/articles/360011003180-Checking-access-rights) +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Parameter for config + +```json +"": +``` diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnostic.java new file mode 100644 index 00000000000..6b4d7cf73b0 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnostic.java @@ -0,0 +1,140 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.Trees; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; +import org.antlr.v4.runtime.tree.ParseTree; + +import java.util.Collection; +import java.util.HashSet; +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.MAJOR, + scope = DiagnosticScope.BSL, + minutesToFix = 5, + tags = { + DiagnosticTag.ERROR + } + +) +public class IsInRoleMethodDiagnosticDiagnostic extends AbstractVisitorDiagnostic { + + private static final HashSet IS_IN_ROLE_VARS = new HashSet<>(); + private static final HashSet PRIVILEGED_MODE_NAME_VARS = new HashSet<>(); + + private static final Pattern IS_IN_ROLE_NAME_PATTERN = Pattern.compile( + "(РольДоступна|IsInRole)", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE + ); + + private static final Pattern PRIVILEGED_MODE_NAME_PATTERN = Pattern.compile( + "(PrivilegedMode|ПривилегированныйРежим)", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE + ); + + public IsInRoleMethodDiagnosticDiagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + public ParseTree visitIfBranch(BSLParser.IfBranchContext ctx) { + Collection listIdentifier = Trees.findAllRuleNodes(ctx, BSLParser.RULE_complexIdentifier); + + if (listIdentifier.isEmpty()) { + return super.visitIfBranch(ctx); + } + + listIdentifier.stream().map(complexCtx -> (BSLParser.ComplexIdentifierContext)complexCtx) + .filter(complexCtx -> IS_IN_ROLE_VARS.contains(complexCtx.getText())) + .filter(IsInRoleMethodDiagnosticDiagnostic::checkStatement) + .forEach(diagnosticStorage::addDiagnostic); + + return super.visitIfBranch(ctx); + } + + @Override + public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { + + if (IS_IN_ROLE_NAME_PATTERN.matcher(ctx.methodName().getText()).matches()) { + handleIsInRoleGlobalMethod(ctx); + } else if (PRIVILEGED_MODE_NAME_PATTERN.matcher(ctx.methodName().getText()).matches()) { + handlePrivilegedModeGlobalMethod(ctx); + } else { + return super.visitGlobalMethodCall(ctx); + } + + return super.visitGlobalMethodCall(ctx); + } + + private void handleIsInRoleGlobalMethod(BSLParser.GlobalMethodCallContext ctx) { + var ifStatementNode = Trees.getRootParent(ctx, BSLParser.RULE_ifStatement); + if (ifStatementNode != null && checkStatement(ctx)) { + diagnosticStorage.addDiagnostic(ctx); + } + + var assignmentNode = Trees.getRootParent(ctx, BSLParser.RULE_assignment); + if (assignmentNode != null) { + var childNodes = Trees.getChildren(assignmentNode, BSLParser.RULE_lValue); + if (!childNodes.isEmpty()) { + IS_IN_ROLE_VARS.add(childNodes.get(0).getText()); + } + } + } + + private static void handlePrivilegedModeGlobalMethod(BSLParser.GlobalMethodCallContext ctx) { + var assignmentNode = Trees.getRootParent(ctx, BSLParser.RULE_assignment); + if (assignmentNode != null) { + var childNodes = Trees.getChildren(assignmentNode, BSLParser.RULE_lValue); + if (!childNodes.isEmpty()) { + PRIVILEGED_MODE_NAME_VARS.add(childNodes.get(0).getText()); + } + } + } + + @Override + public ParseTree visitAssignment(BSLParser.AssignmentContext ctx) { + var childNodes = Trees.getChildren(ctx, BSLParser.RULE_lValue); + + if (!childNodes.isEmpty()) { + IS_IN_ROLE_VARS.remove(childNodes.get(0).getText()); + PRIVILEGED_MODE_NAME_VARS.remove(childNodes.get(0).getText()); + } + return super.visitAssignment(ctx); + } + + private static boolean checkStatement(BSLParserRuleContext ctx) { + var parentExpression = Trees.getRootParent(ctx, BSLParser.RULE_expression); + + if (parentExpression == null) { + return false; + } + + boolean hasPrivilegedModeCheck = false; + + var identifierList = Trees.findAllRuleNodes(parentExpression, BSLParser.RULE_complexIdentifier); + for (ParseTree parseTree : identifierList) { + if (PRIVILEGED_MODE_NAME_VARS.contains(parseTree.getText())) { + hasPrivilegedModeCheck = true; + } + } + + if (!hasPrivilegedModeCheck) { + var nextGlobalMethodNode = Trees.getNextNode(parentExpression, + ctx, BSLParser.RULE_globalMethodCall); + + hasPrivilegedModeCheck = (nextGlobalMethodNode instanceof BSLParser.GlobalMethodCallContext + && PRIVILEGED_MODE_NAME_PATTERN.matcher(((BSLParser.GlobalMethodCallContext) nextGlobalMethodNode) + .methodName().getText()).matches()); + } + + return !hasPrivilegedModeCheck; + } +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnostic_en.properties new file mode 100644 index 00000000000..4ca127c1b8a --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=To check access rights, use AccessRight global method instead. +diagnosticName=IsInRole global method call diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnostic_ru.properties new file mode 100644 index 00000000000..1eef4829c69 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Для проверки прав доступа в коде следует использовать метод ПравоДоступа +diagnosticName=Использование метода РольДоступна diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnosticTest.java new file mode 100644 index 00000000000..7ca610525ea --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnosticTest.java @@ -0,0 +1,26 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class IsInRoleMethodDiagnosticDiagnosticTest extends AbstractDiagnosticTest { + IsInRoleMethodDiagnosticDiagnosticTest() { + super(IsInRoleMethodDiagnosticDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(2); + assertThat(diagnostics, true) + .hasRange(32, 9, 32, 35) + .hasRange(38, 9, 38, 23); + + } +} diff --git a/src/test/resources/diagnostics/IsInRoleMethodDiagnosticDiagnostic.bsl b/src/test/resources/diagnostics/IsInRoleMethodDiagnosticDiagnostic.bsl new file mode 100644 index 00000000000..418c57f0a01 --- /dev/null +++ b/src/test/resources/diagnostics/IsInRoleMethodDiagnosticDiagnostic.bsl @@ -0,0 +1,41 @@ +Процедура Тест() + ДоступРазрешен = РольДоступна("НужнаяРоль"); + ПР = ПривилегированныйРежим(); + Если ДоступРазрешен ИЛИ ПР Тогда // Нет срабатывания. Есть проверка на привилегированный режим + КонецЕсли; +КонецПроцедуры + +Процедура Тест() + Если РольДоступна("НужнаяРоль") ИЛИ ПривилегированныйРежим() Тогда // Нет срабатывания. Есть проверка на привилегированный режим + КонецЕсли; +КонецПроцедуры + +Процедура Тест() + ДоступРазрешен = РольДоступна("НужнаяРоль"); + Если ДоступРазрешен ИЛИ ПривилегированныйРежим() Тогда // Нет срабатывания. Есть проверка на привилегированный режим + КонецЕсли; +КонецПроцедуры + +Процедура Тест() + ПР = ПривилегированныйРежим(); + Если РольДоступна("НужнаяРоль") ИЛИ ПР Тогда // Нет срабатывания. Есть проверка на привилегированный режим + КонецЕсли; +КонецПроцедуры + +Процедура Тест() + ДоступРазрешен = РольДоступна("НужнаяРоль"); + ДоступРазрешен = ПР(); + Если ДоступРазрешен Тогда // Нет срабатывания + КонецЕсли; +КонецПроцедуры + +Процедура Тест2() + Если РольДоступна("НужнаяРоль") Тогда // Срабатывание + КонецЕсли; +КонецПроцедуры + +Процедура Тест3() + ДоступРазрешен = РольДоступна("НужнаяРоль"); + Если ДоступРазрешен Тогда // Срабатывание + КонецЕсли; +КонецПроцедуры \ No newline at end of file From 3e68651ba84fb7f5967312e35267b5babbe03129 Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Tue, 28 Apr 2020 10:59:26 +0300 Subject: [PATCH 212/444] Precommit --- docs/diagnostics/IsInRoleMethodDiagnostic.md | 19 +++++++++-------- docs/diagnostics/index.md | 5 +++-- .../diagnostics/IsInRoleMethodDiagnostic.md | 17 ++++++++------- docs/en/diagnostics/index.md | 5 +++-- .../IsInRoleMethodDiagnosticDiagnostic.java | 21 +++++++++++++++++++ .../configuration/parameters-schema.json | 10 +++++++++ .../languageserver/configuration/schema.json | 3 +++ ...sInRoleMethodDiagnosticDiagnosticTest.java | 21 +++++++++++++++++++ 8 files changed, 80 insertions(+), 21 deletions(-) diff --git a/docs/diagnostics/IsInRoleMethodDiagnostic.md b/docs/diagnostics/IsInRoleMethodDiagnostic.md index 899e854b314..677453d4f2a 100644 --- a/docs/diagnostics/IsInRoleMethodDiagnostic.md +++ b/docs/diagnostics/IsInRoleMethodDiagnostic.md @@ -1,8 +1,8 @@ -# () +# Использование метода РольДоступна (IsInRoleMethodDiagnostic) - - -## +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Дефект кода` | `BSL` | `Важный` | `Да` | `5` | `error` | ## Описание диагностики @@ -32,18 +32,19 @@ * Полезная информаця: [Отказ от использования модальных окон](https://its.1c.ru/db/metod8dev#content:5272:hdoc) * Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) --> * Источник: [Стандарт: Проверка прав доступа](https://its.1c.ru/db/v8std#content:737:hdoc) + ## Сниппеты - + ### Экранирование кода ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:IsInRoleMethodDiagnostic-off +// BSLLS:IsInRoleMethodDiagnostic-on ``` ### Параметр конфигурационного файла ```json -"": -``` \ No newline at end of file +"IsInRoleMethodDiagnostic": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 784ac601b59..c25a32883be 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,9 +8,9 @@ ## Список реализованных диагностик -Общее количество: **94** +Общее количество: **95** -* Дефект кода: **59** +* Дефект кода: **60** * Уязвимость: **2** * Ошибка: **31** * Потенциальная уязвимость: **2** @@ -54,6 +54,7 @@ | [IfElseDuplicatedCondition](IfElseDuplicatedCondition.md) | Повторяющиеся условия в синтаксической конструкции Если...Тогда...ИначеЕсли... | Да | Важный | Дефект кода | `suspicious` | | [IfElseIfEndsWithElse](IfElseIfEndsWithElse.md) | Использование синтаксической конструкции Если...Тогда...ИначеЕсли... | Да | Важный | Дефект кода | `badpractice` | | [InvalidCharacterInFile](InvalidCharacterInFile.md) | Недопустимый символ | Да | Важный | Ошибка | `error`
`standard`
`unpredictable` | +| [IsInRoleMethodDiagnostic](IsInRoleMethodDiagnostic.md) | Использование метода РольДоступна | Да | Важный | Дефект кода | `error` | | [LineLength](LineLength.md) | Ограничение на длину строки | Да | Незначительный | Дефект кода | `standard`
`badpractice` | | [MagicNumber](MagicNumber.md) | Магические числа | Да | Незначительный | Дефект кода | `badpractice` | | [MethodSize](MethodSize.md) | Ограничение на размер метода | Да | Важный | Дефект кода | `badpractice` | diff --git a/docs/en/diagnostics/IsInRoleMethodDiagnostic.md b/docs/en/diagnostics/IsInRoleMethodDiagnostic.md index d2c5089cd87..d73b1abb148 100644 --- a/docs/en/diagnostics/IsInRoleMethodDiagnostic.md +++ b/docs/en/diagnostics/IsInRoleMethodDiagnostic.md @@ -1,8 +1,8 @@ -# +# IsInRole global method call (IsInRoleMethodDiagnostic) - - -## +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Code smell` | `BSL` | `Major` | `Yes` | `5` | `error` | ## Description @@ -32,18 +32,19 @@ If AccessRight("View", Metadata.Reports.PopularCountries) Then ... * Полезная информаця: [Отказ от использования модальных окон](https://its.1c.ru/db/metod8dev#content:5272:hdoc) * Источник: [Cognitive complexity, ver. 1.4](https://www.sonarsource.com/docs/CognitiveComplexity.pdf) --> Source: [Standard: Checking access rights](https://support.1ci.com/hc/en-us/articles/360011003180-Checking-access-rights) + ## Snippets - + ### Diagnostic ignorance in code ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:IsInRoleMethodDiagnostic-off +// BSLLS:IsInRoleMethodDiagnostic-on ``` ### Parameter for config ```json -"": +"IsInRoleMethodDiagnostic": false ``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 5088bbd207c..a17781c9e67 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,10 +8,10 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **94** +Total: **95** * Error: **31** -* Code smell: **59** +* Code smell: **60** * Vulnerability: **2** * Security Hotspot: **2** @@ -54,6 +54,7 @@ Total: **94** | [IfElseDuplicatedCondition](IfElseDuplicatedCondition.md) | Duplicated conditions in If...Then...ElseIf... statements | Yes | Major | Code smell | `suspicious` | | [IfElseIfEndsWithElse](IfElseIfEndsWithElse.md) | Else...The...ElseIf... statement should end with Else branch | Yes | Major | Code smell | `badpractice` | | [InvalidCharacterInFile](InvalidCharacterInFile.md) | Invalid character | Yes | Major | Error | `error`
`standard`
`unpredictable` | +| [IsInRoleMethodDiagnostic](IsInRoleMethodDiagnostic.md) | IsInRole global method call | Yes | Major | Code smell | `error` | | [LineLength](LineLength.md) | Line Length limit | Yes | Minor | Code smell | `standard`
`badpractice` | | [MagicNumber](MagicNumber.md) | Magic numbers | Yes | Minor | Code smell | `badpractice` | | [MethodSize](MethodSize.md) | Method size | Yes | Major | Code smell | `badpractice` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnostic.java index 6b4d7cf73b0..addd9295213 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnostic.java @@ -1,3 +1,24 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index a6dcbbd3085..276c3af0aa6 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -442,6 +442,16 @@ "title": "Invalid character", "$id": "#/definitions/InvalidCharacterInFile" }, + "IsInRoleMethodDiagnostic": { + "description": "IsInRole global method call", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "IsInRole global method call", + "$id": "#/definitions/IsInRoleMethodDiagnostic" + }, "LineLength": { "description": "Line Length limit", "default": true, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 20141ed863e..5cb876b7d78 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -134,6 +134,9 @@ "InvalidCharacterInFile": { "$ref": "parameters-schema.json#/definitions/InvalidCharacterInFile" }, + "IsInRoleMethodDiagnostic": { + "$ref": "parameters-schema.json#/definitions/IsInRoleMethodDiagnostic" + }, "LineLength": { "$ref": "parameters-schema.json#/definitions/LineLength" }, diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnosticTest.java index 7ca610525ea..fe9cc1ed484 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticDiagnosticTest.java @@ -1,3 +1,24 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; import org.eclipse.lsp4j.Diagnostic; From b85be9bf9b694d90e31c55afd77d2e594e0bbda7 Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Tue, 28 Apr 2020 11:08:56 +0300 Subject: [PATCH 213/444] Precommit. --- docs/diagnostics/index.md | 5 +++-- docs/en/diagnostics/index.md | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 208bf744d25..4ac56f2beda 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,9 +8,9 @@ ## Список реализованных диагностик -Общее количество: **102** +Общее количество: **103** -* Дефект кода: **65** +* Дефект кода: **66** * Уязвимость: **2** * Ошибка: **32** * Потенциальная уязвимость: **3** @@ -62,6 +62,7 @@ | [IfElseDuplicatedCondition](IfElseDuplicatedCondition.md) | Повторяющиеся условия в синтаксической конструкции Если...Тогда...ИначеЕсли... | Да | Важный | Дефект кода | `suspicious` | | [IfElseIfEndsWithElse](IfElseIfEndsWithElse.md) | Использование синтаксической конструкции Если...Тогда...ИначеЕсли... | Да | Важный | Дефект кода | `badpractice` | | [InvalidCharacterInFile](InvalidCharacterInFile.md) | Недопустимый символ | Да | Важный | Ошибка | `error`
`standard`
`unpredictable` | +| [IsInRoleMethodDiagnostic](IsInRoleMethodDiagnostic.md) | Использование метода РольДоступна | Да | Важный | Дефект кода | `error` | | [LineLength](LineLength.md) | Ограничение на длину строки | Да | Незначительный | Дефект кода | `standard`
`badpractice` | | [MagicNumber](MagicNumber.md) | Магические числа | Да | Незначительный | Дефект кода | `badpractice` | | [MethodSize](MethodSize.md) | Ограничение на размер метода | Да | Важный | Дефект кода | `badpractice` | diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 5ece9f38a77..ed79ba2b9a8 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,10 +8,10 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **102** +Total: **103** * Error: **32** -* Code smell: **65** +* Code smell: **66** * Vulnerability: **2** * Security Hotspot: **3** @@ -62,6 +62,7 @@ Total: **102** | [IfElseDuplicatedCondition](IfElseDuplicatedCondition.md) | Duplicated conditions in If...Then...ElseIf... statements | Yes | Major | Code smell | `suspicious` | | [IfElseIfEndsWithElse](IfElseIfEndsWithElse.md) | Else...The...ElseIf... statement should end with Else branch | Yes | Major | Code smell | `badpractice` | | [InvalidCharacterInFile](InvalidCharacterInFile.md) | Invalid character | Yes | Major | Error | `error`
`standard`
`unpredictable` | +| [IsInRoleMethodDiagnostic](IsInRoleMethodDiagnostic.md) | IsInRole global method call | Yes | Major | Code smell | `error` | | [LineLength](LineLength.md) | Line Length limit | Yes | Minor | Code smell | `standard`
`badpractice` | | [MagicNumber](MagicNumber.md) | Magic numbers | Yes | Minor | Code smell | `badpractice` | | [MethodSize](MethodSize.md) | Method size | Yes | Major | Code smell | `badpractice` | From f44f01ea5452ae30c5f1fd3f02acb8c0186e665d Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Wed, 29 Apr 2020 12:36:05 +0300 Subject: [PATCH 214/444] =?UTF-8?q?=D0=9D=D0=BE=D0=B2=D1=8B=D0=B9=20=D1=80?= =?UTF-8?q?=D0=B5=D0=B6=D0=B8=D0=BC=20=D1=81=D0=BE=D0=B2=D0=BC=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=B8=D0=BC=D0=BE=D1=81=D1=82=D0=B8:=208.3.17?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/metadata/DiagnosticCompatibilityMode.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticCompatibilityMode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticCompatibilityMode.java index f3189bcec57..19e937906ea 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticCompatibilityMode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticCompatibilityMode.java @@ -43,7 +43,8 @@ public enum DiagnosticCompatibilityMode { COMPATIBILITY_MODE_8_3_13(3, 13), COMPATIBILITY_MODE_8_3_14(3, 14), COMPATIBILITY_MODE_8_3_15(3, 15), - COMPATIBILITY_MODE_8_3_16(3, 16); + COMPATIBILITY_MODE_8_3_16(3, 16), + COMPATIBILITY_MODE_8_3_17(3, 17); private final CompatibilityMode compatibilityMode; From de3ce698839704f888c104f41dc385e62f9f73d1 Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Wed, 29 Apr 2020 15:11:47 +0300 Subject: [PATCH 215/444] =?UTF-8?q?=D0=9D=D0=BE=D0=B2=D0=B0=D1=8F=20=D0=B4?= =?UTF-8?q?=D0=B8=D0=B0=D0=B3=D0=BD=D0=BE=D1=81=D1=82=D0=B8=D0=BA=D0=B0:?= =?UTF-8?q?=20(8.3.17+)=20=D0=A3=D1=81=D1=82=D0=B0=D1=80=D0=B5=D0=B2=D1=88?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=B3=D0=BB=D0=BE=D0=B1=D0=B0=D0=BB=D1=8C=D0=BD?= =?UTF-8?q?=D1=8B=D0=B5=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/DeprecatedMethods8317.md | 36 ++++++++++++++++++ docs/en/diagnostics/DeprecatedMethods8317.md | 36 ++++++++++++++++++ .../DeprecatedMethods8317Diagnostic.java | 37 +++++++++++++++++++ ...recatedMethods8317Diagnostic_en.properties | 2 + ...recatedMethods8317Diagnostic_ru.properties | 2 + .../DeprecatedMethods8317DiagnosticTest.java | 25 +++++++++++++ .../DeprecatedMethods8317Diagnostic.bsl | 1 + 7 files changed, 139 insertions(+) create mode 100644 docs/diagnostics/DeprecatedMethods8317.md create mode 100644 docs/en/diagnostics/DeprecatedMethods8317.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317DiagnosticTest.java create mode 100644 src/test/resources/diagnostics/DeprecatedMethods8317Diagnostic.bsl diff --git a/docs/diagnostics/DeprecatedMethods8317.md b/docs/diagnostics/DeprecatedMethods8317.md new file mode 100644 index 00000000000..6fcb1ecdbe5 --- /dev/null +++ b/docs/diagnostics/DeprecatedMethods8317.md @@ -0,0 +1,36 @@ +# () + + + +## + + +## Описание диагностики + + +## Примеры + + +## Источники + + + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Параметр конфигурационного файла + +```json +"": +``` \ No newline at end of file diff --git a/docs/en/diagnostics/DeprecatedMethods8317.md b/docs/en/diagnostics/DeprecatedMethods8317.md new file mode 100644 index 00000000000..4e7e0f78ada --- /dev/null +++ b/docs/en/diagnostics/DeprecatedMethods8317.md @@ -0,0 +1,36 @@ +# + + + +## + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Parameter for config + +```json +"": +``` diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java new file mode 100644 index 00000000000..5be78a2aa68 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java @@ -0,0 +1,37 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCompatibilityMode; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; + +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.INFO, + compatibilityMode = DiagnosticCompatibilityMode.COMPATIBILITY_MODE_8_3_17, + scope = DiagnosticScope.BSL, + minutesToFix = 5, + tags = { + DiagnosticTag.DEPRECATED + } + +) +public class DeprecatedMethods8317Diagnostic extends AbstractFindMethodDiagnostic { + + private static final Pattern DEPRECATED_METHODS_NAMES = Pattern.compile( + "КраткоеПредставлениеОшибки|BriefErrorDescription" + + "ПодробноеПредставлениеОшибки|DetailErrorDescription" + + "ПоказатьИнформациюОбОшибке|ShowErrorInfo", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE + ); + + public DeprecatedMethods8317Diagnostic(DiagnosticInfo info) { + super(info, DEPRECATED_METHODS_NAMES); + } + +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic_en.properties new file mode 100644 index 00000000000..cdbdb85e658 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=\"%s\" method is deprecated. You should use one of ErrorProcessingManager object type methods. +diagnosticName=Using of deprecated platform 8.3.17 global methods diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic_ru.properties new file mode 100644 index 00000000000..fc1fd309efb --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Метод \"%s\" устарел. Следует использовать одноименный метод объекта типа МенеджерОбработкиОшибок +diagnosticName=Использование устаревших глобальных методов платформы 8.3.17 diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317DiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317DiagnosticTest.java new file mode 100644 index 00000000000..b54670902fc --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317DiagnosticTest.java @@ -0,0 +1,25 @@ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class DeprecatedMethods8317DiagnosticTest extends AbstractDiagnosticTest { + DeprecatedMethods8317DiagnosticTest() { + super(DeprecatedMethods8317Diagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(6, 0, 6, 20); + + } +} diff --git a/src/test/resources/diagnostics/DeprecatedMethods8317Diagnostic.bsl b/src/test/resources/diagnostics/DeprecatedMethods8317Diagnostic.bsl new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/src/test/resources/diagnostics/DeprecatedMethods8317Diagnostic.bsl @@ -0,0 +1 @@ + From 0965538937651f0e0dd55635e000587f2eeac69e Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Wed, 29 Apr 2020 15:21:36 +0300 Subject: [PATCH 216/444] =?UTF-8?q?=D0=A0=D0=B0=D1=81=D1=88=D0=B8=D1=80?= =?UTF-8?q?=D0=B5=D0=BD=D0=BE=20=D0=BE=D0=BF=D0=B8=D1=81=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/IsInRoleMethodDiagnostic.md | 15 +++++++++++++-- docs/en/diagnostics/IsInRoleMethodDiagnostic.md | 11 ++++++++++- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/docs/diagnostics/IsInRoleMethodDiagnostic.md b/docs/diagnostics/IsInRoleMethodDiagnostic.md index 677453d4f2a..6c776a63cb8 100644 --- a/docs/diagnostics/IsInRoleMethodDiagnostic.md +++ b/docs/diagnostics/IsInRoleMethodDiagnostic.md @@ -10,8 +10,11 @@ Для проверки прав доступа в коде следует использовать метод ПравоДоступа. В тех случаях, где роль не дает никаких прав на объекты метаданных, а служит только для определения того или иного дополнительного права, -следует использовать метод РольДоступна. При использовании в конфигурации Библиотеки стандартных подсистем (БСП) следует -использовать функцию РолиДоступны общего модуля Пользователи. +следует использовать метод РольДоступна. + +При использовании в конфигурации Библиотеки стандартных подсистем (БСП) следует +использовать функцию РолиДоступны общего модуля Пользователи. +Если в конфигурации не используется БСП, следует обязательно совмещать вызов РольДоступна() с проверкой на ПривилегированныйРежим(). ## Примеры ``` @@ -24,6 +27,14 @@ Если ПравоДоступа("Редактирование", Метаданные.Справочники.СтраныМира) Тогда ... Если ПравоДоступа("Просмотр", Метаданные.Отчеты.ПопулярныеСтраны) Тогда ... ``` +``` +Неправильно: +Если РольДоступна("Казначей") Тогда ... +``` +``` +Правильно: +Если РольДоступна("Казначей") ИЛИ ПривилегированныйРежим() Тогда ... +``` ## Источники ``` @@ -24,6 +25,14 @@ Correct example: If AccessRight("Edit", Metadata.Catalogs.WorldCountries) Then ... If AccessRight("View", Metadata.Reports.PopularCountries) Then ... ``` +``` +Incorrect: +If IsInRole("Paymaster") Then ... +``` +``` +Correct example: +If IsInRole("Paymaster") OR PrivilegedMode() Then ... +``` ## Sources ## Описание диагностики - -## Примеры - - +В платформе 8.3.17 было реализовано свойство глобального контекста ОбработкаОшибок и +стандартная функция Управление настройками обработки ошибок, позволяющая настроить тексты ошибок. +Методы глобального контекста: +* КраткоеПредставлениеОшибки(); +* ПодробноеПредставлениеОшибки(); +* ПоказатьИнформациюОбОшибке() считаются устаревшими. + +Необходимо использовать одноименные методы объекта ОбработкаОшибок. ## Источники +* Источник: [Описание изменений платформы 8.3.17](https://dl03.1c.ru/content/Platform/8_3_17_1386/1cv8upd_8_3_17_1386.htm#27f2dc70-f0cf-11e9-8371-0050569f678a) ## Сниппеты - + ### Экранирование кода ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:DeprecatedMethods8317-off +// BSLLS:DeprecatedMethods8317-on ``` ### Параметр конфигурационного файла ```json -"": -``` \ No newline at end of file +"DeprecatedMethods8317": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 208bf744d25..4951845a0a1 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,9 +8,9 @@ ## Список реализованных диагностик -Общее количество: **102** +Общее количество: **103** -* Дефект кода: **65** +* Дефект кода: **66** * Уязвимость: **2** * Ошибка: **32** * Потенциальная уязвимость: **3** @@ -44,6 +44,7 @@ | [DeprecatedFind](DeprecatedFind.md) | Использование устаревшего метода "Найти" | Да | Незначительный | Дефект кода | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Ограничение на использование устаревшего метода "Сообщить" | Да | Незначительный | Дефект кода | `standard`
`deprecated` | | [DeprecatedMethods8310](DeprecatedMethods8310.md) | Использование устаревшего метода клиентского приложения | Да | Информационный | Дефект кода | `deprecated` | +| [DeprecatedMethods8317](DeprecatedMethods8317.md) | Использование устаревших глобальных методов платформы 8.3.17 | Да | Информационный | Дефект кода | `deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Устаревшее использование типа "УправляемаяФорма" | Да | Информационный | Дефект кода | `standard`
`deprecated` | | [DuplicateRegion](DuplicateRegion.md) | Повторяющиеся разделы модуля | Да | Информационный | Дефект кода | `standard` | | [EmptyCodeBlock](EmptyCodeBlock.md) | Пустой блок кода | Да | Важный | Дефект кода | `badpractice`
`suspicious` | diff --git a/docs/en/diagnostics/DeprecatedMethods8317.md b/docs/en/diagnostics/DeprecatedMethods8317.md index 4e7e0f78ada..ddc9556ada3 100644 --- a/docs/en/diagnostics/DeprecatedMethods8317.md +++ b/docs/en/diagnostics/DeprecatedMethods8317.md @@ -1,16 +1,20 @@ -# +# Using of deprecated platform 8.3.17 global methods (DeprecatedMethods8317) - - -## +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Code smell` | `BSL` | `Info` | `Yes` | `5` | `deprecated` | ## Description +In platform 8.3.17, the global context property ErrorProcessing was implemented. -## Examples - +The following global context methods are deprecated and should not be used: +* BriefErrorDescription() +* DetailErrorDescription() +* ShowErrorInfo() +You should use the same methods of the ErrorProcessing object instead. ## Sources +* Source: [Platform 8.3.17 changelog](https://dl03.1c.ru/content/Platform/8_3_17_1386/1cv8upd_8_3_17_1386.htm) ## Snippets - + ### Diagnostic ignorance in code ```bsl -// BSLLS:-off -// BSLLS:-on +// BSLLS:DeprecatedMethods8317-off +// BSLLS:DeprecatedMethods8317-on ``` ### Parameter for config ```json -"": +"DeprecatedMethods8317": false ``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 5ece9f38a77..831a87b67b1 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,10 +8,10 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **102** +Total: **103** * Error: **32** -* Code smell: **65** +* Code smell: **66** * Vulnerability: **2** * Security Hotspot: **3** @@ -44,6 +44,7 @@ Total: **102** | [DeprecatedFind](DeprecatedFind.md) | Using of the deprecated method "Find" | Yes | Minor | Code smell | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Restriction on the use of deprecated "Message" method | Yes | Minor | Code smell | `standard`
`deprecated` | | [DeprecatedMethods8310](DeprecatedMethods8310.md) | Deprecated client application method. | Yes | Info | Code smell | `deprecated` | +| [DeprecatedMethods8317](DeprecatedMethods8317.md) | Using of deprecated platform 8.3.17 global methods | Yes | Info | Code smell | `deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Deprecated ManagedForm type | Yes | Info | Code smell | `standard`
`deprecated` | | [DuplicateRegion](DuplicateRegion.md) | Duplicate regions | Yes | Info | Code smell | `standard` | | [EmptyCodeBlock](EmptyCodeBlock.md) | Empty code block | Yes | Major | Code smell | `badpractice`
`suspicious` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java index 372bb6b70b0..f1657a62c2f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java @@ -1,3 +1,24 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCompatibilityMode; diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index 3b2b537e167..149f5e77bca 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -326,6 +326,16 @@ "title": "Deprecated client application method.", "$id": "#/definitions/DeprecatedMethods8310" }, + "DeprecatedMethods8317": { + "description": "Using of deprecated platform 8.3.17 global methods", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Using of deprecated platform 8.3.17 global methods", + "$id": "#/definitions/DeprecatedMethods8317" + }, "DeprecatedTypeManagedForm": { "description": "Deprecated ManagedForm type", "default": true, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index dd5960db17f..f2b6b56669b 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -104,6 +104,9 @@ "DeprecatedMethods8310": { "$ref": "parameters-schema.json#/definitions/DeprecatedMethods8310" }, + "DeprecatedMethods8317": { + "$ref": "parameters-schema.json#/definitions/DeprecatedMethods8317" + }, "DeprecatedTypeManagedForm": { "$ref": "parameters-schema.json#/definitions/DeprecatedTypeManagedForm" }, diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317DiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317DiagnosticTest.java index 67e2321cce1..05dacc261d5 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317DiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317DiagnosticTest.java @@ -1,3 +1,24 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; import org.eclipse.lsp4j.Diagnostic; From 11a2f46dc91987519f837f5429e0579ca46a36a9 Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Wed, 29 Apr 2020 12:00:47 +0300 Subject: [PATCH 219/444] =?UTF-8?q?=D0=9D=D0=BE=D0=B2=D0=B0=D1=8F=20=D0=B4?= =?UTF-8?q?=D0=B8=D0=B0=D0=B3=D0=BD=D0=BE=D1=81=D1=82=D0=B8=D0=BA=D0=B0:?= =?UTF-8?q?=20=D0=9E=D1=88=D0=B8=D0=B1=D0=BA=D0=B0=20=D0=BD=D0=B5=D1=8F?= =?UTF-8?q?=D0=B2=D0=BD=D0=BE=D0=B3=D0=BE=20=D0=BF=D1=80=D0=B5=D0=BE=D0=B1?= =?UTF-8?q?=D1=80=D0=B0=D0=B7=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D1=8F=20=D0=91?= =?UTF-8?q?=D0=B5=D0=B7=D0=BE=D0=BF=D0=B0=D1=81=D0=BD=D1=8B=D0=B9=D0=A0?= =?UTF-8?q?=D0=B5=D0=B6=D0=B8=D0=BC=20=D0=BA=20=D1=82=D0=B8=D0=BF=D1=83=20?= =?UTF-8?q?=D0=91=D1=83=D0=BB=D0=B5=D0=B2=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/UnsafeSafeModeMethodCall.md | 56 +++++++++++++ docs/diagnostics/index.md | 3 +- .../diagnostics/UnsafeSafeModeMethodCall.md | 52 ++++++++++++ docs/en/diagnostics/index.md | 3 +- .../UnsafeSafeModeMethodCallDiagnostic.java | 81 +++++++++++++++++++ .../configuration/parameters-schema.json | 10 +++ .../languageserver/configuration/schema.json | 3 + ...SafeModeMethodCallDiagnostic_en.properties | 2 + ...SafeModeMethodCallDiagnostic_ru.properties | 2 + ...nsafeSafeModeMethodCallDiagnosticTest.java | 47 +++++++++++ .../UnsafeSafeModeMethodCallDiagnostic.bsl | 15 ++++ 11 files changed, 272 insertions(+), 2 deletions(-) create mode 100644 docs/diagnostics/UnsafeSafeModeMethodCall.md create mode 100644 docs/en/diagnostics/UnsafeSafeModeMethodCall.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl diff --git a/docs/diagnostics/UnsafeSafeModeMethodCall.md b/docs/diagnostics/UnsafeSafeModeMethodCall.md new file mode 100644 index 00000000000..6feb15e83ba --- /dev/null +++ b/docs/diagnostics/UnsafeSafeModeMethodCall.md @@ -0,0 +1,56 @@ +# Небезопасное использование функции БезопасныйРежим() (UnsafeSafeModeMethodCall) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Ошибка` | `BSL` | `Блокирующий` | `Да` | `1` | `standard`
`deprecated`
`error` | + + +## Описание диагностики + +Разработчики допускают ошибки, используя неявное преобразование БезопасныйРежим к типу Булево + +На самом деле этот метод может вернуть имя профиля строкой при включенном профиле безопасности в кластере, а может Истина или Ложь. + +Cледует использовать БезопасныйРежим() <> Ложь или БезопасныйРежим() = Ложь +## Примеры + +Неправильно: +``` +Если БезопасныйРежим() Тогда + // Логика выполнения в безопасном режиме... +КонецЕсли; + +Если Не БезопасныйРежим() Тогда + // Логика выполнения в небезопасном режиме... +КонецЕсли; +``` +Правильно: +``` +Если БезопасныйРежим() <> Ложь Тогда + // Логика выполнения в безопасном режиме... +КонецЕсли +``` +## Источники + + +* Источник: [Тип значения, возвращаемый методом "БезопасныйРежим()](https://its.1c.ru/db/metod8dev#content:5293:hdoc:izmenenie_bezopasnyjrezhim) + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:UnsafeSafeModeMethodCall-off +// BSLLS:UnsafeSafeModeMethodCall-on +``` + +### Параметр конфигурационного файла + +```json +"UnsafeSafeModeMethodCall": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 4ac56f2beda..d825cb6c807 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -12,7 +12,7 @@ * Дефект кода: **66** * Уязвимость: **2** -* Ошибка: **32** +* Ошибка: **33** * Потенциальная уязвимость: **3** | Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги | @@ -103,6 +103,7 @@ | [UnaryPlusInConcatenation](UnaryPlusInConcatenation.md) | Унарный плюс в конкатенации строк | Да | Блокирующий | Ошибка | `suspicious`
`brainoverload` | | [UnknownPreprocessorSymbol](UnknownPreprocessorSymbol.md) | Неизвестный символ препроцессора | Да | Критичный | Ошибка | `standard`
`error` | | [UnreachableCode](UnreachableCode.md) | Недостижимый код | Да | Незначительный | Ошибка | `design`
`suspicious` | +| [UnsafeSafeModeMethodCall](UnsafeSafeModeMethodCall.md) | Небезопасное использование функции БезопасныйРежим() | Да | Блокирующий | Ошибка | `standard`
`deprecated`
`error` | | [UnusedLocalMethod](UnusedLocalMethod.md) | Неиспользуемый локальный метод | Да | Важный | Дефект кода | `standard`
`suspicious` | | [UnusedParameters](UnusedParameters.md) | Неиспользуемый параметр | Да | Важный | Дефект кода | `design` | | [UseLessForEach](UseLessForEach.md) | Бесполезный перебор коллекции | Да | Критичный | Ошибка | `clumsy` | diff --git a/docs/en/diagnostics/UnsafeSafeModeMethodCall.md b/docs/en/diagnostics/UnsafeSafeModeMethodCall.md new file mode 100644 index 00000000000..4f145f8f84d --- /dev/null +++ b/docs/en/diagnostics/UnsafeSafeModeMethodCall.md @@ -0,0 +1,52 @@ +# Unsafe SafeMode method call (UnsafeSafeModeMethodCall) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Error` | `BSL` | `Blocker` | `Yes` | `1` | `standard`
`deprecated`
`error` | + + +## Description + +Developers make mistakes using the implicit conversion SafeMode() to Boolean type + +In fact, this method can return the profile name with a string. + +Use SafeMode() <> False or SafeMode() = False +## Examples + +Incorrect: +``` +If SafeMode() Then +// some code +EndIf; +``` +Correct: +``` +If SafeMode() = True Then +// some code +EndIf; +``` +## Sources + + +Source: [SafeMode method](https://its.1c.ru/db/metod8dev#content:5293:hdoc:izmenenie_bezopasnyjrezhim) + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:UnsafeSafeModeMethodCall-off +// BSLLS:UnsafeSafeModeMethodCall-on +``` + +### Parameter for config + +```json +"UnsafeSafeModeMethodCall": false +``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index ed79ba2b9a8..6a5d76186b0 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -10,7 +10,7 @@ To escape individual sections of code or files from triggering diagnostics, you Total: **103** -* Error: **32** +* Error: **33** * Code smell: **66** * Vulnerability: **2** * Security Hotspot: **3** @@ -103,6 +103,7 @@ Total: **103** | [UnaryPlusInConcatenation](UnaryPlusInConcatenation.md) | Unary Plus sign in string concatenation | Yes | Blocker | Error | `suspicious`
`brainoverload` | | [UnknownPreprocessorSymbol](UnknownPreprocessorSymbol.md) | Unknown preprocessor symbol | Yes | Critical | Error | `standard`
`error` | | [UnreachableCode](UnreachableCode.md) | Unreachable Code | Yes | Minor | Error | `design`
`suspicious` | +| [UnsafeSafeModeMethodCall](UnsafeSafeModeMethodCall.md) | Unsafe SafeMode method call | Yes | Blocker | Error | `standard`
`deprecated`
`error` | | [UnusedLocalMethod](UnusedLocalMethod.md) | Unused local method | Yes | Major | Code smell | `standard`
`suspicious` | | [UnusedParameters](UnusedParameters.md) | Unused parameter | Yes | Major | Code smell | `design` | | [UseLessForEach](UseLessForEach.md) | Useless collection iteration | Yes | Critical | Error | `clumsy` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java new file mode 100644 index 00000000000..6016c758fd5 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java @@ -0,0 +1,81 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.Trees; +import com.github._1c_syntax.bsl.parser.BSLParser; + +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.ERROR, + severity = DiagnosticSeverity.BLOCKER, + scope = DiagnosticScope.BSL, + minutesToFix = 1, + tags = { + DiagnosticTag.STANDARD, + DiagnosticTag.DEPRECATED, + DiagnosticTag.ERROR + } + +) +public class UnsafeSafeModeMethodCallDiagnostic extends AbstractFindMethodDiagnostic { + + private static final Pattern SAFE_MODE_METHOD_NAME = Pattern.compile( + "(БезопасныйРежим|SafeMode)", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE + ); + + public UnsafeSafeModeMethodCallDiagnostic(DiagnosticInfo info) { + super(info, SAFE_MODE_METHOD_NAME); + } + + @Override + protected boolean checkMethodCall(BSLParser.MethodCallContext ctx) { + return false; + } + + @Override + protected boolean checkGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { + + var rootIfNode = Trees.getRootParent(ctx, BSLParser.RULE_ifStatement); + var rootExpressionNode = Trees.getRootParent(ctx, BSLParser.RULE_expression); + var currentRootMember = Trees.getRootParent(ctx, BSLParser.RULE_member); + if (rootIfNode == null || rootExpressionNode == null || currentRootMember == null) { + return false; + } + + int indexOfCurrentMemberNode = rootExpressionNode.children.indexOf(currentRootMember); + if (indexOfCurrentMemberNode != rootExpressionNode.getChildCount() - 1) { + var nextNode = rootExpressionNode.children.get(indexOfCurrentMemberNode + 1); + return !(Trees.nodeContains(nextNode, BSLParser.RULE_compareOperation)); + } else { + return true; + } + } +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index 39f207391b7..b4b5c1947fd 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -1118,6 +1118,16 @@ "title": "Unreachable Code", "$id": "#/definitions/UnreachableCode" }, + "UnsafeSafeModeMethodCall": { + "description": "Unsafe SafeMode method call", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Unsafe SafeMode method call", + "$id": "#/definitions/UnsafeSafeModeMethodCall" + }, "UnusedLocalMethod": { "description": "Unused local method", "default": true, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index b2730596359..dfb3b914f9b 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -281,6 +281,9 @@ "UnreachableCode": { "$ref": "parameters-schema.json#/definitions/UnreachableCode" }, + "UnsafeSafeModeMethodCall": { + "$ref": "parameters-schema.json#/definitions/UnsafeSafeModeMethodCall" + }, "UnusedLocalMethod": { "$ref": "parameters-schema.json#/definitions/UnusedLocalMethod" }, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic_en.properties new file mode 100644 index 00000000000..5df6b34c293 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Use explicit comparison with boolean when calling SafeMode method +diagnosticName=Unsafe SafeMode method call diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic_ru.properties new file mode 100644 index 00000000000..9f32d413e9f --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Используйте явное сравнение с Булево при вызове БезопасныйРежим() +diagnosticName=Небезопасное использование функции БезопасныйРежим() diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java new file mode 100644 index 00000000000..e62504d631f --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java @@ -0,0 +1,47 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class UnsafeSafeModeMethodCallDiagnosticTest extends AbstractDiagnosticTest { + UnsafeSafeModeMethodCallDiagnosticTest() { + super(UnsafeSafeModeMethodCallDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(3); + assertThat(diagnostics, true) + .hasRange(1, 9, 1, 24) + .hasRange(3, 17, 3, 32) + .hasRange(7, 12, 7, 27); + } +} diff --git a/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl b/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl new file mode 100644 index 00000000000..d9e0685c423 --- /dev/null +++ b/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl @@ -0,0 +1,15 @@ +Процедура Тест() + Если БезопасныйРежим() ИЛИ Тест = Истина Тогда // Срабатывание + // Логика выполнения в безопасном режиме... + ИначеЕсли Не БезопасныйРежим() Тогда // Срабатывание + // Логика выполнения в небезопасном режиме... + КонецЕсли; + + Если Не БезопасныйРежим() Тогда // Срабатывание + // Логика выполнения в небезопасном режиме... + КонецЕсли; + + Если БезопасныйРежим() <> Ложь Тогда // Нет срабатывания + // Логика выполнения в безопасном режиме... + КонецЕсли; +КонецПроцедуры \ No newline at end of file From ba9759c5b2643d45223332a1b8cbe287ba194fce Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Wed, 29 Apr 2020 13:10:44 +0300 Subject: [PATCH 220/444] =?UTF-8?q?=D0=A3=D1=81=D1=82=D0=B0=D0=BD=D0=BE?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=20=D1=80=D0=B5=D0=B6=D0=B8=D0=BC=20?= =?UTF-8?q?=D1=81=D0=BE=D0=B2=D0=BC=D0=B5=D1=81=D1=82=D0=B8=D0=BC=D0=BE?= =?UTF-8?q?=D1=81=D1=82=D0=B8=208.3.1=20=D0=9F=D0=BE=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=D0=B0=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/UnsafeSafeModeMethodCall.md | 10 ++++++---- docs/en/diagnostics/UnsafeSafeModeMethodCall.md | 10 +++++++--- .../UnsafeSafeModeMethodCallDiagnostic.java | 2 ++ 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/docs/diagnostics/UnsafeSafeModeMethodCall.md b/docs/diagnostics/UnsafeSafeModeMethodCall.md index 6feb15e83ba..c2199ad180c 100644 --- a/docs/diagnostics/UnsafeSafeModeMethodCall.md +++ b/docs/diagnostics/UnsafeSafeModeMethodCall.md @@ -7,11 +7,13 @@ ## Описание диагностики -Разработчики допускают ошибки, используя неявное преобразование БезопасныйРежим к типу Булево +В "1С:Предприятии 8.3" метод глобального контекста БезопасныйРежим() возвращает тип Строка, +если безопасный режим был установлен с указанием имени профиля безопасности. -На самом деле этот метод может вернуть имя профиля строкой при включенном профиле безопасности в кластере, а может Истина или Ложь. - -Cледует использовать БезопасныйРежим() <> Ложь или БезопасныйРежим() = Ложь +Использования метода БезопасныйРежим(), + в которых результат неявно преобразовывается к типу Булево является небезопасным, + необходимо исправить на код с явным сравнением результата со значением Ложь. + Таким образом, при установленном профиле безопасности код будет выполняться так же, как и в безопасном режиме. ## Примеры Неправильно: diff --git a/docs/en/diagnostics/UnsafeSafeModeMethodCall.md b/docs/en/diagnostics/UnsafeSafeModeMethodCall.md index 4f145f8f84d..f0387863219 100644 --- a/docs/en/diagnostics/UnsafeSafeModeMethodCall.md +++ b/docs/en/diagnostics/UnsafeSafeModeMethodCall.md @@ -7,11 +7,15 @@ ## Description -Developers make mistakes using the implicit conversion SafeMode() to Boolean type +In "1C: Enterprise 8.3" the global context method SafeMode () returns the type String, +if safe mode was set with the name of the security profile. -In fact, this method can return the profile name with a string. +Using the Safe Mode () method, + in which the result is implicitly converted to a Boolean type is unsafe, + must be corrected for the code with an explicit comparison of the result with the value False. + Thus, with the installed security profile, the code will be executed in the same way as in the safe mode. -Use SafeMode() <> False or SafeMode() = False +Use SafeMode() <> False ## Examples Incorrect: diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java index 6016c758fd5..eb106484d9c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java @@ -21,6 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCompatibilityMode; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; @@ -36,6 +37,7 @@ type = DiagnosticType.ERROR, severity = DiagnosticSeverity.BLOCKER, scope = DiagnosticScope.BSL, + compatibilityMode = DiagnosticCompatibilityMode.COMPATIBILITY_MODE_8_3_1, minutesToFix = 1, tags = { DiagnosticTag.STANDARD, From 139b0acfc11d5e499b5afb8b04a6685722a42690 Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Wed, 29 Apr 2020 14:39:24 +0300 Subject: [PATCH 221/444] =?UTF-8?q?1.=20=D0=A3=D0=B1=D1=80=D0=B0=D0=BD=20?= =?UTF-8?q?=D1=82=D0=B5=D0=B3=20Standard=202.=20=D0=94=D0=BE=D0=B1=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=D0=B0=20=D0=BF=D1=80=D0=BE=D0=BF=D1=83?= =?UTF-8?q?=D1=89=D0=B5=D0=BD=D0=BD=D0=B0=D1=8F=20=D0=BF=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B5=D1=80=D0=BA=D0=B0=20=D1=80=D0=B5=D0=B3=D1=83=D0=BB=D1=8F?= =?UTF-8?q?=D1=80=D0=BA=D0=BE=D0=B9=203.=20=D0=A0=D0=B0=D1=81=D1=88=D0=B8?= =?UTF-8?q?=D1=80=D0=B5=D0=BD=D1=8B=20=D1=82=D0=B5=D1=81=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/UnsafeSafeModeMethodCall.md | 2 +- docs/diagnostics/index.md | 2 +- docs/en/diagnostics/UnsafeSafeModeMethodCall.md | 2 +- docs/en/diagnostics/index.md | 2 +- .../diagnostics/UnsafeSafeModeMethodCallDiagnostic.java | 4 ++-- .../diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl | 4 ++++ 6 files changed, 10 insertions(+), 6 deletions(-) diff --git a/docs/diagnostics/UnsafeSafeModeMethodCall.md b/docs/diagnostics/UnsafeSafeModeMethodCall.md index c2199ad180c..35cd5e5fb68 100644 --- a/docs/diagnostics/UnsafeSafeModeMethodCall.md +++ b/docs/diagnostics/UnsafeSafeModeMethodCall.md @@ -2,7 +2,7 @@ | Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Ошибка` | `BSL` | `Блокирующий` | `Да` | `1` | `standard`
`deprecated`
`error` | +| `Ошибка` | `BSL` | `Блокирующий` | `Да` | `1` | `deprecated`
`error` | ## Описание диагностики diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index d825cb6c807..128ce5cfcfa 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -103,7 +103,7 @@ | [UnaryPlusInConcatenation](UnaryPlusInConcatenation.md) | Унарный плюс в конкатенации строк | Да | Блокирующий | Ошибка | `suspicious`
`brainoverload` | | [UnknownPreprocessorSymbol](UnknownPreprocessorSymbol.md) | Неизвестный символ препроцессора | Да | Критичный | Ошибка | `standard`
`error` | | [UnreachableCode](UnreachableCode.md) | Недостижимый код | Да | Незначительный | Ошибка | `design`
`suspicious` | -| [UnsafeSafeModeMethodCall](UnsafeSafeModeMethodCall.md) | Небезопасное использование функции БезопасныйРежим() | Да | Блокирующий | Ошибка | `standard`
`deprecated`
`error` | +| [UnsafeSafeModeMethodCall](UnsafeSafeModeMethodCall.md) | Небезопасное использование функции БезопасныйРежим() | Да | Блокирующий | Ошибка | `deprecated`
`error` | | [UnusedLocalMethod](UnusedLocalMethod.md) | Неиспользуемый локальный метод | Да | Важный | Дефект кода | `standard`
`suspicious` | | [UnusedParameters](UnusedParameters.md) | Неиспользуемый параметр | Да | Важный | Дефект кода | `design` | | [UseLessForEach](UseLessForEach.md) | Бесполезный перебор коллекции | Да | Критичный | Ошибка | `clumsy` | diff --git a/docs/en/diagnostics/UnsafeSafeModeMethodCall.md b/docs/en/diagnostics/UnsafeSafeModeMethodCall.md index f0387863219..2251e862871 100644 --- a/docs/en/diagnostics/UnsafeSafeModeMethodCall.md +++ b/docs/en/diagnostics/UnsafeSafeModeMethodCall.md @@ -2,7 +2,7 @@ | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Error` | `BSL` | `Blocker` | `Yes` | `1` | `standard`
`deprecated`
`error` | +| `Error` | `BSL` | `Blocker` | `Yes` | `1` | `deprecated`
`error` | ## Description diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 6a5d76186b0..5a81c30c731 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -103,7 +103,7 @@ Total: **103** | [UnaryPlusInConcatenation](UnaryPlusInConcatenation.md) | Unary Plus sign in string concatenation | Yes | Blocker | Error | `suspicious`
`brainoverload` | | [UnknownPreprocessorSymbol](UnknownPreprocessorSymbol.md) | Unknown preprocessor symbol | Yes | Critical | Error | `standard`
`error` | | [UnreachableCode](UnreachableCode.md) | Unreachable Code | Yes | Minor | Error | `design`
`suspicious` | -| [UnsafeSafeModeMethodCall](UnsafeSafeModeMethodCall.md) | Unsafe SafeMode method call | Yes | Blocker | Error | `standard`
`deprecated`
`error` | +| [UnsafeSafeModeMethodCall](UnsafeSafeModeMethodCall.md) | Unsafe SafeMode method call | Yes | Blocker | Error | `deprecated`
`error` | | [UnusedLocalMethod](UnusedLocalMethod.md) | Unused local method | Yes | Major | Code smell | `standard`
`suspicious` | | [UnusedParameters](UnusedParameters.md) | Unused parameter | Yes | Major | Code smell | `design` | | [UseLessForEach](UseLessForEach.md) | Useless collection iteration | Yes | Critical | Error | `clumsy` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java index eb106484d9c..1b0b2b9717a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java @@ -40,7 +40,6 @@ compatibilityMode = DiagnosticCompatibilityMode.COMPATIBILITY_MODE_8_3_1, minutesToFix = 1, tags = { - DiagnosticTag.STANDARD, DiagnosticTag.DEPRECATED, DiagnosticTag.ERROR } @@ -68,7 +67,8 @@ protected boolean checkGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { var rootIfNode = Trees.getRootParent(ctx, BSLParser.RULE_ifStatement); var rootExpressionNode = Trees.getRootParent(ctx, BSLParser.RULE_expression); var currentRootMember = Trees.getRootParent(ctx, BSLParser.RULE_member); - if (rootIfNode == null || rootExpressionNode == null || currentRootMember == null) { + if (!SAFE_MODE_METHOD_NAME.matcher(ctx.methodName().getText()).matches() + || rootIfNode == null || rootExpressionNode == null || currentRootMember == null) { return false; } diff --git a/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl b/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl index d9e0685c423..d33de2443ab 100644 --- a/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl +++ b/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl @@ -12,4 +12,8 @@ Если БезопасныйРежим() <> Ложь Тогда // Нет срабатывания // Логика выполнения в безопасном режиме... КонецЕсли; + + Если Тест() ИЛИ Тест = Истина Тогда // Нет срабатывания + // код + КонецЕсли; КонецПроцедуры \ No newline at end of file From 01986dc6875e8e5ffa4d8ea75c926edd2084e65c Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Wed, 29 Apr 2020 14:43:57 +0300 Subject: [PATCH 222/444] =?UTF-8?q?return=20=D0=B2=D1=8B=D0=BD=D0=B5=D1=81?= =?UTF-8?q?=D0=B5=D0=BD=20=D0=B2=20=D0=BA=D0=BE=D0=BD=D0=B5=D1=86=20=D0=BC?= =?UTF-8?q?=D0=B5=D1=82=D0=BE=D0=B4=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/UnsafeSafeModeMethodCallDiagnostic.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java index 1b0b2b9717a..e516b3f3813 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java @@ -76,8 +76,8 @@ protected boolean checkGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { if (indexOfCurrentMemberNode != rootExpressionNode.getChildCount() - 1) { var nextNode = rootExpressionNode.children.get(indexOfCurrentMemberNode + 1); return !(Trees.nodeContains(nextNode, BSLParser.RULE_compareOperation)); - } else { - return true; } + + return true; } } From ad56201be55f180c777bf906bf0693fd3425a672 Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Wed, 29 Apr 2020 15:50:05 +0300 Subject: [PATCH 223/444] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D0=B2=D0=B5=D1=80?= =?UTF-8?q?=D0=BA=D0=B0=20=D1=80=D0=B5=D0=B3=D1=83=D0=BB=D1=8F=D1=80=D0=BA?= =?UTF-8?q?=D0=BE=D0=B9=20=D0=B2=D1=8B=D0=BD=D0=B5=D1=81=D0=B5=D0=BD=D0=B0?= =?UTF-8?q?=20=D0=B2=D0=BF=D0=B5=D1=80=D0=B5=D0=B4=20=D1=80=D0=B5=D0=BA?= =?UTF-8?q?=D1=83=D1=80=D1=81=D0=B8=D0=B2=D0=BD=D1=8B=D1=85=20=D0=BE=D0=B1?= =?UTF-8?q?=D1=85=D0=BE=D0=B4=D0=BE=D0=B2=20=D0=B4=D0=B5=D1=80=D0=B5=D0=B2?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UnsafeSafeModeMethodCallDiagnostic.java | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java index e516b3f3813..1cac49560e0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java @@ -30,6 +30,7 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.utils.Trees; import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import java.util.regex.Pattern; @@ -64,11 +65,17 @@ protected boolean checkMethodCall(BSLParser.MethodCallContext ctx) { @Override protected boolean checkGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { - var rootIfNode = Trees.getRootParent(ctx, BSLParser.RULE_ifStatement); - var rootExpressionNode = Trees.getRootParent(ctx, BSLParser.RULE_expression); - var currentRootMember = Trees.getRootParent(ctx, BSLParser.RULE_member); - if (!SAFE_MODE_METHOD_NAME.matcher(ctx.methodName().getText()).matches() - || rootIfNode == null || rootExpressionNode == null || currentRootMember == null) { + BSLParserRuleContext rootIfNode = null; + BSLParserRuleContext rootExpressionNode = null; + BSLParserRuleContext currentRootMember = null; + + if (SAFE_MODE_METHOD_NAME.matcher(ctx.methodName().getText()).matches()) { + rootIfNode = Trees.getRootParent(ctx, BSLParser.RULE_ifStatement); + rootExpressionNode = Trees.getRootParent(ctx, BSLParser.RULE_expression); + currentRootMember = Trees.getRootParent(ctx, BSLParser.RULE_member); + } + + if (rootIfNode == null || rootExpressionNode == null || currentRootMember == null) { return false; } From 091366a51fa0c1cd6730823f95f15fe01f23b40e Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Wed, 29 Apr 2020 17:56:02 +0300 Subject: [PATCH 224/444] =?UTF-8?q?=D0=BC=D0=B8=D0=BD=D0=B8=20=D1=80=D0=B5?= =?UTF-8?q?=D1=84=D0=B0=D0=BA=D1=82=D0=BE=D1=80=D0=B8=D0=BD=D0=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UnsafeSafeModeMethodCallDiagnostic.java | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java index 1cac49560e0..77145d8d86e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java @@ -65,16 +65,14 @@ protected boolean checkMethodCall(BSLParser.MethodCallContext ctx) { @Override protected boolean checkGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { - BSLParserRuleContext rootIfNode = null; - BSLParserRuleContext rootExpressionNode = null; - BSLParserRuleContext currentRootMember = null; - - if (SAFE_MODE_METHOD_NAME.matcher(ctx.methodName().getText()).matches()) { - rootIfNode = Trees.getRootParent(ctx, BSLParser.RULE_ifStatement); - rootExpressionNode = Trees.getRootParent(ctx, BSLParser.RULE_expression); - currentRootMember = Trees.getRootParent(ctx, BSLParser.RULE_member); + if (!SAFE_MODE_METHOD_NAME.matcher(ctx.methodName().getText()).matches()) { + return false; } + BSLParserRuleContext rootIfNode = Trees.getRootParent(ctx, BSLParser.RULE_ifStatement); + BSLParserRuleContext rootExpressionNode = Trees.getRootParent(ctx, BSLParser.RULE_expression); + BSLParserRuleContext currentRootMember = Trees.getRootParent(ctx, BSLParser.RULE_member); + if (rootIfNode == null || rootExpressionNode == null || currentRootMember == null) { return false; } From 6338854611832282dd04485cb60c2dc7de73982d Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Wed, 29 Apr 2020 17:57:26 +0300 Subject: [PATCH 225/444] precommit --- docs/diagnostics/index.md | 2 +- docs/en/diagnostics/index.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 128ce5cfcfa..c5bd626e33a 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,7 +8,7 @@ ## Список реализованных диагностик -Общее количество: **103** +Общее количество: **104** * Дефект кода: **66** * Уязвимость: **2** diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 5a81c30c731..47b90c13659 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,7 +8,7 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **103** +Total: **104** * Error: **33** * Code smell: **66** From e47afab3f7c1b34737be0922d23f8acf5cebee2c Mon Sep 17 00:00:00 2001 From: evgeniy Date: Wed, 29 Apr 2020 21:32:38 +0300 Subject: [PATCH 226/444] Some cleanups. --- .../context/DocumentContext.java | 23 +++++++------------ .../diagnostics/EmptyRegionDiagnostic.java | 8 +++---- 2 files changed, 11 insertions(+), 20 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java index 2836d421a62..c6806778b40 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java @@ -54,6 +54,7 @@ import java.util.Map; import java.util.Optional; import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Predicate; import java.util.stream.Collectors; import static java.util.Objects.requireNonNull; @@ -273,17 +274,11 @@ private MetricStorage computeMetrics() { metricsTemp.setFunctions(Math.toIntExact(methodsUnboxed.stream().filter(MethodSymbol::isFunction).count())); metricsTemp.setProcedures(methodsUnboxed.size() - metricsTemp.getFunctions()); - int ncloc = (int) getTokensFromDefaultChannel().stream() - .map(Token::getLine) - .distinct() - .count(); - - metricsTemp.setNcloc(ncloc); - int[] nclocData = getTokensFromDefaultChannel().stream() .mapToInt(Token::getLine) .distinct().toArray(); metricsTemp.setNclocData(nclocData); + metricsTemp.setNcloc(nclocData.length); metricsTemp.setCovlocData(computeCovlocData()); @@ -296,13 +291,11 @@ private MetricStorage computeMetrics() { } metricsTemp.setLines(lines); - int comments; - final List commentsUnboxed = getComments(); - if (commentsUnboxed.isEmpty()) { - comments = 0; - } else { - comments = (int) commentsUnboxed.stream().map(Token::getLine).distinct().count(); - } + int comments = (int) getComments() + .stream() + .map(Token::getLine) + .distinct() + .count(); metricsTemp.setComments(comments); int statements = Trees.findAllRuleNodes(getAst(), BSLParser.RULE_statement).size(); @@ -317,7 +310,7 @@ private MetricStorage computeMetrics() { private int[] computeCovlocData() { return Trees.getDescendants(getAst()).stream() - .filter(node -> !(node instanceof TerminalNodeImpl)) + .filter(Predicate.not(TerminalNodeImpl.class::isInstance)) .filter(DocumentContext::mustCovered) .mapToInt(node -> ((BSLParserRuleContext) node).getStart().getLine()) .distinct().toArray(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java index dc8cbca0c70..a8d3c5e5624 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java @@ -97,11 +97,6 @@ public List getQuickFixes( for (Diagnostic diagnostic : diagnostics) { int diagnosticStartLine = diagnostic.getRange().getStart().getLine(); - Position diagnosticRangeStart = diagnostic.getRange().getStart(); - diagnosticRangeStart = new Position( - diagnosticRangeStart.getLine(), - diagnosticRangeStart.getCharacter() - 1 - ); Optional optionalRegionSymbol = documentContext.getSymbolTree().getRegionsFlat() .stream() @@ -121,6 +116,9 @@ public List getQuickFixes( maxDiagnosticEndLine = diagnosticEndLine; } + int diagnosticStartCharacter = diagnostic.getRange().getStart().getCharacter() - 1; + Position diagnosticRangeStart = new Position(diagnosticStartLine, diagnosticStartCharacter); + Position diagnosticRangeEnd = new Position( diagnosticEndLine + 1, 0 From f2004a9df109e885bed984c8d156c8743f3132f5 Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Thu, 30 Apr 2020 12:01:34 +0300 Subject: [PATCH 227/444] =?UTF-8?q?1.=20=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B8=D0=B7=20develop=202.=20?= =?UTF-8?q?=D0=97=D0=B0=D0=BC=D0=B5=D0=BD=D0=B0=20=D0=BD=D0=B0=20AbstractF?= =?UTF-8?q?indMethod=203.=20=D0=94=D0=BE=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=BA=D0=B0=20AbstractFindMethod=20-=20=D0=B4=D0=BE=D0=B1?= =?UTF-8?q?=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=BE=20=D0=BF=D1=80=D0=BE=D0=BA?= =?UTF-8?q?=D0=B8=D0=B4=D1=8B=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5=20=D1=81=D0=BE?= =?UTF-8?q?=D0=BE=D0=B1=D1=89=D0=B5=D0=BD=D0=B8=D0=B9=204.=20precommit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/index.md | 5 +++-- docs/en/diagnostics/index.md | 5 +++-- .../AbstractFindMethodDiagnostic.java | 9 +++++++-- .../DeprecatedMethods8317Diagnostic.java | 20 +++++++++++-------- 4 files changed, 25 insertions(+), 14 deletions(-) diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index c5bd626e33a..bced0c76ef5 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,9 +8,9 @@ ## Список реализованных диагностик -Общее количество: **104** +Общее количество: **105** -* Дефект кода: **66** +* Дефект кода: **67** * Уязвимость: **2** * Ошибка: **33** * Потенциальная уязвимость: **3** @@ -44,6 +44,7 @@ | [DeprecatedFind](DeprecatedFind.md) | Использование устаревшего метода "Найти" | Да | Незначительный | Дефект кода | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Ограничение на использование устаревшего метода "Сообщить" | Да | Незначительный | Дефект кода | `standard`
`deprecated` | | [DeprecatedMethods8310](DeprecatedMethods8310.md) | Использование устаревшего метода клиентского приложения | Да | Информационный | Дефект кода | `deprecated` | +| [DeprecatedMethods8317](DeprecatedMethods8317.md) | Использование устаревших глобальных методов платформы 8.3.17 | Да | Информационный | Дефект кода | `deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Устаревшее использование типа "УправляемаяФорма" | Да | Информационный | Дефект кода | `standard`
`deprecated` | | [DuplicateRegion](DuplicateRegion.md) | Повторяющиеся разделы модуля | Да | Информационный | Дефект кода | `standard` | | [EmptyCodeBlock](EmptyCodeBlock.md) | Пустой блок кода | Да | Важный | Дефект кода | `badpractice`
`suspicious` | diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 47b90c13659..c712c1ff135 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,10 +8,10 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **104** +Total: **105** * Error: **33** -* Code smell: **66** +* Code smell: **67** * Vulnerability: **2** * Security Hotspot: **3** @@ -44,6 +44,7 @@ Total: **104** | [DeprecatedFind](DeprecatedFind.md) | Using of the deprecated method "Find" | Yes | Minor | Code smell | `deprecated` | | [DeprecatedMessage](DeprecatedMessage.md) | Restriction on the use of deprecated "Message" method | Yes | Minor | Code smell | `standard`
`deprecated` | | [DeprecatedMethods8310](DeprecatedMethods8310.md) | Deprecated client application method. | Yes | Info | Code smell | `deprecated` | +| [DeprecatedMethods8317](DeprecatedMethods8317.md) | Using of deprecated platform 8.3.17 global methods | Yes | Info | Code smell | `deprecated` | | [DeprecatedTypeManagedForm](DeprecatedTypeManagedForm.md) | Deprecated ManagedForm type | Yes | Info | Code smell | `standard`
`deprecated` | | [DuplicateRegion](DuplicateRegion.md) | Duplicate regions | Yes | Info | Code smell | `standard` | | [EmptyCodeBlock](EmptyCodeBlock.md) | Empty code block | Yes | Major | Code smell | `badpractice`
`suspicious` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractFindMethodDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractFindMethodDiagnostic.java index 99f803a1874..9ddd8530fb9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractFindMethodDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractFindMethodDiagnostic.java @@ -23,6 +23,7 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import lombok.Getter; import lombok.Setter; import org.antlr.v4.runtime.tree.ParseTree; @@ -48,11 +49,15 @@ protected boolean checkMethodCall(BSLParser.MethodCallContext ctx) { return getMethodPattern().matcher(ctx.methodName().getText()).matches(); } + protected String getMessage(BSLParserRuleContext ctx) { + return info.getMessage(ctx.getText()); + } + @Override public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { if (checkGlobalMethodCall(ctx)) { - diagnosticStorage.addDiagnostic(ctx.methodName()); + diagnosticStorage.addDiagnostic(ctx.methodName(), getMessage(ctx)); } return super.visitGlobalMethodCall(ctx); @@ -62,7 +67,7 @@ public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { public ParseTree visitMethodCall(BSLParser.MethodCallContext ctx) { if (checkMethodCall(ctx)) { - diagnosticStorage.addDiagnostic(ctx.methodName()); + diagnosticStorage.addDiagnostic(ctx.methodName(), getMessage(ctx)); } return super.visitMethodCall(ctx); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java index f1657a62c2f..098a93f28c7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java @@ -29,7 +29,7 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.parser.BSLParser; -import org.antlr.v4.runtime.tree.ParseTree; +import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import java.util.regex.Pattern; @@ -44,7 +44,7 @@ } ) -public class DeprecatedMethods8317Diagnostic extends AbstractVisitorDiagnostic { +public class DeprecatedMethods8317Diagnostic extends AbstractFindMethodDiagnostic { private static final Pattern DEPRECATED_METHODS_NAMES = Pattern.compile( "(КраткоеПредставлениеОшибки|BriefErrorDescription|" + @@ -54,16 +54,20 @@ public class DeprecatedMethods8317Diagnostic extends AbstractVisitorDiagnostic { ); public DeprecatedMethods8317Diagnostic(DiagnosticInfo info) { - super(info); + super(info, DEPRECATED_METHODS_NAMES); } @Override - public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { - if (DEPRECATED_METHODS_NAMES.matcher(ctx.methodName().getText()).matches()) { - diagnosticStorage.addDiagnostic(ctx.methodName(), info.getMessage(ctx.methodName().getText())); + protected boolean checkMethodCall(BSLParser.MethodCallContext ctx) { + return false; + } + + @Override + protected String getMessage(BSLParserRuleContext ctx) { + if (ctx instanceof BSLParser.GlobalMethodCallContext) { + return info.getMessage(((BSLParser.GlobalMethodCallContext) ctx).methodName().getText()); } - return super.visitGlobalMethodCall(ctx); + return ""; } - } From 6e47b3f2f0c43a1395520b0c3b61b75f088cc421 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Sat, 2 May 2020 00:21:35 +0300 Subject: [PATCH 228/444] javadoc --- .github/workflows/gh-pages.yml | 12 ++++++++++++ docs/contributing/index.md | 1 + .../configuration/diagnostics/Mode.java | 2 +- 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index 84fb4cebea5..7676da61c6f 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -17,6 +17,14 @@ jobs: steps: - uses: actions/checkout@v1 + - name: Setup JDK 11 + uses: actions/setup-java@v1 + with: + java-version: 11 + + - name: Build javadoc + run: ./gradlew javadoc + - name: Set up Python uses: actions/setup-python@v1 with: @@ -82,6 +90,10 @@ jobs: run: | cp -R tmp-bench/. temp/site/bench rm -rf tmp-bench + + - name: Copy javadoc + run: | + cp -R build/docs/javadoc temp/site/javadoc - name: Public Russian Master if: github.ref == 'refs/heads/master' diff --git a/docs/contributing/index.md b/docs/contributing/index.md index 8abaa5b9f32..61cc0dd890a 100644 --- a/docs/contributing/index.md +++ b/docs/contributing/index.md @@ -8,6 +8,7 @@ - [Настройка окружения](EnvironmentSetting.md) - [Быстрый старт](FastStart.md) - [Руководство по стилю](StyleGuide.md) + - [JavaDoc](../javadoc/index.html) - Разработка диагностик - [Процесс (workflow) разработки диагностики](DiagnosticDevWorkFlow.md) - [Пример разработки диагностики](DiagnosticExample.md) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java index 7e2ab869aea..0dd8e5bfefb 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java @@ -25,7 +25,7 @@ /** * Режим для учета настроек правил. - *

+ *

* См. {@link DiagnosticsOptions#getParameters()} */ public enum Mode { From 0b031d46219e4e2802ee592c89ed1ce8b23fcd59 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Sat, 2 May 2020 00:40:07 +0300 Subject: [PATCH 229/444] javadoc 14 --- .github/workflows/gh-pages.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index 7676da61c6f..2cc67f3d97b 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -17,10 +17,10 @@ jobs: steps: - uses: actions/checkout@v1 - - name: Setup JDK 11 + - name: Setup JDK uses: actions/setup-java@v1 with: - java-version: 11 + java-version: 14 - name: Build javadoc run: ./gradlew javadoc From d167b92abefeb92e464cff72d5ba245392c5d59a Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Sat, 2 May 2020 00:43:03 +0300 Subject: [PATCH 230/444] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=81=D0=B0=D0=B9=D1=82=D0=B0=20?= =?UTF-8?q?=D0=BF=D1=80=D0=B8=20=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=B8=20=D1=84=D0=B0=D0=B9=D0=BB=D0=B0=20=D1=81=D0=B1?= =?UTF-8?q?=D0=BE=D1=80=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/gh-pages.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index 2cc67f3d97b..952b3f686ea 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -10,6 +10,7 @@ on: - 'src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/**' - 'mkdocs.yml' - 'mkdocs.en.yml' + - '.github/workflows/gh-pages.yml' jobs: build-deploy: From ecf358e7bcd3b60683ec1bd2edb3c7196f07940b Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Sat, 2 May 2020 00:45:26 +0300 Subject: [PATCH 231/444] =?UTF-8?q?=D0=98=D0=B3=D0=BD=D0=BE=D1=80=20=D0=BF?= =?UTF-8?q?=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0=D1=82=D0=B5=D0=BB?= =?UTF-8?q?=D1=8C=D1=81=D0=BA=D0=BE=D0=B3=D0=BE=20=D1=84=D0=B0=D0=B9=D0=BB?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 ++- .idea/checkstyle-idea.xml | 16 ---------------- 2 files changed, 2 insertions(+), 17 deletions(-) delete mode 100644 .idea/checkstyle-idea.xml diff --git a/.gitignore b/.gitignore index 1d542df92b1..2124d55423f 100644 --- a/.gitignore +++ b/.gitignore @@ -61,9 +61,10 @@ gen/ .idea/sonarlint-state.xml .idea/sonarlint.xml +.idea/checkstyle-idea.xml *.bak *.orig # mkdocs temp/ -public/ \ No newline at end of file +public/ diff --git a/.idea/checkstyle-idea.xml b/.idea/checkstyle-idea.xml deleted file mode 100644 index 32af77d10a7..00000000000 --- a/.idea/checkstyle-idea.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - \ No newline at end of file From 9e0fc7e36a0e1d00393e1bb415dca243725d8fa6 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Sat, 2 May 2020 00:45:26 +0300 Subject: [PATCH 232/444] =?UTF-8?q?=D0=9F=D1=83=D1=81=D1=82=D0=BE=D0=B9=20?= =?UTF-8?q?=D1=84=D0=B0=D0=B9=D0=BB=20=D0=B2=20javadoc-=D0=BA=D0=B0=D1=82?= =?UTF-8?q?=D0=B0=D0=BB=D0=BE=D0=B3=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/javadoc/.empty | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 docs/javadoc/.empty diff --git a/docs/javadoc/.empty b/docs/javadoc/.empty new file mode 100644 index 00000000000..e69de29bb2d From cc9a538ea0017ccaf3c2d7e9b2f6e2af1337bf8e Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Sat, 2 May 2020 01:11:42 +0300 Subject: [PATCH 233/444] .nojekyll https://github.blog/2009-12-29-bypassing-jekyll-on-github-pages/ --- docs/.nojekyll | 1 + 1 file changed, 1 insertion(+) create mode 100644 docs/.nojekyll diff --git a/docs/.nojekyll b/docs/.nojekyll new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/docs/.nojekyll @@ -0,0 +1 @@ + From 030f3ad6e1e550c3cfdbb9b653c3109aed6902ee Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Sat, 2 May 2020 01:14:52 +0300 Subject: [PATCH 234/444] =?UTF-8?q?=D0=A3=D1=81=D0=BA=D0=BE=D1=80=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D1=81=D0=B1=D0=BE=D1=80=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/gh-pages.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index 952b3f686ea..0d61532924d 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -24,7 +24,7 @@ jobs: java-version: 14 - name: Build javadoc - run: ./gradlew javadoc + run: ./gradlew --no-daemon javadoc - name: Set up Python uses: actions/setup-python@v1 From bdcad7ae9f368f583016f9c4836d817c730169b7 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Sat, 2 May 2020 01:35:01 +0300 Subject: [PATCH 235/444] Create .nojekyll --- .nojekyll | 1 + 1 file changed, 1 insertion(+) create mode 100644 .nojekyll diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/.nojekyll @@ -0,0 +1 @@ + From 0d82c612b40bc66474d59bba0eaa1cd009abe926 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Sat, 2 May 2020 01:35:19 +0300 Subject: [PATCH 236/444] Delete .nojekyll --- docs/.nojekyll | 1 - 1 file changed, 1 deletion(-) delete mode 100644 docs/.nojekyll diff --git a/docs/.nojekyll b/docs/.nojekyll deleted file mode 100644 index 8b137891791..00000000000 --- a/docs/.nojekyll +++ /dev/null @@ -1 +0,0 @@ - From 47c12efdd3f24a948b32e958c469f31aca880b88 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Sat, 2 May 2020 13:49:24 +0300 Subject: [PATCH 237/444] =?UTF-8?q?=D0=9F=D0=9A=D0=9C=20=D0=BF=D0=BE=20fil?= =?UTF-8?q?e?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/contributing/FastStart.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/contributing/FastStart.md b/docs/contributing/FastStart.md index 04e325cd8b4..53998805847 100644 --- a/docs/contributing/FastStart.md +++ b/docs/contributing/FastStart.md @@ -28,5 +28,5 @@ - Установить настройку `Case transformation in the Preview window` в `Transform to uppercase when lexing` 6. Открыть файл `build.gradle.kts` из каталога проекта, согласиться с импортом зависимостей, дождаться их скачивания 7. Открыть файл `src/main/antlr/BSLParser.g4` -8. Установить курсор на любую строку с кодом _(не комментарий)_ и выбрать пункт контекстного меню `Test Rule file` +8. Установить курсор строку с правилом `file:` (первое правило в файле) и выбрать пункт контекстного меню `Test Rule file` 9. В открывшемся окне выбрать bsl-файл либо вставить текст из буфера обмена From c8c60feacba528cc556878322f1286e956889840 Mon Sep 17 00:00:00 2001 From: Oleg Tymko Date: Sat, 2 May 2020 18:20:25 +0700 Subject: [PATCH 238/444] Create _config.yml --- docs/_config.yml | 1 + 1 file changed, 1 insertion(+) create mode 100644 docs/_config.yml diff --git a/docs/_config.yml b/docs/_config.yml new file mode 100644 index 00000000000..3f74121b111 --- /dev/null +++ b/docs/_config.yml @@ -0,0 +1 @@ +include: ['/javadoc/com/github/_1c_syntax'] From a99c345d0eaaa17c4bdfd112fe00ffd80a5189ef Mon Sep 17 00:00:00 2001 From: Oleg Tymko Date: Sat, 2 May 2020 18:39:05 +0700 Subject: [PATCH 239/444] Create .nojekyll --- docs/.nojekyll | 1 + 1 file changed, 1 insertion(+) create mode 100644 docs/.nojekyll diff --git a/docs/.nojekyll b/docs/.nojekyll new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/docs/.nojekyll @@ -0,0 +1 @@ + From c780769b72f1e8f39828409547bc3732a21ef6a7 Mon Sep 17 00:00:00 2001 From: Oleg Tymko Date: Sat, 2 May 2020 19:53:21 +0700 Subject: [PATCH 240/444] =?UTF-8?q?=D0=A1=D0=BE=D0=B7=D0=B4=D0=B0=D0=B5?= =?UTF-8?q?=D0=BC=20nojekyll=20=D0=BF=D1=80=D0=B8=20deploy=20gh-pages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/gh-pages.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index 0d61532924d..cff66cc8e24 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -95,6 +95,7 @@ jobs: - name: Copy javadoc run: | cp -R build/docs/javadoc temp/site/javadoc + echo "" > temp/site/.nojekyll - name: Public Russian Master if: github.ref == 'refs/heads/master' From f7f965bdf393a21e63a31a7fd496dbf788f7e153 Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Sun, 3 May 2020 14:42:43 +0300 Subject: [PATCH 241/444] =?UTF-8?q?1.=20=D0=94=D0=BE=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=BA=D0=B0=20AbstractFindMethodDiagnostic=202.=20?= =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=20javadoc=20?= =?UTF-8?q?=D0=B4=D0=BB=D1=8F=20AbstractFindMethodDiagnostic?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractFindMethodDiagnostic.java | 53 ++++++++++++++++++- .../DeprecatedMethods8317Diagnostic.java | 9 ---- 2 files changed, 52 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractFindMethodDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractFindMethodDiagnostic.java index 9ddd8530fb9..05a534060f0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractFindMethodDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractFindMethodDiagnostic.java @@ -30,29 +30,74 @@ import java.util.regex.Pattern; +/** + * Абстрактная диагностика, предназначенная для поиска вызова обычных методов и методов глобального контекста + * с использованием регулярного выражения. + * {@code AbstractFindMethodDiagnostic} предоставляет для переопределения два метода проверки вызовов и один + * метод генерации сообщения пользователю. + * По умолчанию проверяется, что имя вызываемого метода соответствует переданному в конструкторе регулярному выражению. + * Важно: наследование данной диагностики без переопределения {@code getMessage} подразумевает, что первым + * параметром сообщения пользователю всегда будет имя найденного метода. + */ public abstract class AbstractFindMethodDiagnostic extends AbstractVisitorDiagnostic { @Getter @Setter private Pattern methodPattern; + /** + * Конструктор по умолчанию + * @param info служебная информация о диагностике + * @param pattern регулярное выражение для проверки + */ AbstractFindMethodDiagnostic(DiagnosticInfo info, Pattern pattern) { super(info); methodPattern = pattern; } + /** + * Проверка контекста глобального метода + * @param ctx контекст глобального метода + * @return {@code true} если имя метода соответствует регулярному выражению + */ protected boolean checkGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { return getMethodPattern().matcher(ctx.methodName().getText()).matches(); } + /** + * Проверка контекста обычного метода + * @param ctx контекст метода + * @return {@code true} если имя метода соответствует регулярному выражению + */ protected boolean checkMethodCall(BSLParser.MethodCallContext ctx) { return getMethodPattern().matcher(ctx.methodName().getText()).matches(); } + /** + * Получает сообщение диагностики для пользователя + * @param ctx контекст узла + * @return В случае если передан контекст метода, параметризованное сообщение, + * первым параметром которого всегда будет имя метода. + * В противном случае возвращается обычное сообщение без параметров. + */ protected String getMessage(BSLParserRuleContext ctx) { - return info.getMessage(ctx.getText()); + + if (ctx instanceof BSLParser.GlobalMethodCallContext) { + return info.getMessage(((BSLParser.GlobalMethodCallContext) ctx).methodName().getText()); + } else if (ctx instanceof BSLParser.MethodCallContext) { + return info.getMessage(((BSLParser.MethodCallContext) ctx).methodName().getText()); + } else { + return info.getMessage(); + } + } + /** + * Обработчик узла глобального метода. Добавляет информацию о сработавшей диагностике + * в случае если проверка метода возвращает {@code true} + * @param ctx контекст гломабльного метода + * @return результат посещения ноды по умолчанию. + */ @Override public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { @@ -63,6 +108,12 @@ public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { return super.visitGlobalMethodCall(ctx); } + /** + * Обработчик узла обычного метода. Добавляет информацию о сработавшей диагностике + * в случае если проверка метода возвращает {@code true} + * @param ctx контекст метода + * @return результат посещения ноды по умолчанию. + */ @Override public ParseTree visitMethodCall(BSLParser.MethodCallContext ctx) { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java index 098a93f28c7..c4fe85f37e5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java @@ -29,7 +29,6 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.parser.BSLParser; -import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import java.util.regex.Pattern; @@ -62,12 +61,4 @@ protected boolean checkMethodCall(BSLParser.MethodCallContext ctx) { return false; } - @Override - protected String getMessage(BSLParserRuleContext ctx) { - if (ctx instanceof BSLParser.GlobalMethodCallContext) { - return info.getMessage(((BSLParser.GlobalMethodCallContext) ctx).methodName().getText()); - } - - return ""; - } } From d2a76fe26b226e59b8cfbcb4b54cd9a47510e4fb Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Sun, 3 May 2020 14:55:50 +0300 Subject: [PATCH 242/444] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=87?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D0=B9=20=D1=81=D0=BE=D0=BD=D0=B0=D1=80=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UnsafeSafeModeMethodCallDiagnostic.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java index 77145d8d86e..1cac49560e0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java @@ -65,13 +65,15 @@ protected boolean checkMethodCall(BSLParser.MethodCallContext ctx) { @Override protected boolean checkGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { - if (!SAFE_MODE_METHOD_NAME.matcher(ctx.methodName().getText()).matches()) { - return false; - } + BSLParserRuleContext rootIfNode = null; + BSLParserRuleContext rootExpressionNode = null; + BSLParserRuleContext currentRootMember = null; - BSLParserRuleContext rootIfNode = Trees.getRootParent(ctx, BSLParser.RULE_ifStatement); - BSLParserRuleContext rootExpressionNode = Trees.getRootParent(ctx, BSLParser.RULE_expression); - BSLParserRuleContext currentRootMember = Trees.getRootParent(ctx, BSLParser.RULE_member); + if (SAFE_MODE_METHOD_NAME.matcher(ctx.methodName().getText()).matches()) { + rootIfNode = Trees.getRootParent(ctx, BSLParser.RULE_ifStatement); + rootExpressionNode = Trees.getRootParent(ctx, BSLParser.RULE_expression); + currentRootMember = Trees.getRootParent(ctx, BSLParser.RULE_member); + } if (rootIfNode == null || rootExpressionNode == null || currentRootMember == null) { return false; From 12f2b29648b2245cede168a9b12ab00dcad72884 Mon Sep 17 00:00:00 2001 From: Viktor Gukov Date: Sun, 3 May 2020 15:40:21 +0300 Subject: [PATCH 243/444] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/AbstractFindMethodDiagnostic.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractFindMethodDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractFindMethodDiagnostic.java index 05a534060f0..4e2d097f7f2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractFindMethodDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractFindMethodDiagnostic.java @@ -94,8 +94,9 @@ protected String getMessage(BSLParserRuleContext ctx) { /** * Обработчик узла глобального метода. Добавляет информацию о сработавшей диагностике - * в случае если проверка метода возвращает {@code true} - * @param ctx контекст гломабльного метода + * в случае если проверка метода {@link AbstractFindMethodDiagnostic#checkGlobalMethodCall(BSLParser.GlobalMethodCallContext)} + * возвращает {@code true} + * @param ctx контекст глобального метода * @return результат посещения ноды по умолчанию. */ @Override @@ -110,7 +111,8 @@ public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { /** * Обработчик узла обычного метода. Добавляет информацию о сработавшей диагностике - * в случае если проверка метода возвращает {@code true} + * в случае если проверка метода {@link AbstractFindMethodDiagnostic#checkMethodCall(BSLParser.MethodCallContext)} + * возвращает {@code true} * @param ctx контекст метода * @return результат посещения ноды по умолчанию. */ From 942cc1d4897b8aebcac22f59e40603bb9f049b77 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Sun, 3 May 2020 17:31:43 +0300 Subject: [PATCH 244/444] =?UTF-8?q?=D0=9E=D0=BF=D1=82=D0=B8=D0=BC=D0=B8?= =?UTF-8?q?=D0=B7=D0=B0=D1=86=D0=B8=D1=8F=20getDescendants?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Единоразовое создание List для хранения результата дает ускорение примерно в 4 раза. --- .../_1c_syntax/bsl/languageserver/utils/Trees.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java index 2ce462cf19e..72ac052e999 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java @@ -74,7 +74,18 @@ public static Collection findAllTokenNodes(ParseTree t, int ttype) { } public static List getDescendants(ParseTree t) { - return org.antlr.v4.runtime.tree.Trees.getDescendants(t); + List nodes = new ArrayList<>(t.getChildCount()); + flatten(t, nodes); + return nodes; + } + + private static void flatten(ParseTree t, List flatList) { + flatList.add(t); + + int n = t.getChildCount(); + for (int i = 0; i < n; i++) { + flatten(t.getChild(i), flatList); + } } /** From 2179f6858415b6a2bae860534e08721b12f22934 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Mon, 4 May 2020 20:45:28 +0300 Subject: [PATCH 245/444] =?UTF-8?q?=D0=98=D0=BD=D1=84=D0=BE=D1=80=D0=BC?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D1=8F=20=D0=BE=20=D1=82=D0=BE=D0=BC,=20?= =?UTF-8?q?=D1=87=D1=82=D0=BE=20=D1=81=D0=B8=D0=BC=D0=B2=D0=BE=D0=BB=20?= =?UTF-8?q?=D1=8F=D0=B2=D0=BB=D1=8F=D0=B5=D1=82=D1=81=D1=8F=20deprecated?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../computer/MethodSymbolComputer.java | 8 ++++++- .../context/symbol/MethodDescription.java | 18 +++++++++++++++ .../context/symbol/MethodSymbol.java | 2 ++ .../providers/DocumentSymbolProvider.java | 10 +++++++++ .../computer/MethodSymbolComputerTest.java | 22 ++++++++++++++++++- .../providers/DocumentSymbolProviderTest.java | 8 ++++--- .../computer/MethodSymbolComputerTest.bsl | 11 ++++++++++ .../resources/providers/documentSymbol.bsl | 4 ++++ 8 files changed, 78 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java index 9561f672a90..559aba92f1f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java @@ -125,13 +125,19 @@ private MethodSymbol createMethodSymbol( boolean function, boolean export ) { + Optional description = createDescription(startNode.getSymbol()); + boolean deprecated = description + .map(MethodDescription::isDeprecated) + .orElse(false); + return MethodSymbol.builder() .name(subName.getText()) .range(Ranges.create(startNode, stopNode)) .subNameRange(Ranges.create(subName)) .function(function) .export(export) - .description(createDescription(startNode.getSymbol())) + .description(description) + .deprecated(deprecated) .parameters(createParameters(paramList)) .build(); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodDescription.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodDescription.java index 9b4e117020a..762c3805c70 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodDescription.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodDescription.java @@ -21,25 +21,39 @@ */ package com.github._1c_syntax.bsl.languageserver.context.symbol; +import com.github._1c_syntax.utils.CaseInsensitivePattern; import lombok.Getter; import org.antlr.v4.runtime.Token; import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import java.util.stream.Collectors; public class MethodDescription { private static final int COMMENT_LENGTH = 2; + private static final Pattern DEPRECATED = CaseInsensitivePattern.compile("(?:\\s*)((?:Устарела|Deprecated)\\..*)"); + private final int startLine; private final int endLine; @Getter private final String description; + @Getter + private final String deprecatedInfo; + public MethodDescription(List comments) { description = comments.stream() .map(Token::getText) .map(MethodDescription::uncomment) .collect(Collectors.joining("\n")); + Matcher matcher = DEPRECATED.matcher(description); + if (matcher.find()) { + deprecatedInfo = matcher.group(1); + } else { + deprecatedInfo = ""; + } if (comments.isEmpty()) { startLine = 0; @@ -55,6 +69,10 @@ public boolean isEmpty() { return description.isEmpty(); } + public boolean isDeprecated() { + return !deprecatedInfo.isEmpty(); + } + public boolean contains(Token first, Token last) { int firstLine = first.getLine(); int lastLine = last.getLine(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java index 337583fadaa..46b94f8d48e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java @@ -57,6 +57,8 @@ public class MethodSymbol implements Symbol { boolean export; Optional description; + boolean deprecated; + @Builder.Default List parameters = new ArrayList<>(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProvider.java index f2da3cd6d07..3c2afcd8747 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProvider.java @@ -67,6 +67,7 @@ private static DocumentSymbol toDocumentSymbol(Symbol symbol) { .map(DocumentSymbolProvider::toDocumentSymbol) .collect(Collectors.toList()); + documentSymbol.setDeprecated(getDeprecated(symbol)); documentSymbol.setChildren(children); return documentSymbol; @@ -86,4 +87,13 @@ private static Range getSelectionRange(Symbol symbol) { return selectionRange; } + private static boolean getDeprecated(Symbol symbol) { + boolean deprecated; + if (symbol instanceof MethodSymbol) { + deprecated = ((MethodSymbol) symbol).isDeprecated(); + } else { + deprecated = false; + } + return deprecated; + } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java index 1c4a6d36fa4..c8cf325fdb4 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java @@ -40,7 +40,7 @@ void testMethodSymbolComputer() { DocumentContext documentContext = TestUtils.getDocumentContextFromFile("./src/test/resources/context/computer/MethodSymbolComputerTest.bsl"); List methods = documentContext.getSymbolTree().getMethods(); - assertThat(methods.size()).isEqualTo(3); + assertThat(methods.size()).isEqualTo(5); assertThat(methods.get(0).getName()).isEqualTo("Один"); assertThat(methods.get(0).getDescription().orElse(null)).isNull(); @@ -79,6 +79,26 @@ void testParameters() { } + @Test + void testDeprecated() { + DocumentContext documentContext = TestUtils.getDocumentContextFromFile("./src/test/resources/context/computer/MethodSymbolComputerTest.bsl"); + List methods = documentContext.getSymbolTree().getMethods(); + + MethodSymbol methodSymbol = methods.get(2); + + assertThat(methodSymbol.isDeprecated()).isFalse(); + + methodSymbol = methods.get(3); + + assertThat(methodSymbol.isDeprecated()).isTrue(); + assertThat(methodSymbol.getDescription().orElseThrow().getDeprecatedInfo()).isNotEmpty(); + + methodSymbol = methods.get(4); + + assertThat(methodSymbol.isDeprecated()).isTrue(); + assertThat(methodSymbol.getDescription().orElseThrow().getDeprecatedInfo()).isNotEmpty(); + } + @Test void testParseError() { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProviderTest.java index ab0b9876b91..1ae37babd16 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProviderTest.java @@ -43,7 +43,7 @@ void testDocumentSymbol() { List> documentSymbols = DocumentSymbolProvider.getDocumentSymbols(documentContext); - assertThat(documentSymbols).hasSize(8); + assertThat(documentSymbols).hasSize(9); // global variables assertThat(documentSymbols) @@ -58,12 +58,14 @@ void testDocumentSymbol() { // methods assertThat(documentSymbols) .filteredOn(documentSymbol -> documentSymbol.getRight().getKind().equals(SymbolKind.Method)) - .hasSize(3) + .hasSize(4) .extracting(Either::getRight) .anyMatch(documentSymbol -> documentSymbol.getRange().equals(Ranges.create(4, 0, 5, 14))) .anyMatch(documentSymbol -> documentSymbol.getRange().equals(Ranges.create(7, 0, 8, 12))) .anyMatch(documentSymbol -> documentSymbol.getRange().equals(Ranges.create(10, 0, 13, 14))) - .anyMatch(documentSymbol -> documentSymbol.getRange().equals(Ranges.create(10, 0, 13, 14))) + .anyMatch(documentSymbol -> documentSymbol.getRange().equals(Ranges.create(47, 0, 48, 12))) + .filteredOn(DocumentSymbol::getDeprecated) + .anyMatch(documentSymbol -> documentSymbol.getRange().equals(Ranges.create(47, 0, 48, 12))) ; // sub vars diff --git a/src/test/resources/context/computer/MethodSymbolComputerTest.bsl b/src/test/resources/context/computer/MethodSymbolComputerTest.bsl index 373be805b44..0bfb724211e 100644 --- a/src/test/resources/context/computer/MethodSymbolComputerTest.bsl +++ b/src/test/resources/context/computer/MethodSymbolComputerTest.bsl @@ -17,3 +17,14 @@ КонецФункции #КонецОбласти + +// Устарела. +// +Функция Четыре() +КонецФункции + +// Описание +// Устарела. См. функцию Три() +// +Функция Пять() +КонецФункции diff --git a/src/test/resources/providers/documentSymbol.bsl b/src/test/resources/providers/documentSymbol.bsl index f37467ddd3d..594cd6bbdcc 100644 --- a/src/test/resources/providers/documentSymbol.bsl +++ b/src/test/resources/providers/documentSymbol.bsl @@ -44,4 +44,8 @@ #КонецОбласти +// Устарела. +Функция УстаревшаяФункция() +КонецФункции + А = 0; From fe382eda6b2d1587be55e2133adc5c32b26366bc Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Mon, 4 May 2020 21:19:29 +0300 Subject: [PATCH 246/444] =?UTF-8?q?=D0=98=D0=B7=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BE=D1=82=20ParseTree=20=D0=B2=20?= =?UTF-8?q?Symbol?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../context/DocumentContext.java | 4 --- .../computer/RegionSymbolComputer.java | 29 +++---------------- .../context/symbol/RegionSymbol.java | 15 ++-------- .../languageserver/context/symbol/Symbol.java | 3 -- .../diagnostics/EmptyRegionDiagnostic.java | 26 ++++++++++++++++- 5 files changed, 31 insertions(+), 46 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java index c6806778b40..f0491ddfa1e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java @@ -28,7 +28,6 @@ import com.github._1c_syntax.bsl.languageserver.context.computer.DiagnosticIgnoranceComputer; import com.github._1c_syntax.bsl.languageserver.context.computer.SymbolTreeComputer; import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; -import com.github._1c_syntax.bsl.languageserver.context.symbol.Symbol; import com.github._1c_syntax.bsl.languageserver.context.symbol.SymbolTree; import com.github._1c_syntax.bsl.languageserver.utils.Trees; import com.github._1c_syntax.bsl.parser.BSLLexer; @@ -207,9 +206,6 @@ public void clearSecondaryData() { contentList.clear(); tokenizer = null; - if (symbolTree.isPresent()) { - getSymbolTree().getChildrenFlat().forEach(Symbol::clearParseTreeData); - } cognitiveComplexityData.clear(); cyclomaticComplexityData.clear(); metrics.clear(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/RegionSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/RegionSymbolComputer.java index b0179f21738..b4a15c7f6cc 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/RegionSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/RegionSymbolComputer.java @@ -24,10 +24,8 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.context.symbol.RegionSymbol; 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.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserBaseVisitor; -import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; import org.apache.commons.lang3.tuple.Pair; import org.eclipse.lsp4j.Range; @@ -36,7 +34,6 @@ import java.util.ArrayList; import java.util.Deque; import java.util.List; -import java.util.stream.Collectors; public final class RegionSymbolComputer extends BSLParserBaseVisitor @@ -45,7 +42,6 @@ public final class RegionSymbolComputer private final DocumentContext documentContext; private final Deque> regionStack = new ArrayDeque<>(); private final List regions = new ArrayList<>(); - private final List allNodes = new ArrayList<>(); public RegionSymbolComputer(DocumentContext documentContext) { this.documentContext = documentContext; @@ -55,21 +51,15 @@ public RegionSymbolComputer(DocumentContext documentContext) { public List compute() { regionStack.clear(); regions.clear(); - allNodes.clear(); - - Trees.getDescendants(documentContext.getAst()).stream() - .filter(node -> node instanceof BSLParserRuleContext) - .map(node -> (BSLParserRuleContext) node) - .filter(node -> (node.getStop() != null) - && (node.getStart() != null)) - .collect(Collectors.toCollection(() -> allNodes)); visitFile(documentContext.getAst()); regionStack.clear(); - allNodes.clear(); - return new ArrayList<>(regions); + List result = new ArrayList<>(regions); + regions.clear(); + + return result; } @Override @@ -102,17 +92,6 @@ public ParseTree visitRegionEnd(BSLParser.RegionEndContext ctx) { .endRange(Ranges.create(ctx)) ; - // zero-based ranges - int regionStartLine = range.getStart().getLine() + 1; - int regionEndLine = range.getEnd().getLine() + 1; - List regionNodes = allNodes.stream() - .filter(node -> - node.getStart().getLine() > regionStartLine - && node.getStart().getLine() < regionEndLine) - .collect(Collectors.toList()); - - builder.nodes(regionNodes); - RegionSymbol region = builder.build(); regions.add(region); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/RegionSymbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/RegionSymbol.java index 0b0ac4847ac..2367b5878b3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/RegionSymbol.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/RegionSymbol.java @@ -21,7 +21,6 @@ */ package com.github._1c_syntax.bsl.languageserver.context.symbol; -import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import lombok.AccessLevel; import lombok.Builder; import lombok.EqualsAndHashCode; @@ -39,8 +38,8 @@ @Value @Builder(access = AccessLevel.PUBLIC) -@EqualsAndHashCode(exclude = {"children", "parent", "nodes"}) -@ToString(exclude = {"children", "parent", "nodes"}) +@EqualsAndHashCode(exclude = {"children", "parent"}) +@ToString(exclude = {"children", "parent"}) public class RegionSymbol implements Symbol { String name; Range range; @@ -57,16 +56,6 @@ public class RegionSymbol implements Symbol { @Builder.Default List children = new ArrayList<>(); - @NonFinal - @Builder.Default - // TODO подумать, как избавиться от этого - List nodes = new ArrayList<>(); - - @Override - public void clearParseTreeData() { - nodes = null; - } - public List getMethods() { return children.stream() .filter(MethodSymbol.class::isInstance) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Symbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Symbol.java index 87638ac472e..0f14318b764 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Symbol.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Symbol.java @@ -41,9 +41,6 @@ public interface Symbol { List getChildren(); - default void clearParseTreeData() { - } - default Optional getRootParent() { return getParent().flatMap(Symbol::getRootParent).or(() -> Optional.of(this)); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java index a8d3c5e5624..310f46641c4 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java @@ -29,7 +29,9 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.providers.CodeActionProvider; +import com.github._1c_syntax.bsl.languageserver.utils.Trees; import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import org.antlr.v4.runtime.RuleContext; import org.eclipse.lsp4j.CodeAction; import org.eclipse.lsp4j.CodeActionParams; @@ -43,6 +45,7 @@ import java.util.List; import java.util.Optional; import java.util.Set; +import java.util.stream.Collectors; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, @@ -61,17 +64,38 @@ public class EmptyRegionDiagnostic extends AbstractDiagnostic implements QuickFi BSLParser.RULE_preprocessor ); + private final List allNodes = new ArrayList<>(); + public EmptyRegionDiagnostic(DiagnosticInfo info) { super(info); } @Override protected void check(DocumentContext documentContext) { + + allNodes.clear(); + + Trees.getDescendants(documentContext.getAst()).stream() + .filter(node -> node instanceof BSLParserRuleContext) + .map(node -> (BSLParserRuleContext) node) + .filter(node -> (node.getStop() != null) + && (node.getStart() != null)) + .collect(Collectors.toCollection(() -> allNodes)); + documentContext.getSymbolTree().getRegionsFlat().forEach(this::checkRegion); + + allNodes.clear(); } private void checkRegion(RegionSymbol region) { - var hasChildren = region.getNodes().stream() + // zero-based ranges + int startLine = region.getStartRange().getStart().getLine() + 1; + int endLine = region.getEndRange().getEnd().getLine() + 1; + + var hasChildren = allNodes.stream() + .filter(node -> + node.getStart().getLine() > startLine + && node.getStart().getLine() < endLine) .map(RuleContext::getRuleIndex) .filter(ruleIndex -> !REGIONS_NODE_INDEXES.contains(ruleIndex)) .findAny(); From d1105173025d9e4ceebf632f73c8814ea95e7ad2 Mon Sep 17 00:00:00 2001 From: evgeniy Date: Tue, 5 May 2020 03:14:55 +0300 Subject: [PATCH 247/444] Cleanup diagnostic for EmptyRegion --- .../diagnostics/EmptyRegionDiagnostic.java | 110 ++++++++++-------- .../EmptyRegionDiagnosticTest.java | 5 +- 2 files changed, 63 insertions(+), 52 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java index 310f46641c4..d52597088b7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java @@ -29,10 +29,13 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.providers.CodeActionProvider; -import com.github._1c_syntax.bsl.languageserver.utils.Trees; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import com.github._1c_syntax.bsl.parser.BSLParser; -import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; -import org.antlr.v4.runtime.RuleContext; +import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.tree.ErrorNode; +import org.antlr.v4.runtime.tree.ParseTreeListener; +import org.antlr.v4.runtime.tree.ParseTreeWalker; +import org.antlr.v4.runtime.tree.TerminalNode; import org.eclipse.lsp4j.CodeAction; import org.eclipse.lsp4j.CodeActionParams; import org.eclipse.lsp4j.Diagnostic; @@ -40,12 +43,12 @@ import org.eclipse.lsp4j.Range; import org.eclipse.lsp4j.TextEdit; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Comparator; +import java.util.Deque; import java.util.List; import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, @@ -57,55 +60,14 @@ ) public class EmptyRegionDiagnostic extends AbstractDiagnostic implements QuickFixProvider { - private static final Set REGIONS_NODE_INDEXES = Set.of( - BSLParser.RULE_regionName, - BSLParser.RULE_regionStart, - BSLParser.RULE_regionEnd, - BSLParser.RULE_preprocessor - ); - - private final List allNodes = new ArrayList<>(); - public EmptyRegionDiagnostic(DiagnosticInfo info) { super(info); } @Override protected void check(DocumentContext documentContext) { - - allNodes.clear(); - - Trees.getDescendants(documentContext.getAst()).stream() - .filter(node -> node instanceof BSLParserRuleContext) - .map(node -> (BSLParserRuleContext) node) - .filter(node -> (node.getStop() != null) - && (node.getStart() != null)) - .collect(Collectors.toCollection(() -> allNodes)); - - documentContext.getSymbolTree().getRegionsFlat().forEach(this::checkRegion); - - allNodes.clear(); - } - - private void checkRegion(RegionSymbol region) { - // zero-based ranges - int startLine = region.getStartRange().getStart().getLine() + 1; - int endLine = region.getEndRange().getEnd().getLine() + 1; - - var hasChildren = allNodes.stream() - .filter(node -> - node.getStart().getLine() > startLine - && node.getStart().getLine() < endLine) - .map(RuleContext::getRuleIndex) - .filter(ruleIndex -> !REGIONS_NODE_INDEXES.contains(ruleIndex)) - .findAny(); - - if (hasChildren.isEmpty()) { - diagnosticStorage.addDiagnostic( - region.getStartRange(), - info.getMessage(region.getName()) - ); - } + ParseTreeWalker walker = new ParseTreeWalker(); + walker.walk(new RegionChecker(), documentContext.getAst()); } @Override @@ -150,8 +112,7 @@ public List getQuickFixes( Range range = new Range(diagnosticRangeStart, diagnosticRangeEnd); - TextEdit textEdit = new TextEdit(range, ""); - textEdits.add(textEdit); + textEdits.add(new TextEdit(range, "")); } @@ -162,5 +123,54 @@ public List getQuickFixes( diagnostics ); } + + private class RegionChecker implements ParseTreeListener { + int currentRegionLevel = 0; + int currentUsageLevel = 0; + Deque regions = new ArrayDeque<>(); + + @Override + public void visitTerminal(TerminalNode node) { + // nothing to do + } + + @Override + public void visitErrorNode(ErrorNode node) { + // nothing to do + } + + @Override + public void enterEveryRule(ParserRuleContext ctx) { + if (ctx instanceof BSLParser.RegionStartContext) { + currentRegionLevel++; + regions.push((BSLParser.RegionStartContext) ctx); + } else if (ctx instanceof BSLParser.PreprocessorContext + || ctx instanceof BSLParser.FileContext + || ctx instanceof BSLParser.RegionNameContext + || ctx instanceof BSLParser.RegionEndContext) { + //ignore + } else { + currentUsageLevel = Math.max(currentUsageLevel, currentRegionLevel); + } + } + + @Override + public void exitEveryRule(ParserRuleContext ctx) { + if (ctx instanceof BSLParser.RegionEndContext) { + if (!regions.isEmpty()) { + BSLParser.RegionStartContext currentRegion = regions.pop(); + if (currentUsageLevel < currentRegionLevel) { + diagnosticStorage.addDiagnostic( + Ranges.create(currentRegion), + info.getMessage(currentRegion.regionName().getText()) + ); + } else if (currentRegionLevel == currentUsageLevel) { + currentUsageLevel--; + } + currentRegionLevel--; + } + } + } + } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnosticTest.java index 5f3eb542f7e..9dea99d9aa7 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnosticTest.java @@ -51,7 +51,8 @@ void test() { @Test void testQuickFix() { - + // TODO Some bad code happens + /* final DocumentContext documentContext = getDocumentContext(); List diagnostics = getDiagnostics(); final Diagnostic externalRegionDiagnostic = diagnostics.get(1); @@ -76,6 +77,6 @@ void testQuickFix() { .in(documentContext) .hasChanges(1) .hasNewText(""); - +*/ } } From 2e2739c588350daf6db6a4d6c3b66ff805315dd5 Mon Sep 17 00:00:00 2001 From: evgeniy Date: Tue, 5 May 2020 03:26:38 +0300 Subject: [PATCH 248/444] Fix test by change order... --- .../diagnostics/EmptyRegionDiagnosticTest.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnosticTest.java index 9dea99d9aa7..a7f6d9ccfe8 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnosticTest.java @@ -51,12 +51,11 @@ void test() { @Test void testQuickFix() { - // TODO Some bad code happens - /* + final DocumentContext documentContext = getDocumentContext(); List diagnostics = getDiagnostics(); - final Diagnostic externalRegionDiagnostic = diagnostics.get(1); - final Diagnostic internalRegionDiagnostic = diagnostics.get(2); + final Diagnostic externalRegionDiagnostic = diagnostics.get(2); + final Diagnostic internalRegionDiagnostic = diagnostics.get(1); List quickFixes = getQuickFixes(externalRegionDiagnostic); assertThat(quickFixes).hasSize(1); @@ -77,6 +76,6 @@ void testQuickFix() { .in(documentContext) .hasChanges(1) .hasNewText(""); -*/ + } } From c381959f5a32c1d400856ae42cda80419ef2385f Mon Sep 17 00:00:00 2001 From: evgeniy Date: Tue, 5 May 2020 10:27:36 +0300 Subject: [PATCH 249/444] Remove inner listener in EmptyRegionDiagnostic --- .../diagnostics/EmptyRegionDiagnostic.java | 90 +++++++------------ 1 file changed, 34 insertions(+), 56 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java index d52597088b7..fc8b88a31b9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java @@ -32,10 +32,6 @@ import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import com.github._1c_syntax.bsl.parser.BSLParser; import org.antlr.v4.runtime.ParserRuleContext; -import org.antlr.v4.runtime.tree.ErrorNode; -import org.antlr.v4.runtime.tree.ParseTreeListener; -import org.antlr.v4.runtime.tree.ParseTreeWalker; -import org.antlr.v4.runtime.tree.TerminalNode; import org.eclipse.lsp4j.CodeAction; import org.eclipse.lsp4j.CodeActionParams; import org.eclipse.lsp4j.Diagnostic; @@ -58,16 +54,46 @@ DiagnosticTag.STANDARD } ) -public class EmptyRegionDiagnostic extends AbstractDiagnostic implements QuickFixProvider { +public class EmptyRegionDiagnostic extends AbstractListenerDiagnostic implements QuickFixProvider { + int currentRegionLevel = 0; + int currentUsageLevel = 0; + Deque regions = new ArrayDeque<>(); public EmptyRegionDiagnostic(DiagnosticInfo info) { super(info); } @Override - protected void check(DocumentContext documentContext) { - ParseTreeWalker walker = new ParseTreeWalker(); - walker.walk(new RegionChecker(), documentContext.getAst()); + public void enterEveryRule(ParserRuleContext ctx) { + if (ctx instanceof BSLParser.RegionStartContext) { + currentRegionLevel++; + regions.push((BSLParser.RegionStartContext) ctx); + } else if (ctx instanceof BSLParser.PreprocessorContext + || ctx instanceof BSLParser.FileContext + || ctx instanceof BSLParser.RegionNameContext + || ctx instanceof BSLParser.RegionEndContext) { + //ignore + } else { + currentUsageLevel = Math.max(currentUsageLevel, currentRegionLevel); + } + } + + @Override + public void exitEveryRule(ParserRuleContext ctx) { + if (ctx instanceof BSLParser.RegionEndContext) { + if (!regions.isEmpty()) { + BSLParser.RegionStartContext currentRegion = regions.pop(); + if (currentUsageLevel < currentRegionLevel) { + diagnosticStorage.addDiagnostic( + Ranges.create(currentRegion), + info.getMessage(currentRegion.regionName().getText()) + ); + } else if (currentRegionLevel == currentUsageLevel) { + currentUsageLevel--; + } + currentRegionLevel--; + } + } } @Override @@ -124,53 +150,5 @@ public List getQuickFixes( ); } - private class RegionChecker implements ParseTreeListener { - int currentRegionLevel = 0; - int currentUsageLevel = 0; - Deque regions = new ArrayDeque<>(); - - @Override - public void visitTerminal(TerminalNode node) { - // nothing to do - } - - @Override - public void visitErrorNode(ErrorNode node) { - // nothing to do - } - - @Override - public void enterEveryRule(ParserRuleContext ctx) { - if (ctx instanceof BSLParser.RegionStartContext) { - currentRegionLevel++; - regions.push((BSLParser.RegionStartContext) ctx); - } else if (ctx instanceof BSLParser.PreprocessorContext - || ctx instanceof BSLParser.FileContext - || ctx instanceof BSLParser.RegionNameContext - || ctx instanceof BSLParser.RegionEndContext) { - //ignore - } else { - currentUsageLevel = Math.max(currentUsageLevel, currentRegionLevel); - } - } - - @Override - public void exitEveryRule(ParserRuleContext ctx) { - if (ctx instanceof BSLParser.RegionEndContext) { - if (!regions.isEmpty()) { - BSLParser.RegionStartContext currentRegion = regions.pop(); - if (currentUsageLevel < currentRegionLevel) { - diagnosticStorage.addDiagnostic( - Ranges.create(currentRegion), - info.getMessage(currentRegion.regionName().getText()) - ); - } else if (currentRegionLevel == currentUsageLevel) { - currentUsageLevel--; - } - currentRegionLevel--; - } - } - } - } } From 2f90b46a4af443560caee91807bc57befb3aa53a Mon Sep 17 00:00:00 2001 From: evgeniy Date: Tue, 5 May 2020 12:34:32 +0300 Subject: [PATCH 250/444] Simplify quick fix for EmptyRegionDiagnostic. --- .../diagnostics/EmptyRegionDiagnostic.java | 57 +++---------------- .../EmptyRegionDiagnosticTest.java | 6 +- 2 files changed, 11 insertions(+), 52 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java index fc8b88a31b9..b3c6f258823 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java @@ -22,7 +22,6 @@ package com.github._1c_syntax.bsl.languageserver.diagnostics; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; -import com.github._1c_syntax.bsl.languageserver.context.symbol.RegionSymbol; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; @@ -35,16 +34,12 @@ import org.eclipse.lsp4j.CodeAction; import org.eclipse.lsp4j.CodeActionParams; import org.eclipse.lsp4j.Diagnostic; -import org.eclipse.lsp4j.Position; -import org.eclipse.lsp4j.Range; import org.eclipse.lsp4j.TextEdit; import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Comparator; import java.util.Deque; import java.util.List; -import java.util.Optional; +import java.util.stream.Collectors; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, @@ -69,12 +64,11 @@ public void enterEveryRule(ParserRuleContext ctx) { currentRegionLevel++; regions.push((BSLParser.RegionStartContext) ctx); } else if (ctx instanceof BSLParser.PreprocessorContext - || ctx instanceof BSLParser.FileContext || ctx instanceof BSLParser.RegionNameContext || ctx instanceof BSLParser.RegionEndContext) { //ignore - } else { - currentUsageLevel = Math.max(currentUsageLevel, currentRegionLevel); + } else if (currentUsageLevel < currentRegionLevel) { + currentUsageLevel = currentRegionLevel; } } @@ -85,7 +79,7 @@ public void exitEveryRule(ParserRuleContext ctx) { BSLParser.RegionStartContext currentRegion = regions.pop(); if (currentUsageLevel < currentRegionLevel) { diagnosticStorage.addDiagnostic( - Ranges.create(currentRegion), + Ranges.create(currentRegion.getParent(), ctx), info.getMessage(currentRegion.regionName().getText()) ); } else if (currentRegionLevel == currentUsageLevel) { @@ -102,45 +96,10 @@ public List getQuickFixes( CodeActionParams params, DocumentContext documentContext ) { - diagnostics.sort(Comparator.comparingInt(o -> o.getRange().getStart().getLine())); - List textEdits = new ArrayList<>(); - int maxDiagnosticEndLine = 0; - - for (Diagnostic diagnostic : diagnostics) { - - int diagnosticStartLine = diagnostic.getRange().getStart().getLine(); - - Optional optionalRegionSymbol = documentContext.getSymbolTree().getRegionsFlat() - .stream() - .filter(regionSymbol -> regionSymbol.getRange().getStart().getLine() == diagnosticStartLine) - .findFirst(); - if (optionalRegionSymbol.isEmpty()) { - continue; - } - RegionSymbol region = optionalRegionSymbol.get(); - - int diagnosticEndLine = region.getRange().getEnd().getLine() - 1; - if (diagnosticEndLine < maxDiagnosticEndLine) { - continue; - } - - if (maxDiagnosticEndLine == 0 || diagnosticEndLine > maxDiagnosticEndLine) { - maxDiagnosticEndLine = diagnosticEndLine; - } - - int diagnosticStartCharacter = diagnostic.getRange().getStart().getCharacter() - 1; - Position diagnosticRangeStart = new Position(diagnosticStartLine, diagnosticStartCharacter); - - Position diagnosticRangeEnd = new Position( - diagnosticEndLine + 1, - 0 - ); - - Range range = new Range(diagnosticRangeStart, diagnosticRangeEnd); - - textEdits.add(new TextEdit(range, "")); - - } + List textEdits = diagnostics + .stream() + .map(diagnostic -> new TextEdit(diagnostic.getRange(), "")) + .collect(Collectors.toList()); return CodeActionProvider.createCodeActions( textEdits, diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnosticTest.java index a7f6d9ccfe8..35f170075a2 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnosticTest.java @@ -42,9 +42,9 @@ void test() { assertThat(diagnostics).hasSize(3); assertThat(diagnostics, true) - .hasRange(0, 1, 13) - .hasRange(10, 1, 23) - .hasRange(12, 1, 26) + .hasRange(0, 0, 2, 13) + .hasRange(10, 0, 15, 13) + .hasRange(12, 0, 14, 13) ; } From 6400001a0e59e536c289710e211855de3175dea5 Mon Sep 17 00:00:00 2001 From: evgeniy Date: Wed, 6 May 2020 07:32:42 +0300 Subject: [PATCH 251/444] Fix "Quick fix all" operation. Remove warning with empty statements. --- .../diagnostics/EmptyRegionDiagnostic.java | 28 ++++++++++++------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java index b3c6f258823..162f8348fb2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java @@ -37,9 +37,10 @@ import org.eclipse.lsp4j.TextEdit; import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Comparator; import java.util.Deque; import java.util.List; -import java.util.stream.Collectors; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, @@ -63,11 +64,10 @@ public void enterEveryRule(ParserRuleContext ctx) { if (ctx instanceof BSLParser.RegionStartContext) { currentRegionLevel++; regions.push((BSLParser.RegionStartContext) ctx); - } else if (ctx instanceof BSLParser.PreprocessorContext + } else if (! (ctx instanceof BSLParser.PreprocessorContext || ctx instanceof BSLParser.RegionNameContext - || ctx instanceof BSLParser.RegionEndContext) { - //ignore - } else if (currentUsageLevel < currentRegionLevel) { + || ctx instanceof BSLParser.RegionEndContext) + && currentUsageLevel < currentRegionLevel) { currentUsageLevel = currentRegionLevel; } } @@ -96,10 +96,20 @@ public List getQuickFixes( CodeActionParams params, DocumentContext documentContext ) { - List textEdits = diagnostics + List textEdits = new ArrayList<>(diagnostics.size()); + diagnostics .stream() - .map(diagnostic -> new TextEdit(diagnostic.getRange(), "")) - .collect(Collectors.toList()); + .map(Diagnostic::getRange) + .sorted(Comparator.comparingInt(o -> o.getStart().getLine())) + .reduce((prev, curr) -> { + if (prev.getEnd().getLine() > curr.getStart().getLine()) { + return prev; + } else { + textEdits.add(new TextEdit(prev, "")); + return curr; + } + }) + .ifPresent(lastRange -> textEdits.add(new TextEdit(lastRange, ""))); return CodeActionProvider.createCodeActions( textEdits, @@ -108,6 +118,4 @@ public List getQuickFixes( diagnostics ); } - } - From 96b846cb706cf501e47b0acbbc4fc5fba65e601b Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Wed, 6 May 2020 13:36:09 +0300 Subject: [PATCH 252/444] Fix qf --- .../bsl/languageserver/providers/DocumentSymbolProvider.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProvider.java index 3c2afcd8747..3e926e097c1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProvider.java @@ -67,7 +67,7 @@ private static DocumentSymbol toDocumentSymbol(Symbol symbol) { .map(DocumentSymbolProvider::toDocumentSymbol) .collect(Collectors.toList()); - documentSymbol.setDeprecated(getDeprecated(symbol)); + documentSymbol.setDeprecated(isDeprecated(symbol)); documentSymbol.setChildren(children); return documentSymbol; @@ -87,7 +87,7 @@ private static Range getSelectionRange(Symbol symbol) { return selectionRange; } - private static boolean getDeprecated(Symbol symbol) { + private static boolean isDeprecated(Symbol symbol) { boolean deprecated; if (symbol instanceof MethodSymbol) { deprecated = ((MethodSymbol) symbol).isDeprecated(); From 778743d38d4d510cbb81dd91e6ca9130aba187dc Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Wed, 6 May 2020 14:58:17 +0300 Subject: [PATCH 253/444] Fix QF --- .../diagnostics/EmptyRegionDiagnostic.java | 28 +++++++++---------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java index fc8b88a31b9..9230eb8e968 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java @@ -55,9 +55,9 @@ } ) public class EmptyRegionDiagnostic extends AbstractListenerDiagnostic implements QuickFixProvider { - int currentRegionLevel = 0; - int currentUsageLevel = 0; - Deque regions = new ArrayDeque<>(); + private int currentRegionLevel; + private int currentUsageLevel; + private final Deque regions = new ArrayDeque<>(); public EmptyRegionDiagnostic(DiagnosticInfo info) { super(info); @@ -80,19 +80,17 @@ public void enterEveryRule(ParserRuleContext ctx) { @Override public void exitEveryRule(ParserRuleContext ctx) { - if (ctx instanceof BSLParser.RegionEndContext) { - if (!regions.isEmpty()) { - BSLParser.RegionStartContext currentRegion = regions.pop(); - if (currentUsageLevel < currentRegionLevel) { - diagnosticStorage.addDiagnostic( - Ranges.create(currentRegion), - info.getMessage(currentRegion.regionName().getText()) - ); - } else if (currentRegionLevel == currentUsageLevel) { - currentUsageLevel--; - } - currentRegionLevel--; + if (ctx instanceof BSLParser.RegionEndContext && !regions.isEmpty()) { + BSLParser.RegionStartContext currentRegion = regions.pop(); + if (currentUsageLevel < currentRegionLevel) { + diagnosticStorage.addDiagnostic( + Ranges.create(currentRegion), + info.getMessage(currentRegion.regionName().getText()) + ); + } else if (currentRegionLevel == currentUsageLevel) { + currentUsageLevel--; } + currentRegionLevel--; } } From 52125fd3ae311854328a9c7f1125a3e69bfca040 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Wed, 6 May 2020 17:31:02 +0300 Subject: [PATCH 254/444] =?UTF-8?q?=D0=9E=D0=BF=D1=82=D0=B8=D0=BC=D0=B8?= =?UTF-8?q?=D0=B7=D0=B0=D1=86=D0=B8=D1=8F=20=D0=BF=D0=BE=D0=B8=D1=81=D0=BA?= =?UTF-8?q?=D0=B0=20MethodSymbol=20=D0=B2=20SymbolTree?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../context/symbol/SymbolTree.java | 22 ++++++------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java index d58da5a8515..55fd568b667 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java @@ -29,7 +29,6 @@ import org.eclipse.lsp4j.Range; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @@ -39,10 +38,10 @@ public class SymbolTree { List children; public List getChildrenFlat() { - return children.stream() - .map(this::getSelfAndChildrenRecursive) - .flatMap(Collection::stream) - .collect(Collectors.toList()); + List symbols = new ArrayList<>(); + children.forEach(child -> flatten(child, symbols)); + + return symbols; } public List getChildrenFlat(Class clazz) { @@ -113,16 +112,9 @@ public Optional getVariableSymbol(BSLParserRuleContext ctx) { .findAny(); } - private List getSelfAndChildrenRecursive(Symbol symbol) { - var list = new ArrayList(); - list.add(symbol); - - symbol.getChildren().stream() - .map(this::getSelfAndChildrenRecursive) - .flatMap(Collection::stream) - .collect(Collectors.toCollection(() -> list)); - - return list; + private static void flatten(Symbol symbol, List symbols) { + symbols.add(symbol); + symbol.getChildren().forEach(child -> flatten(child, symbols)); } } From d864741b6cc186635e40d90c1416e279333ef338 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Wed, 6 May 2020 17:50:25 +0300 Subject: [PATCH 255/444] =?UTF-8?q?=D0=9E=D0=BF=D1=82=D0=B8=D0=BC=D0=B8?= =?UTF-8?q?=D0=B7=D0=B0=D1=86=D0=B8=D1=8F=20=D0=BF=D0=BE=D0=B8=D1=81=D0=BA?= =?UTF-8?q?=D0=B0=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../context/symbol/SymbolTree.java | 25 ++++++++++++------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java index 55fd568b667..2a609f1431a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java @@ -25,6 +25,7 @@ import com.github._1c_syntax.bsl.languageserver.utils.Trees; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; +import lombok.Getter; import lombok.Value; import org.eclipse.lsp4j.Range; @@ -37,12 +38,11 @@ public class SymbolTree { List children; - public List getChildrenFlat() { - List symbols = new ArrayList<>(); - children.forEach(child -> flatten(child, symbols)); + @Getter(lazy = true) + List childrenFlat = createChildrenFlat(); - return symbols; - } + @Getter(lazy = true) + List methods = createMethods(); public List getChildrenFlat(Class clazz) { return getChildrenFlat().stream() @@ -62,10 +62,6 @@ public List getRegionsFlat() { return getChildrenFlat(RegionSymbol.class); } - public List getMethods() { - return getChildrenFlat(MethodSymbol.class); - } - public Optional getMethodSymbol(BSLParserRuleContext ctx) { BSLParserRuleContext subNameNode; if (Trees.nodeContainsErrors(ctx)) { @@ -112,6 +108,17 @@ public Optional getVariableSymbol(BSLParserRuleContext ctx) { .findAny(); } + private List createChildrenFlat() { + List symbols = new ArrayList<>(); + getChildren().forEach(child -> flatten(child, symbols)); + + return symbols; + } + + private List createMethods() { + return getChildrenFlat(MethodSymbol.class); + } + private static void flatten(Symbol symbol, List symbols) { symbols.add(symbol); symbol.getChildren().forEach(child -> flatten(child, symbols)); From d3d4c44fe5157f854a3d3656e1abe3f39d2d33bc Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Wed, 6 May 2020 17:58:28 +0300 Subject: [PATCH 256/444] =?UTF-8?q?=D0=A1=D1=82=D0=B0=D1=80=D0=B0=D1=8F=20?= =?UTF-8?q?=D1=80=D0=B5=D0=B0=D0=BB=D0=B8=D0=B7=D0=B0=D1=86=D0=B8=D1=8F=20?= =?UTF-8?q?case=20insensetivity=20=D0=B2=20=D0=BF=D0=B0=D1=80=D1=81=D0=B5?= =?UTF-8?q?=D1=80=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle.kts b/build.gradle.kts index d5df81751b2..d9860190cf2 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -77,7 +77,7 @@ dependencies { implementation("org.reflections", "reflections", "0.9.10") - implementation("com.github.1c-syntax", "bsl-parser", "01cc1512e10b667a0ec3fdd2307ca0221bf52684") { + implementation("com.github.1c-syntax", "bsl-parser", "57e4b9574b") { exclude("com.tunnelvisionlabs", "antlr4-annotations") exclude("com.ibm.icu", "*") exclude("org.antlr", "ST4") From 6e1a862653752d2036aaadbb850968201a3de492 Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Wed, 6 May 2020 19:22:12 +0300 Subject: [PATCH 257/444] =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BE=D0=B1=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=BA=D1=83?= =?UTF-8?q?=20=D0=BF=D1=80=D0=BE=D0=BF=D1=83=D1=89=D0=B5=D0=BD=D0=BD=D1=8B?= =?UTF-8?q?=D1=85=20=D1=82=D0=B5=D1=81=D1=82-=D0=BA=D0=B5=D0=B9=D1=81?= =?UTF-8?q?=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit воспользовался штатным методов сравнения с регуляркой ускорил работу правила --- .../UnsafeSafeModeMethodCallDiagnostic.java | 27 +++++++++++++------ .../bsl/languageserver/utils/Trees.java | 27 +++++++++++++++---- ...nsafeSafeModeMethodCallDiagnosticTest.java | 5 ++-- 3 files changed, 44 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java index 1cac49560e0..ac25c27a844 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java @@ -32,6 +32,8 @@ import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; +import java.util.Arrays; +import java.util.List; import java.util.regex.Pattern; @DiagnosticMetadata( @@ -52,6 +54,10 @@ public class UnsafeSafeModeMethodCallDiagnostic extends AbstractFindMethodDiagno "(БезопасныйРежим|SafeMode)", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE ); + private static final List ROOT_LIST = Arrays.asList( + BSLParser.RULE_ifBranch, BSLParser.RULE_elsifBranch, BSLParser.RULE_codeBlock); + private static final List IF_BRANCHES = Arrays.asList( + BSLParser.RULE_ifBranch, BSLParser.RULE_elsifBranch); public UnsafeSafeModeMethodCallDiagnostic(DiagnosticInfo info) { super(info, SAFE_MODE_METHOD_NAME); @@ -65,22 +71,27 @@ protected boolean checkMethodCall(BSLParser.MethodCallContext ctx) { @Override protected boolean checkGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { - BSLParserRuleContext rootIfNode = null; - BSLParserRuleContext rootExpressionNode = null; - BSLParserRuleContext currentRootMember = null; + if (!super.checkGlobalMethodCall(ctx)){ + return false; + } - if (SAFE_MODE_METHOD_NAME.matcher(ctx.methodName().getText()).matches()) { - rootIfNode = Trees.getRootParent(ctx, BSLParser.RULE_ifStatement); - rootExpressionNode = Trees.getRootParent(ctx, BSLParser.RULE_expression); - currentRootMember = Trees.getRootParent(ctx, BSLParser.RULE_member); + BSLParserRuleContext currentRootMember = Trees.getRootParent(ctx, BSLParser.RULE_member); + if (currentRootMember == null) { + return false; + } + BSLParserRuleContext rootExpressionNode = Trees.getRootParent(currentRootMember, BSLParser.RULE_expression); + if (rootExpressionNode == null) { + return false; } - if (rootIfNode == null || rootExpressionNode == null || currentRootMember == null) { + BSLParserRuleContext rootIfNode = Trees.getRootParent(rootExpressionNode, ROOT_LIST); + if (rootIfNode == null || !IF_BRANCHES.contains(rootIfNode.getRuleIndex())) { return false; } int indexOfCurrentMemberNode = rootExpressionNode.children.indexOf(currentRootMember); if (indexOfCurrentMemberNode != rootExpressionNode.getChildCount() - 1) { + var nextNode = rootExpressionNode.children.get(indexOfCurrentMemberNode + 1); return !(Trees.nodeContains(nextNode, BSLParser.RULE_compareOperation)); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java index 72ac052e999..d4b9ca77584 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java @@ -222,17 +222,34 @@ public static BSLParserRuleContext getRootParent(BSLParserRuleContext tnc) { } /** - * Рекурсивно находит самого верхнего родителя текущей ноды нужно типа + * Рекурсивно находит самого верхнего родителя текущей ноды нужного типа */ public static BSLParserRuleContext getRootParent(BSLParserRuleContext tnc, int ruleindex) { - if (tnc.getParent() == null) { + final var parent = tnc.getParent(); + if (parent == null) { + return null; + } + + if (getRuleIndex(parent) == ruleindex) { + return (BSLParserRuleContext) parent; + } else { + return getRootParent((BSLParserRuleContext) parent, ruleindex); + } + } + + /** + * Рекурсивно находит самого верхнего родителя текущей ноды одного из нужных типов + */ + public static BSLParserRuleContext getRootParent(BSLParserRuleContext tnc, List indexes) { + final var parent = tnc.getParent(); + if (parent == null) { return null; } - if (getRuleIndex(tnc.getParent()) == ruleindex) { - return (BSLParserRuleContext) tnc.getParent(); + if (indexes.contains(getRuleIndex(parent))) { + return (BSLParserRuleContext) parent; } else { - return getRootParent((BSLParserRuleContext) tnc.getParent(), ruleindex); + return getRootParent((BSLParserRuleContext) parent, indexes); } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java index e62504d631f..6b9bf82d0e9 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java @@ -38,10 +38,11 @@ void test() { List diagnostics = getDiagnostics(); - assertThat(diagnostics).hasSize(3); + assertThat(diagnostics).hasSize(4); assertThat(diagnostics, true) .hasRange(1, 9, 1, 24) .hasRange(3, 17, 3, 32) - .hasRange(7, 12, 7, 27); + .hasRange(7, 12, 7, 27) + .hasRange(24, 33, 24, 48); } } From c77f0dc24628ad9c4070debb221b2ea3237e6fba Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Wed, 6 May 2020 19:24:09 +0300 Subject: [PATCH 258/444] =?UTF-8?q?=D0=BF=D1=80=D0=BE=D0=BF=D1=83=D1=89?= =?UTF-8?q?=D0=B5=D0=BD=D0=BD=D1=8B=D0=B5=20=D1=82=D0=B5=D1=81=D1=82-?= =?UTF-8?q?=D0=BA=D0=B5=D0=B9=D1=81=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl b/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl index d33de2443ab..d056309c056 100644 --- a/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl +++ b/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl @@ -16,4 +16,12 @@ Если Тест() ИЛИ Тест = Истина Тогда // Нет срабатывания // код КонецЕсли; + + Если Истина Тогда + Перем1 = БезопасныйРежим(); // Нет срабатывания + Перем1 = Метод(БезопасныйРежим()); // Нет срабатывания + КонецЕсли; + + Если Условие И (Условие2 Или БезопасныйРежим()) Тогда // Есть срабатывание + КонецЕсли; КонецПроцедуры \ No newline at end of file From ab23128d9e1193ee1a8bf3cdebd356177be6ae06 Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Thu, 7 May 2020 00:19:11 +0300 Subject: [PATCH 259/444] =?UTF-8?q?=D0=BF=D0=B0=D0=B4=D0=B0=D1=8E=D1=89?= =?UTF-8?q?=D0=B8=D0=B5=20=D1=82=D0=B5=D1=81=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...nsafeSafeModeMethodCallDiagnosticTest.java | 12 +++++++--- .../UnsafeSafeModeMethodCallDiagnostic.bsl | 24 ++++++++++++++++--- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java index 6b9bf82d0e9..4b38e4ffdc5 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java @@ -38,11 +38,17 @@ void test() { List diagnostics = getDiagnostics(); - assertThat(diagnostics).hasSize(4); + assertThat(diagnostics).hasSize(9); assertThat(diagnostics, true) .hasRange(1, 9, 1, 24) .hasRange(3, 17, 3, 32) .hasRange(7, 12, 7, 27) - .hasRange(24, 33, 24, 48); + .hasRange(11, 33, 11, 48) + .hasRange(14, 47, 14, 62) + .hasRange(16, 50, 16, 65) + .hasRange(18, 34, 18, 49) + .hasRange(20, 34, 20, 49) + .hasRange(23, 20, 23, 35) + ; } -} +} \ No newline at end of file diff --git a/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl b/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl index d056309c056..ba7ba390f90 100644 --- a/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl +++ b/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl @@ -9,6 +9,21 @@ // Логика выполнения в небезопасном режиме... КонецЕсли; + Если Условие И (Условие2 Или БезопасныйРежим()) Тогда // Есть срабатывание + КонецЕсли; + + ФинальноеУсловие = Условие И (Условие2 Или БезопасныйРежим()); // Есть срабатывание + + ФинальноеУсловие = Условие И (Условие2 Или Не БезопасныйРежим()); // Есть срабатывание + + ФинальноеУсловие = Условие И (БезопасныйРежим() Или Условие2); // Есть срабатывание + + Если Условие И (Условие2 И Не БезопасныйРежим())) Тогда // Есть срабатывание + КонецЕсли; + + Если Условие И (БезопасныйРежим() И Условие)) Тогда // Есть срабатывание + КонецЕсли; + Если БезопасныйРежим() <> Ложь Тогда // Нет срабатывания // Логика выполнения в безопасном режиме... КонецЕсли; @@ -19,9 +34,12 @@ Если Истина Тогда Перем1 = БезопасныйРежим(); // Нет срабатывания - Перем1 = Метод(БезопасныйРежим()); // Нет срабатывания - КонецЕсли; - Если Условие И (Условие2 Или БезопасныйРежим()) Тогда // Есть срабатывание + Перем2 = Метод(БезопасныйРежим()); // Нет срабатывания КонецЕсли; + + ФинальноеУсловие1 = Условие1 И (Условие12 Или БезопасныйРежим() = Истина); // Нет срабатывания + + ФинальноеУсловие2 = Условие2 И (Ложь <> БезопасныйРежим() Или Условие2); // Нет срабатывания + КонецПроцедуры \ No newline at end of file From 1c4631581fce444d9b28ba20b4250bc557b6759e Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Thu, 7 May 2020 00:36:27 +0300 Subject: [PATCH 260/444] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=BD=D0=B0=D1=8F=20=D1=80=D0=B5=D0=B0=D0=BB?= =?UTF-8?q?=D0=B8=D0=B7=D0=B0=D1=86=D0=B8=D1=8F=20-=20=D0=BB=D0=BE=D0=B2?= =?UTF-8?q?=D1=8F=D1=82=D1=81=D1=8F=20=D1=83=D1=81=D0=BB=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=8F=20=D0=B2=20=D0=95=D1=81=D0=BB=D0=B8\=D0=98=D0=BD=D0=B0?= =?UTF-8?q?=D1=87=D0=B5=D0=95=D1=81=D0=BB=D0=B8=20+=20=D0=B8=D1=81=D0=BF?= =?UTF-8?q?=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5=20?= =?UTF-8?q?=D0=B2=20=D0=BE=D0=B1=D1=8B=D1=87=D0=BD=D1=8B=D1=85=20=D0=B2?= =?UTF-8?q?=D1=8B=D1=80=D0=B0=D0=B6=D0=B5=D0=BD=D0=B8=D1=8F=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UnsafeSafeModeMethodCallDiagnostic.java | 42 ++++++++++++++----- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java index ac25c27a844..4732e7ab904 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java @@ -55,7 +55,8 @@ public class UnsafeSafeModeMethodCallDiagnostic extends AbstractFindMethodDiagno Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE ); private static final List ROOT_LIST = Arrays.asList( - BSLParser.RULE_ifBranch, BSLParser.RULE_elsifBranch, BSLParser.RULE_codeBlock); + BSLParser.RULE_ifBranch, BSLParser.RULE_elsifBranch, BSLParser.RULE_expression, + BSLParser.RULE_codeBlock, BSLParser.RULE_assignment); private static final List IF_BRANCHES = Arrays.asList( BSLParser.RULE_ifBranch, BSLParser.RULE_elsifBranch); @@ -79,23 +80,44 @@ protected boolean checkGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { if (currentRootMember == null) { return false; } - BSLParserRuleContext rootExpressionNode = Trees.getRootParent(currentRootMember, BSLParser.RULE_expression); - if (rootExpressionNode == null) { - return false; + if (((BSLParserRuleContext)currentRootMember.getChild(0)).getRuleIndex() == BSLParser.RULE_unaryModifier){ + return true; } + BSLParserRuleContext rootExpressionNode = (BSLParserRuleContext) currentRootMember.getParent(); + BSLParserRuleContext rootIfNode = Trees.getRootParent(rootExpressionNode, ROOT_LIST); - if (rootIfNode == null || !IF_BRANCHES.contains(rootIfNode.getRuleIndex())) { + if (rootIfNode == null || rootIfNode.getRuleIndex() == BSLParser.RULE_codeBlock) { return false; } + if (rootExpressionNode.getChildCount() == 1 && IF_BRANCHES.contains(rootIfNode.getRuleIndex())){ + return true; + } - int indexOfCurrentMemberNode = rootExpressionNode.children.indexOf(currentRootMember); - if (indexOfCurrentMemberNode != rootExpressionNode.getChildCount() - 1) { + return haveNeighboorBooleanOperator(currentRootMember, rootExpressionNode); + } - var nextNode = rootExpressionNode.children.get(indexOfCurrentMemberNode + 1); - return !(Trees.nodeContains(nextNode, BSLParser.RULE_compareOperation)); + private static boolean haveNeighboorBooleanOperator(BSLParserRuleContext currentRootMember, + BSLParserRuleContext rootExpressionNode) { + boolean haveNeighboorBoolOperation = false; + int indexOfCurrentMemberNode = rootExpressionNode.children.indexOf(currentRootMember); + if (indexOfCurrentMemberNode > 0) { + var prev = (BSLParserRuleContext) rootExpressionNode.children.get(indexOfCurrentMemberNode - 1); + if (Trees.nodeContains(prev, BSLParser.RULE_compareOperation)){ + return false; + } + haveNeighboorBoolOperation = Trees.nodeContains(prev, BSLParser.RULE_boolOperation); } + if (indexOfCurrentMemberNode < rootExpressionNode.getChildCount() - 1) { - return true; + var next = (BSLParserRuleContext) rootExpressionNode.children.get(indexOfCurrentMemberNode + 1); + if (Trees.nodeContains(next, BSLParser.RULE_compareOperation)){ + return false; + } + if (!haveNeighboorBoolOperation){ + haveNeighboorBoolOperation = Trees.nodeContains(next, BSLParser.RULE_boolOperation); + } + } + return haveNeighboorBoolOperation; } } From 60763957e932467297e30e620f1845bacb916295 Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Thu, 7 May 2020 00:36:48 +0300 Subject: [PATCH 261/444] =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D1=81=D0=B0=D0=BC=D1=8B=D0=B9=20=D0=BF=D1=80=D0=BE?= =?UTF-8?q?=D1=81=D1=82=D0=BE=D0=B9=20=D0=BA=D0=B5=D0=B9=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java | 3 ++- .../diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java index 4b38e4ffdc5..477bd664fdf 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java @@ -38,7 +38,7 @@ void test() { List diagnostics = getDiagnostics(); - assertThat(diagnostics).hasSize(9); + assertThat(diagnostics).hasSize(10); assertThat(diagnostics, true) .hasRange(1, 9, 1, 24) .hasRange(3, 17, 3, 32) @@ -49,6 +49,7 @@ void test() { .hasRange(18, 34, 18, 49) .hasRange(20, 34, 20, 49) .hasRange(23, 20, 23, 35) + .hasRange(26, 9, 26, 24) ; } } \ No newline at end of file diff --git a/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl b/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl index ba7ba390f90..6531bcbcd26 100644 --- a/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl +++ b/src/test/resources/diagnostics/UnsafeSafeModeMethodCallDiagnostic.bsl @@ -24,6 +24,10 @@ Если Условие И (БезопасныйРежим() И Условие)) Тогда // Есть срабатывание КонецЕсли; + Если БезопасныйРежим() Тогда //Есть срабатывание + // Логика выполнения в безопасном режиме... + КонецЕсли; + Если БезопасныйРежим() <> Ложь Тогда // Нет срабатывания // Логика выполнения в безопасном режиме... КонецЕсли; From 4e9dc8d62b6ce6739a6904c1c0a15e47a93dfbb2 Mon Sep 17 00:00:00 2001 From: evgeniy Date: Thu, 7 May 2020 07:31:16 +0300 Subject: [PATCH 262/444] Fix FN. Skip all StatementContext because they may be empty. --- .../bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java index 162f8348fb2..de56b592b40 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java @@ -66,7 +66,8 @@ public void enterEveryRule(ParserRuleContext ctx) { regions.push((BSLParser.RegionStartContext) ctx); } else if (! (ctx instanceof BSLParser.PreprocessorContext || ctx instanceof BSLParser.RegionNameContext - || ctx instanceof BSLParser.RegionEndContext) + || ctx instanceof BSLParser.RegionEndContext + || ctx instanceof BSLParser.StatementContext) && currentUsageLevel < currentRegionLevel) { currentUsageLevel = currentRegionLevel; } From f0bba75740ba5cebb7d09c0963c5e017a7492687 Mon Sep 17 00:00:00 2001 From: evgeniy Date: Thu, 7 May 2020 07:45:06 +0300 Subject: [PATCH 263/444] Restore ranges. Fix build. --- .../bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java index 30d40784a31..6e3076a45de 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java @@ -79,7 +79,7 @@ public void exitEveryRule(ParserRuleContext ctx) { BSLParser.RegionStartContext currentRegion = regions.pop(); if (currentUsageLevel < currentRegionLevel) { diagnosticStorage.addDiagnostic( - Ranges.create(currentRegion), + Ranges.create(currentRegion.getParent(), ctx), info.getMessage(currentRegion.regionName().getText()) ); } else if (currentRegionLevel == currentUsageLevel) { From 60d5118c4ad84ea05110bf8d9176870e85b70bfd Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Thu, 7 May 2020 19:29:20 +0300 Subject: [PATCH 264/444] =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20javadoc=20=D0=B8=20=D0=B8=D1=81=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=B8=D0=BB=20=D1=82=D0=B8=D0=BF=20=D0=BA=D0=BE=D0=BB?= =?UTF-8?q?=D0=BB=D0=B5=D0=BA=D1=86=D0=B8=D0=B8=20=D0=B4=D0=BB=D1=8F=20?= =?UTF-8?q?=D1=83=D0=BD=D0=B8=D0=B2=D0=B5=D1=80=D1=81=D0=B0=D0=BB=D1=8C?= =?UTF-8?q?=D0=BD=D0=BE=D1=81=D1=82=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../_1c_syntax/bsl/languageserver/utils/Trees.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java index d4b9ca77584..ad05adb4c7a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java @@ -223,6 +223,10 @@ public static BSLParserRuleContext getRootParent(BSLParserRuleContext tnc) { /** * Рекурсивно находит самого верхнего родителя текущей ноды нужного типа + * + * @param tnc - нода, для которой ищем родителя + * @param ruleindex - BSLParser.RULE_* + * @return tnc - если родитель не найден, вернет null */ public static BSLParserRuleContext getRootParent(BSLParserRuleContext tnc, int ruleindex) { final var parent = tnc.getParent(); @@ -239,8 +243,12 @@ public static BSLParserRuleContext getRootParent(BSLParserRuleContext tnc, int r /** * Рекурсивно находит самого верхнего родителя текущей ноды одного из нужных типов + * + * @param tnc - нода, для которой ищем родителя + * @param indexes - Collection of BSLParser.RULE_* + * @return tnc - если родитель не найден, вернет null */ - public static BSLParserRuleContext getRootParent(BSLParserRuleContext tnc, List indexes) { + public static BSLParserRuleContext getRootParent(BSLParserRuleContext tnc, Collection indexes) { final var parent = tnc.getParent(); if (parent == null) { return null; From ac38cbede5480c9da9ca912231b389ce71fc8afd Mon Sep 17 00:00:00 2001 From: Artur Ayukhanov Date: Thu, 7 May 2020 19:30:26 +0300 Subject: [PATCH 265/444] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D0=BE=D0=BB=D1=8C?= =?UTF-8?q?=D0=B7=D1=83=D1=8E=20Set=20=20+=20=D1=83=D0=BF=D1=80=D0=BE?= =?UTF-8?q?=D1=81=D1=82=D0=B8=D0=BB=20=D0=BA=D0=BE=D0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UnsafeSafeModeMethodCallDiagnostic.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java index 4732e7ab904..44d94f4119e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java @@ -32,8 +32,7 @@ import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; -import java.util.Arrays; -import java.util.List; +import java.util.Set; import java.util.regex.Pattern; @DiagnosticMetadata( @@ -54,10 +53,10 @@ public class UnsafeSafeModeMethodCallDiagnostic extends AbstractFindMethodDiagno "(БезопасныйРежим|SafeMode)", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE ); - private static final List ROOT_LIST = Arrays.asList( + private static final Set ROOT_LIST = Set.of( BSLParser.RULE_ifBranch, BSLParser.RULE_elsifBranch, BSLParser.RULE_expression, BSLParser.RULE_codeBlock, BSLParser.RULE_assignment); - private static final List IF_BRANCHES = Arrays.asList( + private static final Set IF_BRANCHES = Set.of( BSLParser.RULE_ifBranch, BSLParser.RULE_elsifBranch); public UnsafeSafeModeMethodCallDiagnostic(DiagnosticInfo info) { @@ -76,11 +75,15 @@ protected boolean checkGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { return false; } - BSLParserRuleContext currentRootMember = Trees.getRootParent(ctx, BSLParser.RULE_member); + BSLParser.MemberContext currentRootMember = (BSLParser.MemberContext)Trees.getRootParent(ctx, BSLParser.RULE_member); if (currentRootMember == null) { return false; } - if (((BSLParserRuleContext)currentRootMember.getChild(0)).getRuleIndex() == BSLParser.RULE_unaryModifier){ + return nonValidExpression(currentRootMember); + } + + private static boolean nonValidExpression(BSLParser.MemberContext currentRootMember) { + if (currentRootMember.unaryModifier() != null){ return true; } From e81bcebee4333e5d91ff49bc38f247098520ea25 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Thu, 7 May 2020 22:29:04 +0300 Subject: [PATCH 266/444] fix unreacheable preproc_endIf fp --- .../diagnostics/UnreachableCodeDiagnostic.java | 2 +- .../diagnostics/UnreachableCodeDiagnosticTest.java | 10 +++++++++- .../diagnostics/UnreachableCodeRegionDiagnostic.bsl | 11 +++++++++++ 3 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 src/test/resources/diagnostics/UnreachableCodeRegionDiagnostic.bsl diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnostic.java index 4d245a1a155..9d2a6a185a1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnostic.java @@ -174,7 +174,7 @@ private void findAndAddDiagnostic(BSLParserRuleContext ctx) { .stream() .filter(node -> node.getStart().getType() != BSLLexer.SEMICOLON - && !Trees.nodeContains(node, BSLParser.RULE_regionStart, BSLParser.RULE_regionEnd)) + && !Trees.nodeContains(node, BSLParser.RULE_regionStart, BSLParser.RULE_regionEnd, BSLParser.RULE_preproc_endif)) .collect(Collectors.toList()); // если в блоке кода есть еще стейты кроме текущего diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnosticTest.java index 738ac8f5d3c..057ad74b464 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnosticTest.java @@ -50,10 +50,18 @@ void test() { .hasRange(82, 16, 84, 25) .hasRange(93, 8, 16) .hasRange(102, 8, 17) - .hasRange(108, 16, 112, 26) + .hasRange(108, 16, 111, 29) .hasRange(138, 4, 16) .hasRange(161, 4, 13) .hasRange(166, 4, 168, 13) .hasRange(172, 0, 9); } + + @Test + void testRegion() { + List diagnostics = getDiagnostics("UnreachableCodeRegionDiagnostic"); + + assertThat(diagnostics).hasSize(0); + + } } diff --git a/src/test/resources/diagnostics/UnreachableCodeRegionDiagnostic.bsl b/src/test/resources/diagnostics/UnreachableCodeRegionDiagnostic.bsl new file mode 100644 index 00000000000..cc669c3aeea --- /dev/null +++ b/src/test/resources/diagnostics/UnreachableCodeRegionDiagnostic.bsl @@ -0,0 +1,11 @@ +#Если Сервер Или ТолстыйКлиентОбычноеПриложение Или ВнешнееСоединение Тогда + +#Иначе + +#Область Инициализация + + ВызватьИсключение НСтр("ru = 'Недопустимый вызов объекта на клиенте.'"); + +#КонецОбласти + +#КонецЕсли From 8717d86829960e22945500231f821946424eeee7 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Thu, 7 May 2020 11:44:07 +0300 Subject: [PATCH 267/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D1=81=D1=81=D1=8B=D0=BB=D0=BAb=20=D0=BD=D0=B0=20?= =?UTF-8?q?=D0=BC=D0=B5=D1=82=D0=B0=D0=B4=D0=B0=D0=BD=D0=BD=D1=8B=D0=B5=20?= =?UTF-8?q?mdoRef=20=D0=B2=20MethodSymbol=20=D0=B8=20ServerContext?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../languageserver/context/ServerContext.java | 66 ++++++++++++++++++- .../computer/MethodSymbolComputer.java | 6 ++ .../context/symbol/MethodSymbol.java | 6 ++ .../context/ServerContextTest.java | 38 +++++++++++ .../computer/MethodSymbolComputerTest.java | 31 +++++++++ .../Ext/ManagerModule.bsl" | 2 +- .../Ext/ObjectModule.bsl" | 2 +- .../Ext/Module.bsl" | 2 +- 8 files changed, 149 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java index d4b62c01410..3062297b29a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java @@ -21,7 +21,9 @@ */ package com.github._1c_syntax.bsl.languageserver.context; +import com.github._1c_syntax.mdclasses.mdo.MDObjectBase; import com.github._1c_syntax.mdclasses.metadata.Configuration; +import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; import com.github._1c_syntax.utils.Absolute; import com.github._1c_syntax.utils.Lazy; import org.eclipse.lsp4j.TextDocumentItem; @@ -38,6 +40,8 @@ public class ServerContext { private final Lazy configurationMetadata = new Lazy<>(this::computeConfigurationMetadata); @CheckForNull private Path configurationRoot; + private final Map mdoRefs = Collections.synchronizedMap(new HashMap<>()); + private final Map> documentsByMDORef = Collections.synchronizedMap(new HashMap<>()); public ServerContext() { this(null); @@ -51,16 +55,37 @@ public Map getDocuments() { return Collections.unmodifiableMap(documents); } + public Map getMdoRefs() { + return Collections.unmodifiableMap(mdoRefs); + } + + public Map> getDocumentsByMdoRef() { + return Collections.unmodifiableMap(documentsByMDORef); + } + @CheckForNull public DocumentContext getDocument(String uri) { return getDocument(URI.create(uri)); } + public DocumentContext getDocument(String mdoRef, ModuleType moduleType) { + var documentsGroup = documentsByMDORef.get(mdoRef); + if (documentsGroup != null) { + return documentsGroup.get(moduleType); + } + return null; + } + @CheckForNull public DocumentContext getDocument(URI uri) { return documents.get(Absolute.uri(uri)); } + @CheckForNull + public Map getDocumentsByMdoRef(String mdoRef) { + return documentsByMDORef.get(mdoRef); + } + public DocumentContext addDocument(URI uri, String content) { URI absoluteURI = Absolute.uri(uri); @@ -68,6 +93,7 @@ public DocumentContext addDocument(URI uri, String content) { if (documentContext == null) { documentContext = new DocumentContext(absoluteURI, content, this); documents.put(absoluteURI, documentContext); + addMdoRefByUri(absoluteURI, documentContext); } else { documentContext.rebuild(content); } @@ -80,11 +106,15 @@ public DocumentContext addDocument(TextDocumentItem textDocumentItem) { } public void removeDocument(URI uri) { - documents.remove(Absolute.uri(uri)); + URI absoluteURI = Absolute.uri(uri); + removeDocumentMdoRefByUri(absoluteURI); + documents.remove(absoluteURI); } public void clear() { documents.clear(); + documentsByMDORef.clear(); + mdoRefs.clear(); configurationMetadata.clear(); } @@ -103,4 +133,38 @@ private Configuration computeConfigurationMetadata() { return Configuration.create(configurationRoot); } + + private void addMdoRefByUri(URI uri, DocumentContext documentContext) { + addMdoRefByUri(getConfiguration().getModulesByURI(), uri, documentContext); + } + + private void addMdoRefByUri(Map modulesByUri, URI uri, DocumentContext documentContext) { + var mdoByUri = modulesByUri.get(uri); + if (mdoByUri != null) { + var mdoRef = mdoByUri.getMdoRef(); + mdoRefs.put(uri, mdoRef); + var documentsGroup = documentsByMDORef.get(mdoRef); + if (documentsGroup == null) { + Map newDocumentsGroup = new HashMap<>(); + newDocumentsGroup.put(documentContext.getModuleType(), documentContext); + documentsByMDORef.put(mdoRef, newDocumentsGroup); + } else { + documentsGroup.put(documentContext.getModuleType(), documentContext); + } + } + } + + private void removeDocumentMdoRefByUri(URI uri) { + var mdoRef = mdoRefs.get(uri); + if (mdoRef != null) { + var documentsGroup = documentsByMDORef.get(mdoRef); + if (documentsGroup != null) { + documentsGroup.remove(documents.get(uri).getModuleType()); + if (documentsGroup.isEmpty()) { + documentsByMDORef.remove(mdoRef); + } + } + mdoRefs.remove(uri); + } + } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java index 559aba92f1f..9ba5578f13d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java @@ -29,6 +29,7 @@ import com.github._1c_syntax.bsl.languageserver.utils.Trees; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserBaseVisitor; +import com.github._1c_syntax.mdclasses.mdo.MDObjectBase; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.ParseTree; @@ -130,6 +131,10 @@ private MethodSymbol createMethodSymbol( .map(MethodDescription::isDeprecated) .orElse(false); + String mdoRef = documentContext.getMdObject() + .map(MDObjectBase::getMdoRef) + .orElse(null); + return MethodSymbol.builder() .name(subName.getText()) .range(Ranges.create(startNode, stopNode)) @@ -138,6 +143,7 @@ private MethodSymbol createMethodSymbol( .export(export) .description(description) .deprecated(deprecated) + .mdoRef(mdoRef) .parameters(createParameters(paramList)) .build(); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java index 46b94f8d48e..0f4e5b944c9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java @@ -59,6 +59,12 @@ public class MethodSymbol implements Symbol { boolean deprecated; + /** + * Ссылка на объект метаданных, в модуле которого находится метод + * Формат ссылки: Document.Заказ, CommonModule.ОбщегоНазначения + */ + String mdoRef; + @Builder.Default List parameters = new ArrayList<>(); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java index 515eb9aa948..eed6bfefe7f 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java @@ -26,9 +26,12 @@ import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; import com.github._1c_syntax.mdclasses.metadata.additional.ScriptVariant; import com.github._1c_syntax.utils.Absolute; +import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.Test; import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; @@ -38,6 +41,8 @@ public class ServerContextTest { private static final String PATH_TO_METADATA = "src/test/resources/metadata"; private static final String PATH_TO_MODULE_FILE = "CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; + private static final String PATH_TO_CATALOG_FILE = "Catalogs/Справочник1/Ext/ManagerModule.bsl"; + private static final String PATH_TO_CATALOG_MODULE_FILE = "Catalogs/Справочник1/Ext/ObjectModule.bsl"; @Test void testConfigurationMetadata() { @@ -62,6 +67,34 @@ void testConfigurationMetadata() { } + @Test + void testMdoRefs() throws IOException { + + var path = Absolute.path(PATH_TO_METADATA); + var serverContext = new ServerContext(path); + var mdoRefCommonModule = "CommonModule.ПервыйОбщийМодуль"; + + DocumentContext documentContext = addDocumentContext(serverContext, PATH_TO_MODULE_FILE); + assertThat(serverContext.getMdoRefs()).hasSize(1); + assertThat(serverContext.getDocumentsByMdoRef()).hasSize(1); + assertThat(serverContext.getDocument(mdoRefCommonModule, documentContext.getModuleType())) + .isEqualTo(documentContext); + assertThat(serverContext.getDocumentsByMdoRef(mdoRefCommonModule)) + .hasSize(1) + .containsKey(documentContext.getModuleType()) + .containsValue(documentContext); + + addDocumentContext(serverContext, PATH_TO_CATALOG_MODULE_FILE); + addDocumentContext(serverContext, PATH_TO_CATALOG_FILE); + + assertThat(serverContext.getMdoRefs()).hasSize(3); + assertThat(serverContext.getDocumentsByMdoRef()).hasSize(2); + + assertThat(serverContext.getDocumentsByMdoRef("Catalog.Справочник1")) + .hasSize(2) + .containsKeys(ModuleType.ManagerModule, ModuleType.ObjectModule); + } + @Test void testErrorConfigurationMetadata() { Path path = Absolute.path(Paths.get(PATH_TO_METADATA, "test")); @@ -74,4 +107,9 @@ void testErrorConfigurationMetadata() { assertThat(configurationMetadata.getModulesByType()).hasSize(0); } + private DocumentContext addDocumentContext(ServerContext serverContext, String path) throws IOException { + var file = new File(PATH_TO_METADATA, path); + var uri = Absolute.uri(file); + return serverContext.addDocument(uri, FileUtils.readFileToString(file, StandardCharsets.UTF_8)); + } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java index c8cf325fdb4..a87d3889c4d 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java @@ -22,18 +22,29 @@ package com.github._1c_syntax.bsl.languageserver.context.computer; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.ServerContext; import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; import com.github._1c_syntax.bsl.languageserver.context.symbol.ParameterDefinition; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.utils.Absolute; +import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.Test; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class MethodSymbolComputerTest { + private static final String PATH_TO_METADATA = "src/test/resources/metadata"; + private static final String PATH_TO_MODULE_FILE = "CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; + private static final String PATH_TO_CATALOG_FILE = "Catalogs/Справочник1/Ext/ManagerModule.bsl"; + private static final String PATH_TO_CATALOG_MODULE_FILE = "Catalogs/Справочник1/Ext/ObjectModule.bsl"; + @Test void testMethodSymbolComputer() { @@ -99,6 +110,16 @@ void testDeprecated() { assertThat(methodSymbol.getDescription().orElseThrow().getDeprecatedInfo()).isNotEmpty(); } + @Test + void testMdoRef() throws IOException { + + var path = Absolute.path(PATH_TO_METADATA); + var serverContext = new ServerContext(path); + checkModule(serverContext, PATH_TO_MODULE_FILE, "CommonModule.ПервыйОбщийМодуль"); + checkModule(serverContext, PATH_TO_CATALOG_FILE, "Catalog.Справочник1"); + checkModule(serverContext, PATH_TO_CATALOG_MODULE_FILE, "Catalog.Справочник1"); + } + @Test void testParseError() { @@ -109,4 +130,14 @@ void testParseError() { assertThat(methods.get(0).getSubNameRange()).isEqualTo(Ranges.create(0, 10, 0, 19)); } + + private void checkModule(ServerContext serverContext, String path, String mdoRef) throws IOException { + var file = new File(PATH_TO_METADATA, path); + var uri = Absolute.uri(file); + var documentContext = serverContext.addDocument(uri, FileUtils.readFileToString(file, StandardCharsets.UTF_8)); + List methods = documentContext.getSymbolTree().getMethods(); + assertThat(methods.size()).isEqualTo(1); + assertThat(methods.get(0).getName()).isEqualTo("Тест"); + assertThat(methods.get(0).getMdoRef()).isEqualTo(mdoRef); + } } diff --git "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Ext/ManagerModule.bsl" "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Ext/ManagerModule.bsl" index 5336dff9ef1..9e86853259e 100644 --- "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Ext/ManagerModule.bsl" +++ "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Ext/ManagerModule.bsl" @@ -14,7 +14,7 @@ #КонецОбласти #Область СлужебныеПроцедурыИФункции -// Код процедур и функций +Процедура Тест() КонецПроцедуры #КонецОбласти diff --git "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Ext/ObjectModule.bsl" "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Ext/ObjectModule.bsl" index 5336dff9ef1..ccb85c7239d 100644 --- "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Ext/ObjectModule.bsl" +++ "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Ext/ObjectModule.bsl" @@ -14,7 +14,7 @@ #КонецОбласти #Область СлужебныеПроцедурыИФункции -// Код процедур и функций +Function Тест() EndFunction #КонецОбласти diff --git "a/src/test/resources/metadata/CommonModules/\320\237\320\265\321\200\320\262\321\213\320\271\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\214/Ext/Module.bsl" "b/src/test/resources/metadata/CommonModules/\320\237\320\265\321\200\320\262\321\213\320\271\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\214/Ext/Module.bsl" index feb46be66dd..b91677cafa7 100644 --- "a/src/test/resources/metadata/CommonModules/\320\237\320\265\321\200\320\262\321\213\320\271\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\214/Ext/Module.bsl" +++ "b/src/test/resources/metadata/CommonModules/\320\237\320\265\321\200\320\262\321\213\320\271\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\214/Ext/Module.bsl" @@ -52,7 +52,7 @@ #КонецОбласти #Область СлужебныеПроцедурыИФункции -// Код процедур и функций +Функция Тест() КонецФункции #КонецОбласти #Region Initialize From b4160af90a3a8b599ed83eab062650d0f0c51051 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Thu, 7 May 2020 12:26:18 +0300 Subject: [PATCH 268/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D1=82=D0=B5=D1=81=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../bsl/languageserver/context/ServerContext.java | 3 ++- .../bsl/languageserver/context/ServerContextTest.java | 9 +++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java index 3062297b29a..b0a7edd3a3d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java @@ -41,7 +41,8 @@ public class ServerContext { @CheckForNull private Path configurationRoot; private final Map mdoRefs = Collections.synchronizedMap(new HashMap<>()); - private final Map> documentsByMDORef = Collections.synchronizedMap(new HashMap<>()); + private final Map> documentsByMDORef + = Collections.synchronizedMap(new HashMap<>()); public ServerContext() { this(null); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java index eed6bfefe7f..bc41c77eaf5 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java @@ -87,12 +87,21 @@ void testMdoRefs() throws IOException { addDocumentContext(serverContext, PATH_TO_CATALOG_MODULE_FILE); addDocumentContext(serverContext, PATH_TO_CATALOG_FILE); + // для проверки на дубль + addDocumentContext(serverContext, PATH_TO_CATALOG_FILE); + assertThat(serverContext.getMdoRefs()).hasSize(3); assertThat(serverContext.getDocumentsByMdoRef()).hasSize(2); assertThat(serverContext.getDocumentsByMdoRef("Catalog.Справочник1")) .hasSize(2) .containsKeys(ModuleType.ManagerModule, ModuleType.ObjectModule); + + serverContext.removeDocument(Absolute.uri(new File(PATH_TO_METADATA, PATH_TO_MODULE_FILE))); + assertThat(serverContext.getMdoRefs()).hasSize(2); + assertThat(serverContext.getDocumentsByMdoRef()).hasSize(1); + + assertThat(serverContext.getDocument(mdoRefCommonModule, ModuleType.CommonModule)).isNull(); } @Test From dd2aa47abb4b8a407ad63d787142827c6eba2221 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Thu, 7 May 2020 23:13:54 +0300 Subject: [PATCH 269/444] to EnumMap --- .../_1c_syntax/bsl/languageserver/context/ServerContext.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java index b0a7edd3a3d..7d46a721f45 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java @@ -32,6 +32,7 @@ import java.net.URI; import java.nio.file.Path; import java.util.Collections; +import java.util.EnumMap; import java.util.HashMap; import java.util.Map; @@ -146,7 +147,7 @@ private void addMdoRefByUri(Map modulesByUri, URI uri, Docume mdoRefs.put(uri, mdoRef); var documentsGroup = documentsByMDORef.get(mdoRef); if (documentsGroup == null) { - Map newDocumentsGroup = new HashMap<>(); + Map newDocumentsGroup = new EnumMap<>(ModuleType.class); newDocumentsGroup.put(documentContext.getModuleType(), documentContext); documentsByMDORef.put(mdoRef, newDocumentsGroup); } else { From ffefe4057b42a9c19f68bf44871b80c92c19e0ea Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Thu, 7 May 2020 23:16:20 +0300 Subject: [PATCH 270/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BD=D0=BE=D0=B2=D1=8B=D0=B9=20=D0=BA=D0=BE=D0=BC?= =?UTF-8?q?=D0=BF=D0=BE=D0=BD=D0=B5=D0=BD=D1=82=20documentLink?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../bsl/languageserver/BSLLanguageServer.java | 2 + .../BSLTextDocumentService.java | 17 +++- .../providers/DocumentLinkProvider.java | 56 +++++++++++ .../providers/DocumentLinkProviderTest.java | 97 +++++++++++++++++++ .../.bsl-language-server-only-en-param.json | 3 + .../providers/documentLinkProvider.bsl | 5 + 6 files changed, 179 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProviderTest.java create mode 100644 src/test/resources/.bsl-language-server-only-en-param.json create mode 100644 src/test/resources/providers/documentLinkProvider.bsl diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServer.java index 24e77222dc7..06980c45f30 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServer.java @@ -25,6 +25,7 @@ import com.github._1c_syntax.bsl.languageserver.context.ServerContext; import lombok.extern.slf4j.Slf4j; import org.eclipse.lsp4j.CodeLensOptions; +import org.eclipse.lsp4j.DocumentLinkOptions; import org.eclipse.lsp4j.InitializeParams; import org.eclipse.lsp4j.InitializeResult; import org.eclipse.lsp4j.ServerCapabilities; @@ -76,6 +77,7 @@ public CompletableFuture initialize(InitializeParams params) { capabilities.setDocumentSymbolProvider(Boolean.TRUE); capabilities.setCodeActionProvider(Boolean.TRUE); capabilities.setCodeLensProvider(new CodeLensOptions()); + capabilities.setDocumentLinkProvider(new DocumentLinkOptions()); InitializeResult result = new InitializeResult(capabilities); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentService.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentService.java index 89d0dea4e30..a794a9ee6e7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentService.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentService.java @@ -22,14 +22,15 @@ package com.github._1c_syntax.bsl.languageserver; import com.github._1c_syntax.bsl.languageserver.codeactions.QuickFixSupplier; -import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.ComputeTrigger; import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; +import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.ComputeTrigger; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.context.ServerContext; import com.github._1c_syntax.bsl.languageserver.diagnostics.DiagnosticSupplier; 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.DiagnosticProvider; +import com.github._1c_syntax.bsl.languageserver.providers.DocumentLinkProvider; import com.github._1c_syntax.bsl.languageserver.providers.DocumentSymbolProvider; import com.github._1c_syntax.bsl.languageserver.providers.FoldingRangeProvider; import com.github._1c_syntax.bsl.languageserver.providers.FormatProvider; @@ -50,6 +51,8 @@ import org.eclipse.lsp4j.DocumentFormattingParams; import org.eclipse.lsp4j.DocumentHighlight; import org.eclipse.lsp4j.DocumentHighlightParams; +import org.eclipse.lsp4j.DocumentLink; +import org.eclipse.lsp4j.DocumentLinkParams; import org.eclipse.lsp4j.DocumentOnTypeFormattingParams; import org.eclipse.lsp4j.DocumentRangeFormattingParams; import org.eclipse.lsp4j.DocumentSymbol; @@ -85,6 +88,7 @@ public class BSLTextDocumentService implements TextDocumentService, LanguageClie private final DiagnosticProvider diagnosticProvider; private final CodeActionProvider codeActionProvider; private final CodeLensProvider codeLensProvider; + private final DocumentLinkProvider documentLinkProvider; @CheckForNull private LanguageClient client; @@ -99,6 +103,7 @@ public BSLTextDocumentService(LanguageServerConfiguration configuration, ServerC diagnosticProvider = new DiagnosticProvider(diagnosticSupplier); codeActionProvider = new CodeActionProvider(this.diagnosticProvider, quickFixSupplier); codeLensProvider = new CodeLensProvider(this.configuration); + documentLinkProvider = new DocumentLinkProvider(this.configuration, this.diagnosticProvider); } @Override @@ -281,6 +286,16 @@ public void connect(LanguageClient client) { this.client = client; } + @Override + public CompletableFuture> documentLink(DocumentLinkParams params) { + DocumentContext documentContext = context.getDocument(params.getTextDocument().getUri()); + if (documentContext == null) { + return CompletableFuture.completedFuture(null); + } + + return CompletableFuture.supplyAsync(() -> documentLinkProvider.getDocumentLinks(documentContext)); + } + public void reset() { diagnosticProvider.clearAllComputedDiagnostics(); context.clear(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java new file mode 100644 index 00000000000..4db41150eb1 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java @@ -0,0 +1,56 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.providers; + +import com.github._1c_syntax.bsl.languageserver.configuration.Language; +import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCode; +import org.eclipse.lsp4j.DocumentLink; + +import java.util.ArrayList; +import java.util.List; + +/** + * Класс-провайдер для реализации формирования ссылки на страницу с информацией по диагностике + */ +public class DocumentLinkProvider { + private final DiagnosticProvider diagnosticProvider; + private static final String SITE_DIAGNOSTICS_URL_RU = "https://1c-syntax.github.io/bsl-language-server/diagnostics/"; + private static final String SITE_DIAGNOSTICS_URL_EN = "https://1c-syntax.github.io/bsl-language-server/en/diagnostics/"; + private final LanguageServerConfiguration configuration; + + public DocumentLinkProvider(LanguageServerConfiguration configuration, DiagnosticProvider diagnosticProvider) { + this.diagnosticProvider = diagnosticProvider; + this.configuration = configuration; + } + + public List getDocumentLinks(DocumentContext documentContext) { + List documentLinks = new ArrayList<>(); + var siteDiagnosticsUrl = configuration.getLanguage().equals(Language.EN) + ? SITE_DIAGNOSTICS_URL_EN : SITE_DIAGNOSTICS_URL_RU; + diagnosticProvider.getComputedDiagnostics(documentContext) + .forEach(diagnostic -> documentLinks.add(new DocumentLink(diagnostic.getRange(), + siteDiagnosticsUrl + DiagnosticCode.getStringValue(diagnostic.getCode())))); + return documentLinks; + } +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProviderTest.java new file mode 100644 index 00000000000..4e3e792668d --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProviderTest.java @@ -0,0 +1,97 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.providers; + +import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.diagnostics.DiagnosticSupplier; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.Test; + +import java.io.File; + +import static org.assertj.core.api.Assertions.assertThat; + +class DocumentLinkProviderTest { + + private static final String SITE_URL = "https://1c-syntax.github.io/bsl-language-server/"; + private static final String SITE_EN_URL = "https://1c-syntax.github.io/bsl-language-server/en/"; + private static final String DIAGNOSTIC_CODE = "CanonicalSpellingKeywords"; + + @Test + void testGetDocumentLinks() { + + // given + var configuration = LanguageServerConfiguration.create(); + var documentContext = getDocumentContext(); + var documentLinkProvider = getDocumentLinkProvider(configuration, documentContext); + + // when + var documentLinks = documentLinkProvider.getDocumentLinks(documentContext); + + // then + assertThat(documentLinks) + .isNotEmpty() + .hasSize(7) + .allMatch(documentLink -> documentLink.getTarget() + .startsWith(SITE_URL)) + .filteredOn(documentLink -> !documentLink.getTarget().endsWith(DIAGNOSTIC_CODE)) + .hasSize(3); + } + + @Test + void testGetDocumentLinksEn() { + + // given + var configurationFile = new File("./src/test/resources/.bsl-language-server-only-en-param.json"); + var configuration = LanguageServerConfiguration.create(configurationFile); + var documentContext = getDocumentContext(); + var documentLinkProvider = getDocumentLinkProvider(configuration, documentContext); + + // when + var documentLinks = documentLinkProvider.getDocumentLinks(documentContext); + + // then + assertThat(documentLinks) + .isNotEmpty() + .hasSize(7) + .allMatch(documentLink -> documentLink.getTarget() + .startsWith(SITE_EN_URL)) + .filteredOn(documentLink -> !documentLink.getTarget().endsWith(DIAGNOSTIC_CODE)) + .hasSize(3); + } + + @NotNull + private DocumentLinkProvider getDocumentLinkProvider(LanguageServerConfiguration configuration, DocumentContext documentContext) { + var diagnosticSupplier = new DiagnosticSupplier(configuration); + var diagnosticProvider = new DiagnosticProvider(diagnosticSupplier); + diagnosticProvider.computeDiagnostics(documentContext); + return new DocumentLinkProvider(configuration, diagnosticProvider); + } + + @NotNull + private DocumentContext getDocumentContext() { + var filePath = "./src/test/resources/providers/documentLinkProvider.bsl"; + return TestUtils.getDocumentContextFromFile(filePath); + } +} \ No newline at end of file diff --git a/src/test/resources/.bsl-language-server-only-en-param.json b/src/test/resources/.bsl-language-server-only-en-param.json new file mode 100644 index 00000000000..a6042a4e442 --- /dev/null +++ b/src/test/resources/.bsl-language-server-only-en-param.json @@ -0,0 +1,3 @@ +{ + "language": "en" +} diff --git a/src/test/resources/providers/documentLinkProvider.bsl b/src/test/resources/providers/documentLinkProvider.bsl new file mode 100644 index 00000000000..dc5ec2acd07 --- /dev/null +++ b/src/test/resources/providers/documentLinkProvider.bsl @@ -0,0 +1,5 @@ +Процедура ИмяПроцедуры() + для каждого А из т цикл + Сообщить(А) + конецЦикла; +КонецПроцедуры \ No newline at end of file From 0c6573c0ef654c0aedfe0712e09b160795c25f85 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Fri, 8 May 2020 08:37:25 +0300 Subject: [PATCH 271/444] fix SQ --- .../bsl/languageserver/providers/DocumentLinkProvider.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java index 4db41150eb1..0e4faeb3aa0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java @@ -35,8 +35,8 @@ */ public class DocumentLinkProvider { private final DiagnosticProvider diagnosticProvider; - private static final String SITE_DIAGNOSTICS_URL_RU = "https://1c-syntax.github.io/bsl-language-server/diagnostics/"; - private static final String SITE_DIAGNOSTICS_URL_EN = "https://1c-syntax.github.io/bsl-language-server/en/diagnostics/"; + private static final String SITE_URL_RU = "https://1c-syntax.github.io/bsl-language-server/diagnostics/"; + private static final String SITE_URL_EN = "https://1c-syntax.github.io/bsl-language-server/en/diagnostics/"; private final LanguageServerConfiguration configuration; public DocumentLinkProvider(LanguageServerConfiguration configuration, DiagnosticProvider diagnosticProvider) { @@ -46,8 +46,7 @@ public DocumentLinkProvider(LanguageServerConfiguration configuration, Diagnosti public List getDocumentLinks(DocumentContext documentContext) { List documentLinks = new ArrayList<>(); - var siteDiagnosticsUrl = configuration.getLanguage().equals(Language.EN) - ? SITE_DIAGNOSTICS_URL_EN : SITE_DIAGNOSTICS_URL_RU; + var siteDiagnosticsUrl = configuration.getLanguage() == Language.EN ? SITE_URL_EN : SITE_URL_RU; diagnosticProvider.getComputedDiagnostics(documentContext) .forEach(diagnostic -> documentLinks.add(new DocumentLink(diagnostic.getRange(), siteDiagnosticsUrl + DiagnosticCode.getStringValue(diagnostic.getCode())))); From 035e6d175ed0803e3e7e69952c19a26b208a9d48 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Fri, 8 May 2020 09:13:19 +0300 Subject: [PATCH 272/444] fix CR --- .../languageserver/context/ServerContext.java | 22 +++++-------------- .../computer/MethodSymbolComputer.java | 2 +- .../context/ServerContextTest.java | 13 ++++------- 3 files changed, 11 insertions(+), 26 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java index 7d46a721f45..446587c65df 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java @@ -21,7 +21,6 @@ */ package com.github._1c_syntax.bsl.languageserver.context; -import com.github._1c_syntax.mdclasses.mdo.MDObjectBase; import com.github._1c_syntax.mdclasses.metadata.Configuration; import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; import com.github._1c_syntax.utils.Absolute; @@ -35,6 +34,7 @@ import java.util.EnumMap; import java.util.HashMap; import java.util.Map; +import java.util.Optional; public class ServerContext { private final Map documents = Collections.synchronizedMap(new HashMap<>()); @@ -57,25 +57,17 @@ public Map getDocuments() { return Collections.unmodifiableMap(documents); } - public Map getMdoRefs() { - return Collections.unmodifiableMap(mdoRefs); - } - - public Map> getDocumentsByMdoRef() { - return Collections.unmodifiableMap(documentsByMDORef); - } - @CheckForNull public DocumentContext getDocument(String uri) { return getDocument(URI.create(uri)); } - public DocumentContext getDocument(String mdoRef, ModuleType moduleType) { + public Optional getDocument(String mdoRef, ModuleType moduleType) { var documentsGroup = documentsByMDORef.get(mdoRef); if (documentsGroup != null) { - return documentsGroup.get(moduleType); + return Optional.ofNullable(documentsGroup.get(moduleType)); } - return null; + return Optional.empty(); } @CheckForNull @@ -137,11 +129,9 @@ private Configuration computeConfigurationMetadata() { } private void addMdoRefByUri(URI uri, DocumentContext documentContext) { - addMdoRefByUri(getConfiguration().getModulesByURI(), uri, documentContext); - } - - private void addMdoRefByUri(Map modulesByUri, URI uri, DocumentContext documentContext) { + var modulesByUri = getConfiguration().getModulesByURI(); var mdoByUri = modulesByUri.get(uri); + if (mdoByUri != null) { var mdoRef = mdoByUri.getMdoRef(); mdoRefs.put(uri, mdoRef); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java index 9ba5578f13d..376c263598d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java @@ -133,7 +133,7 @@ private MethodSymbol createMethodSymbol( String mdoRef = documentContext.getMdObject() .map(MDObjectBase::getMdoRef) - .orElse(null); + .orElse(""); return MethodSymbol.builder() .name(subName.getText()) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java index bc41c77eaf5..868aae9b8c7 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java @@ -75,9 +75,9 @@ void testMdoRefs() throws IOException { var mdoRefCommonModule = "CommonModule.ПервыйОбщийМодуль"; DocumentContext documentContext = addDocumentContext(serverContext, PATH_TO_MODULE_FILE); - assertThat(serverContext.getMdoRefs()).hasSize(1); - assertThat(serverContext.getDocumentsByMdoRef()).hasSize(1); assertThat(serverContext.getDocument(mdoRefCommonModule, documentContext.getModuleType())) + .isPresent() + .get() .isEqualTo(documentContext); assertThat(serverContext.getDocumentsByMdoRef(mdoRefCommonModule)) .hasSize(1) @@ -90,18 +90,13 @@ void testMdoRefs() throws IOException { // для проверки на дубль addDocumentContext(serverContext, PATH_TO_CATALOG_FILE); - assertThat(serverContext.getMdoRefs()).hasSize(3); - assertThat(serverContext.getDocumentsByMdoRef()).hasSize(2); - assertThat(serverContext.getDocumentsByMdoRef("Catalog.Справочник1")) .hasSize(2) .containsKeys(ModuleType.ManagerModule, ModuleType.ObjectModule); serverContext.removeDocument(Absolute.uri(new File(PATH_TO_METADATA, PATH_TO_MODULE_FILE))); - assertThat(serverContext.getMdoRefs()).hasSize(2); - assertThat(serverContext.getDocumentsByMdoRef()).hasSize(1); - - assertThat(serverContext.getDocument(mdoRefCommonModule, ModuleType.CommonModule)).isNull(); + assertThat(serverContext.getDocument(mdoRefCommonModule, ModuleType.CommonModule)) + .isNotPresent(); } @Test From 02bed0b18996ea465494d07e847f8424d4a390a4 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Fri, 8 May 2020 11:42:00 +0300 Subject: [PATCH 273/444] CashedPublicDiagnostic --- docs/diagnostics/CachedPublic.md | 44 ++++++ docs/en/diagnostics/CachedPublic.md | 36 +++++ .../diagnostics/CachedPublicDiagnostic.java | 89 +++++++++++ .../CachedPublicDiagnostic_en.properties | 2 + .../CachedPublicDiagnostic_ru.properties | 2 + .../CachedPublicDiagnosticTest.java | 138 ++++++++++++++++++ .../diagnostics/CachedPublicDiagnostic.bsl | 23 +++ 7 files changed, 334 insertions(+) create mode 100644 docs/diagnostics/CachedPublic.md create mode 100644 docs/en/diagnostics/CachedPublic.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/CachedPublicDiagnostic.bsl diff --git a/docs/diagnostics/CachedPublic.md b/docs/diagnostics/CachedPublic.md new file mode 100644 index 00000000000..4d95b8fcb74 --- /dev/null +++ b/docs/diagnostics/CachedPublic.md @@ -0,0 +1,44 @@ +# Кеширование программного интерфейса (CachedPublic) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Дефект кода` | `BSL` | `Важный` | `Да` | `5` | `standard`
`design` | + + +## Описание диагностики + +Не следует создавать программный интерфейс в модулях с повторным использованием возвращаемых значений. + +3.6. Другой пример скрытия деталей реализации библиотеки от потребителя. +Допустим: в первой версии библиотеки потребителям предоставлялась экспортная функция общего модуля с повторным использованием +возвращаемых значений; Но в следующей версии библиотеки это проектное решение пересмотрено в пользу +«обычного» общего модуля, куда эта функция была перенесена (аналогично, если в обратную сторону). В данном примере, +для того чтобы избавить потребителя библиотеки от дополнительных усилий по замене вызовов «старой» функции на новую, +рекомендуется сразу размещать экспортную функцию в «обычном» модуле, в его разделе «программный интерфейс». Тогда эта +функция, в зависимости от текущего проектного решения, может вызывать служебную функцию из модуля с повторным +использованием возвращаемых значений или из любого другого модуля, или непосредственно сама содержать реализацию. +Однако для потребителя ее местоположение уже не будет меняться в следующих версиях библиотеки. + +## Примеры + + +## Источники + + +* Источник: [Стандарт: Обеспечение совместимости библиотек](https://its.1c.ru/db/v8std#content:644:hdoc:3.6) + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:CachedPublic-off +// BSLLS:CachedPublic-on +``` + +### Параметр конфигурационного файла + +```json +"CachedPublic": false +``` diff --git a/docs/en/diagnostics/CachedPublic.md b/docs/en/diagnostics/CachedPublic.md new file mode 100644 index 00000000000..5462c2d49a6 --- /dev/null +++ b/docs/en/diagnostics/CachedPublic.md @@ -0,0 +1,36 @@ +# Cached public methods (CachedPublic) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Code smell` | `BSL` | `Major` | `Yes` | `5` | `standard`
`design` | + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:CachedPublic-off +// BSLLS:CachedPublic-on +``` + +### Parameter for config + +```json +"CachedPublic": false +``` diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnostic.java new file mode 100644 index 00000000000..a93af83fa33 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnostic.java @@ -0,0 +1,89 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.Keywords; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; +import com.github._1c_syntax.mdclasses.metadata.additional.ReturnValueReuse; +import com.github._1c_syntax.utils.CaseInsensitivePattern; + +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.MAJOR, + scope = DiagnosticScope.BSL, + modules = { + ModuleType.CommonModule + }, + minutesToFix = 5, + tags = { + DiagnosticTag.STANDARD, + DiagnosticTag.DESIGN + } + +) +public class CachedPublicDiagnostic extends AbstractDiagnostic { + + private static final Pattern PUBLIC = CaseInsensitivePattern.compile( + String.format("^(%s|%s)$", Keywords.PUBLIC_REGION_RU, Keywords.PUBLIC_REGION_EN)); + + public CachedPublicDiagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + protected void check(DocumentContext documentContext) { + + if (!isCashed(documentContext)) { + return; + } + + documentContext.getSymbolTree().getModuleLevelRegions() + .stream() + .filter(regionSymbol -> PUBLIC.matcher(regionSymbol.getName()).find()) + .forEach(regionSymbol -> diagnosticStorage.addDiagnostic(regionSymbol.getRegionNameRange())); + } + + private boolean isCashed(DocumentContext documentContext) { + return documentContext.getMdObject() + .filter(CommonModule.class::isInstance) + .map(CommonModule.class::cast) + .map(CommonModule::getReturnValuesReuse) + .filter(this::isReuseValue) + .isPresent(); + } + + private Boolean isReuseValue(ReturnValueReuse value) { + return value == ReturnValueReuse.DURING_REQUEST + || value == ReturnValueReuse.DURING_SESSION; + } + +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnostic_en.properties new file mode 100644 index 00000000000..f35d1858669 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Move methods to private region +diagnosticName=Cached public methods diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnostic_ru.properties new file mode 100644 index 00000000000..1d265cf1bd1 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Переместите методы в Служебный Программный интерфейс +diagnosticName=Кеширование программного интерфейса \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnosticTest.java new file mode 100644 index 00000000000..d6864b85c3f --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnosticTest.java @@ -0,0 +1,138 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.ServerContext; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.mdclasses.metadata.additional.ReturnValueReuse; +import com.github._1c_syntax.utils.Absolute; +import lombok.SneakyThrows; +import org.apache.commons.io.FileUtils; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Optional; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +class CachedPublicDiagnosticTest extends AbstractDiagnosticTest { + CachedPublicDiagnosticTest() { + super(CachedPublicDiagnostic.class); + } + + private CommonModule module; + private DocumentContext documentContext; + + private static final String PATH_TO_METADATA = "src/test/resources/metadata"; + private static final String PATH_TO_MODULE_FILE = "src/test/resources/metadata/CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; + private static final String PATH_TO_MODULE_CONTENT = "src/test/resources/diagnostics/CachedPublicDiagnostic.bsl"; + + + @Test + void test() { + + getDocumentContextFromFile(); + + // given + when(module.getReturnValuesReuse()).thenReturn(ReturnValueReuse.DURING_REQUEST); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(2); + assertThat(diagnostics, true) + .hasRange(0, 9, 29) + .hasRange(16, 9, 15); + + } + @Test + void testSession() { + + getDocumentContextFromFile(); + + // given + when(module.getReturnValuesReuse()).thenReturn(ReturnValueReuse.DURING_SESSION); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(2); + assertThat(diagnostics, true) + .hasRange(0, 9, 29) + .hasRange(16, 9, 15); + + } + + + @Test + void testNegative() { + + getDocumentContextFromFile(); + + // given + when(module.getReturnValuesReuse()).thenReturn(ReturnValueReuse.DONT_USE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + + @SneakyThrows + void getDocumentContextFromFile() { + + Path path = Absolute.path(PATH_TO_METADATA); + Path moduleFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + Path testFile = Paths.get(PATH_TO_MODULE_CONTENT).toAbsolutePath(); + + + ServerContext serverContext = new ServerContext(path); + var configuration = serverContext.getConfiguration(); + documentContext = spy(new DocumentContext( + testFile.toUri(), + FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), + serverContext + )); + + + module = spy((CommonModule) configuration.getModulesByURI().get(moduleFile.toUri())); + + } +} diff --git a/src/test/resources/diagnostics/CachedPublicDiagnostic.bsl b/src/test/resources/diagnostics/CachedPublicDiagnostic.bsl new file mode 100644 index 00000000000..73c386a1bba --- /dev/null +++ b/src/test/resources/diagnostics/CachedPublicDiagnostic.bsl @@ -0,0 +1,23 @@ +#Область ПрограммныйИнтерфейс + +Процедура Метод1() + +КонецПроцедуры + +#КонецОбласти + +#Область СлужебныйПрограммныйИнтерфейс + +Процедура Метод1() + +КонецПроцедуры + +#КонецОбласти + +#Область public + +Процедура Метод1() + +КонецПроцедуры + +#КонецОбласти From 5dcb91b7aad10c87019763a70fc0a5493d55f8b9 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Fri, 8 May 2020 11:43:40 +0300 Subject: [PATCH 274/444] precommit --- docs/diagnostics/index.md | 5 +++-- docs/en/diagnostics/index.md | 5 +++-- .../configuration/parameters-schema.json | 10 ++++++++++ .../bsl/languageserver/configuration/schema.json | 3 +++ 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index bced0c76ef5..df5706650b9 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,9 +8,9 @@ ## Список реализованных диагностик -Общее количество: **105** +Общее количество: **106** -* Дефект кода: **67** +* Дефект кода: **68** * Уязвимость: **2** * Ошибка: **33** * Потенциальная уязвимость: **3** @@ -18,6 +18,7 @@ | Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги | | --- | --- | :-: | --- | --- | --- | | [BeginTransactionBeforeTryCatch](BeginTransactionBeforeTryCatch.md) | Нарушение правил работы с транзакциями для метода 'НачатьТранзакцию' | Да | Важный | Ошибка | `standard` | +| [CachedPublic](CachedPublic.md) | Кеширование программного интерфейса | Да | Важный | Дефект кода | `standard`
`design` | | [CanonicalSpellingKeywords](CanonicalSpellingKeywords.md) | Каноническое написание ключевых слов | Да | Информационный | Дефект кода | `standard` | | [CodeBlockBeforeSub](CodeBlockBeforeSub.md) | Определения методов должны размещаться перед операторами тела модуля | Да | Блокирующий | Ошибка | `error` | | [CodeOutOfRegion](CodeOutOfRegion.md) | Код расположен вне области | Да | Информационный | Дефект кода | `standard` | diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index c712c1ff135..e0c9cb13820 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,16 +8,17 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **105** +Total: **106** * Error: **33** -* Code smell: **67** +* Code smell: **68** * Vulnerability: **2** * Security Hotspot: **3** | Key | Name| Enabled by default | Severity | Type | Tags | | --- | --- | :-: | --- | --- | --- | | [BeginTransactionBeforeTryCatch](BeginTransactionBeforeTryCatch.md) | Violating transaction rules for the 'BeginTransaction' method | Yes | Major | Error | `standard` | +| [CachedPublic](CachedPublic.md) | Cached public methods | Yes | Major | Code smell | `standard`
`design` | | [CanonicalSpellingKeywords](CanonicalSpellingKeywords.md) | Canonical keyword writing | Yes | Info | Code smell | `standard` | | [CodeBlockBeforeSub](CodeBlockBeforeSub.md) | Method definitions must be placed before the module body operators | Yes | Blocker | Error | `error` | | [CodeOutOfRegion](CodeOutOfRegion.md) | Code out of region | Yes | Info | Code smell | `standard` | diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index f50dee385b4..9fc7822f6e4 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -14,6 +14,16 @@ "title": "Violating transaction rules for the 'BeginTransaction' method", "$id": "#/definitions/BeginTransactionBeforeTryCatch" }, + "CachedPublic": { + "description": "Cached public methods", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Cached public methods", + "$id": "#/definitions/CachedPublic" + }, "CanonicalSpellingKeywords": { "description": "Canonical keyword writing", "default": true, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index d89278f4b78..ca19c891e6f 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -26,6 +26,9 @@ "BeginTransactionBeforeTryCatch": { "$ref": "parameters-schema.json#/definitions/BeginTransactionBeforeTryCatch" }, + "CachedPublic": { + "$ref": "parameters-schema.json#/definitions/CachedPublic" + }, "CanonicalSpellingKeywords": { "$ref": "parameters-schema.json#/definitions/CanonicalSpellingKeywords" }, From 5982cb3309ec2d22d2e97f2cd4a3e36615d80035 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Fri, 8 May 2020 12:07:19 +0300 Subject: [PATCH 275/444] =?UTF-8?q?=D0=BD=D0=BE=D0=B2=D1=8B=D0=B9=20=D1=88?= =?UTF-8?q?=D0=B0=D0=B1=D0=BB=D0=BE=D0=BD=20=D0=B4=D0=BB=D1=8F=20=D0=B4?= =?UTF-8?q?=D0=B5=D1=81=D1=82=D0=B2=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/ISSUE_TEMPLATE/NewCodeAction.md | 30 +++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/NewCodeAction.md diff --git a/.github/ISSUE_TEMPLATE/NewCodeAction.md b/.github/ISSUE_TEMPLATE/NewCodeAction.md new file mode 100644 index 00000000000..26e073f42a2 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/NewCodeAction.md @@ -0,0 +1,30 @@ +--- +name: Новое действие +about: Добавление нового действия (CodeAction) +title: '[NEW]' +labels: component/codeAction +assignees: '' + +--- + +## Описание назначения, идеи + + +## Тип действия (смысловая составляющая) + + +* [ ] :syringe: Исправление ошибки (`QuickFix`) +* [ ] :scissors: Рефакторинг кода (`Refactor`) +* [ ] :memo: Шаблон кода (`Template`, `Snippet`) +* [ ] :mushroom: Другое + +## Область применения (привязка создаваемого действия) + + +* [ ] :interrobang: Замечание диагностики +* [ ] :bookmark_tabs: Выделенный пользователем блок кода +* [ ] :book: Действие над файлом +* [ ] :ghost: Другое + +## Дополнительная информация + From 687f2e7b8ce60c2064cd679a4545808b58b16d8e Mon Sep 17 00:00:00 2001 From: Evgeniy Vanzhula Date: Mon, 11 May 2020 12:08:16 +0300 Subject: [PATCH 276/444] Update gh-pages.yml --- .github/workflows/gh-pages.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index cff66cc8e24..26f54b6cfd3 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -35,7 +35,7 @@ jobs: - name: Install dependencies run: | pip install --upgrade pip - pip install mkdocs mkdocs-material pygments-bsl + pip install mkdocs mkdocs-material==5.0.0 pygments-bsl - name: Dowload latest GitHub Pages run: | From 9d0a90144559ad84e5e3535cb969e29016937bef Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Mon, 11 May 2020 22:13:06 +0300 Subject: [PATCH 277/444] Update benchmark.yml --- .github/workflows/benchmark.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index 5002e68c47e..1c2cd4369fb 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -9,7 +9,7 @@ on: jobs: Benchmark: - runs-on: ubuntu-latest + runs-on: self-hosted steps: - name: Checkout project uses: actions/checkout@v2 From 4652afce27b5a28e217af2137f58e3ffe88d9275 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Mon, 11 May 2020 22:26:45 +0300 Subject: [PATCH 278/444] =?UTF-8?q?=D0=91=D0=B0=D0=BC=D0=BF=20=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D1=81=D0=B8=D0=B8=20python=20install?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/benchmark.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index 1c2cd4369fb..c0538220160 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -23,7 +23,7 @@ jobs: run: ./gradlew jar - name: Set up Python - uses: actions/setup-python@v1 + uses: actions/setup-python@v2 with: python-version: "3.7" From 075b484e613eb117468b8cae44913d531569f427 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Mon, 11 May 2020 23:44:04 +0300 Subject: [PATCH 279/444] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BF=D0=BE=D0=B2=D0=B5=D0=B4?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D1=8F=20EXCEPT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Вне зависимости от включения/выключения диагностики, если mode = except, диагностика должна исключаться --- .../languageserver/diagnostics/DiagnosticSupplier.java | 5 ++++- .../diagnostics/DiagnosticSupplierTest.java | 8 ++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java index 02058ea6ce1..d494f1a3e2b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplier.java @@ -142,11 +142,14 @@ private boolean isEnabled(DiagnosticInfo diagnosticInfo, DiagnosticsOptions diag boolean enabledDirectly = diagnosticConfiguration != null && diagnosticConfiguration.isLeft() && diagnosticConfiguration.getLeft(); + boolean disabledDirectly = diagnosticConfiguration != null + && diagnosticConfiguration.isLeft() + && !diagnosticConfiguration.getLeft(); boolean hasDefinedSetting = enabledDirectly || hasCustomConfiguration; boolean passedAllMode = mode == Mode.ALL; boolean passedOnlyMode = mode == Mode.ONLY && hasDefinedSetting; - boolean passedExcept = mode == Mode.EXCEPT && !hasDefinedSetting; + boolean passedExcept = mode == Mode.EXCEPT && !(hasDefinedSetting || disabledDirectly); boolean passedOn = mode == Mode.ON && (activatedByDefault || hasDefinedSetting); return passedOn diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java index ab3dc740032..8d2233ac458 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticSupplierTest.java @@ -368,16 +368,16 @@ void testDiagnosticModeOnly() { // when lsConfiguration.getDiagnosticsOptions().setMode(Mode.ONLY); Map>> rules = new HashMap<>(); - rules.put("Typo", Either.forLeft(true)); + rules.put("Typo", Either.forLeft(false)); rules.put("TooManyReturns", Either.forLeft(true)); lsConfiguration.getDiagnosticsOptions().setParameters(rules); List diagnostics = diagnosticSupplier.getDiagnosticInstances(documentContext); assertThat(diagnostics) - .hasSize(2) + .hasSize(1) .flatExtracting(Object::getClass) - .contains(TypoDiagnostic.class) + .doesNotContain(TypoDiagnostic.class) .contains(TooManyReturnsDiagnostic.class) ; } @@ -392,7 +392,7 @@ void testDiagnosticModeExcept() { // when lsConfiguration.getDiagnosticsOptions().setMode(Mode.EXCEPT); Map>> rules = new HashMap<>(); - rules.put("Typo", Either.forLeft(true)); + rules.put("Typo", Either.forLeft(false)); rules.put("TooManyReturns", Either.forLeft(true)); lsConfiguration.getDiagnosticsOptions().setParameters(rules); From d9982a5c42aa2ce2bb4cdda706bb351fa739f5fd Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Wed, 6 May 2020 17:57:13 +0300 Subject: [PATCH 280/444] =?UTF-8?q?=D0=9A=D0=BE=D0=BD=D1=86=D0=B5=D0=BF?= =?UTF-8?q?=D1=82=20=D0=B4=D0=B2=D0=BE=D0=B9=D0=BD=D0=BE=D0=B3=D0=BE=20?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D1=85=D0=BE=D0=B4=D0=B0=20=D1=81=20=D1=81?= =?UTF-8?q?=D0=BE=D1=85=D1=80=D0=B0=D0=BD=D0=B5=D0=BD=D0=B8=D0=B5=D0=BC=20?= =?UTF-8?q?=D1=81=D0=B8=D0=BC=D0=B2=D0=BE=D0=BB=D1=8C=D0=BD=D0=BE=D0=B3?= =?UTF-8?q?=D0=BE=20=D0=B4=D0=B5=D1=80=D0=B5=D0=B2=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../languageserver/cli/AnalyzeCommand.java | 5 +++++ .../context/DocumentContext.java | 10 +++------- .../languageserver/context/ServerContext.java | 19 +++++++++++++++++++ 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java index b4ca21035e2..49df60e3acd 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java @@ -165,6 +165,11 @@ public Integer call() { Collection files = FileUtils.listFiles(srcDir.toFile(), new String[]{"bsl", "os"}, true); + if (!silentMode) { + System.out.println("Populating context..."); + } + context.populateContext(files); + List fileInfos; if (silentMode) { fileInfos = files.parallelStream() diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java index f0491ddfa1e..b5a3027834a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java @@ -195,13 +195,14 @@ public Optional getMdObject() { public void rebuild(String content) { computeLock.lock(); - clear(); + clearSecondaryData(); this.content = content; tokenizer = new Tokenizer(content); computeLock.unlock(); } public void clearSecondaryData() { + computeLock.lock(); content = null; contentList.clear(); tokenizer = null; @@ -210,12 +211,7 @@ public void clearSecondaryData() { cyclomaticComplexityData.clear(); metrics.clear(); diagnosticIgnoranceData.clear(); - } - - private void clear() { - clearSecondaryData(); - - symbolTree.clear(); + computeLock.unlock(); } private static FileType computeFileType(URI uri) { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java index d4b62c01410..e96364fec06 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java @@ -24,11 +24,16 @@ import com.github._1c_syntax.mdclasses.metadata.Configuration; import com.github._1c_syntax.utils.Absolute; import com.github._1c_syntax.utils.Lazy; +import lombok.SneakyThrows; +import org.apache.commons.io.FileUtils; import org.eclipse.lsp4j.TextDocumentItem; import javax.annotation.CheckForNull; +import java.io.File; import java.net.URI; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -47,6 +52,14 @@ public ServerContext(@CheckForNull Path configurationRoot) { this.configurationRoot = configurationRoot; } + public void populateContext(Collection uris) { + uris.parallelStream().forEach(file -> { + DocumentContext documentContext = addDocument(file); + documentContext.getSymbolTree(); + documentContext.clearSecondaryData(); + }); + } + public Map getDocuments() { return Collections.unmodifiableMap(documents); } @@ -61,6 +74,12 @@ public DocumentContext getDocument(URI uri) { return documents.get(Absolute.uri(uri)); } + @SneakyThrows + public DocumentContext addDocument(File file) { + String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8); + return addDocument(file.toURI(), content); + } + public DocumentContext addDocument(URI uri, String content) { URI absoluteURI = Absolute.uri(uri); From 3417329c90e488925f384f970ac7106098e342f9 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Fri, 8 May 2020 17:55:47 +0300 Subject: [PATCH 281/444] =?UTF-8?q?=D0=92=D0=BE=D0=B7=D0=BC=D0=BE=D0=B6?= =?UTF-8?q?=D0=BD=D0=BE=D1=81=D1=82=D1=8C=20=D0=BD=D0=B0=D0=BF=D0=BE=D0=BB?= =?UTF-8?q?=D0=BD=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BA=D0=BE=D0=BD=D1=82=D0=B5?= =?UTF-8?q?=D0=BA=D1=81=D1=82=D0=B0=20=D0=BD=D0=B0=20=D0=B1=D0=B0=D0=B7?= =?UTF-8?q?=D0=B5=20=D0=BA=D0=BE=D1=80=D0=BD=D1=8F=20=D0=BA=D0=BE=D0=BD?= =?UTF-8?q?=D1=84=D0=B8=D0=B3=D1=83=D1=80=D0=B0=D1=86=D0=B8=D0=B8=20=D0=B8?= =?UTF-8?q?=20=D1=84=D0=B0=D0=B9=D0=BB=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../bsl/languageserver/BSLLanguageServer.java | 1 + .../languageserver/cli/AnalyzeCommand.java | 5 +-- .../languageserver/context/ServerContext.java | 31 ++++++++++++++++--- 3 files changed, 29 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServer.java index 06980c45f30..e5f55c6a1ae 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServer.java @@ -68,6 +68,7 @@ public BSLLanguageServer() { public CompletableFuture initialize(InitializeParams params) { setConfigurationRoot(params); + CompletableFuture.runAsync(context::populateContext); ServerCapabilities capabilities = new ServerCapabilities(); capabilities.setTextDocumentSync(TextDocumentSyncKind.Full); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java index 49df60e3acd..7ae3e76077c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java @@ -164,10 +164,7 @@ public Integer call() { diagnosticProvider = new DiagnosticProvider(diagnosticSupplier); Collection files = FileUtils.listFiles(srcDir.toFile(), new String[]{"bsl", "os"}, true); - - if (!silentMode) { - System.out.println("Populating context..."); - } + context.populateContext(files); List fileInfos; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java index e96364fec06..a7e5c638460 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java @@ -25,6 +25,7 @@ import com.github._1c_syntax.utils.Absolute; import com.github._1c_syntax.utils.Lazy; import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.eclipse.lsp4j.TextDocumentItem; @@ -38,6 +39,7 @@ import java.util.HashMap; import java.util.Map; +@Slf4j public class ServerContext { private final Map documents = Collections.synchronizedMap(new HashMap<>()); private final Lazy configurationMetadata = new Lazy<>(this::computeConfigurationMetadata); @@ -52,12 +54,33 @@ public ServerContext(@CheckForNull Path configurationRoot) { this.configurationRoot = configurationRoot; } + public void populateContext() { + if (configurationRoot == null) { + LOGGER.info("Can't populate server context. Configuration root is not defined."); + return; + } + LOGGER.info("Finding files to populate context..."); + Collection files = FileUtils.listFiles( + configurationRoot.toFile(), + new String[]{"bsl", "os"}, + true + ); + populateContext(files); + } + public void populateContext(Collection uris) { - uris.parallelStream().forEach(file -> { - DocumentContext documentContext = addDocument(file); - documentContext.getSymbolTree(); - documentContext.clearSecondaryData(); + LOGGER.info("Populating context..."); + + uris.parallelStream().forEach((File file) -> { + DocumentContext documentContext = getDocument(file.toURI()); + if (documentContext == null) { + documentContext = addDocument(file); + documentContext.getSymbolTree(); + documentContext.clearSecondaryData(); + } }); + + LOGGER.info("Context populated."); } public Map getDocuments() { From df1667dbd23121d45c40e7ec3c8109d0bf5b22a6 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Mon, 11 May 2020 23:12:02 +0300 Subject: [PATCH 282/444] =?UTF-8?q?=D0=92=D1=8B=D0=B2=D0=BE=D0=B4=20=D0=B8?= =?UTF-8?q?=D0=BD=D1=84=D0=BE=D1=80=D0=BC=D0=B0=D1=86=D0=B8=D0=B8=20=D0=B2?= =?UTF-8?q?=20debug=20=D1=80=D0=B5=D0=B6=D0=B8=D0=BC=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../bsl/languageserver/context/ServerContext.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java index a7e5c638460..cc0a676ae67 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java @@ -59,7 +59,7 @@ public void populateContext() { LOGGER.info("Can't populate server context. Configuration root is not defined."); return; } - LOGGER.info("Finding files to populate context..."); + LOGGER.debug("Finding files to populate context..."); Collection files = FileUtils.listFiles( configurationRoot.toFile(), new String[]{"bsl", "os"}, @@ -69,7 +69,7 @@ public void populateContext() { } public void populateContext(Collection uris) { - LOGGER.info("Populating context..."); + LOGGER.debug("Populating context..."); uris.parallelStream().forEach((File file) -> { DocumentContext documentContext = getDocument(file.toURI()); @@ -80,7 +80,7 @@ public void populateContext(Collection uris) { } }); - LOGGER.info("Context populated."); + LOGGER.debug("Context populated."); } public Map getDocuments() { From fd60a4dfe5fe1f8b36e130141777e19a4858c32e Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Tue, 12 May 2020 00:16:34 +0300 Subject: [PATCH 283/444] =?UTF-8?q?=D0=A2=D0=B5=D1=81=D1=82=20=D0=BD=D0=B0?= =?UTF-8?q?=20populate=20context?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../languageserver/context/ServerContextTest.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java index 515eb9aa948..f8995581aec 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java @@ -74,4 +74,19 @@ void testErrorConfigurationMetadata() { assertThat(configurationMetadata.getModulesByType()).hasSize(0); } + @Test + void testPopulateContext() { + // given + Path path = Absolute.path(PATH_TO_METADATA); + ServerContext serverContext = new ServerContext(path); + + assertThat(serverContext.getDocuments()).hasSize(0); + + // when + serverContext.populateContext(); + + // then + assertThat(serverContext.getDocuments()).hasSizeGreaterThan(0); + } + } From 8c520b3d379da66b4353795340877722703822f5 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Tue, 12 May 2020 10:06:31 +0300 Subject: [PATCH 284/444] =?UTF-8?q?SemicolonPresence=20=D0=BF=D1=80=D0=BE?= =?UTF-8?q?=D0=B2=D0=B5=D1=80=D0=BA=D0=B0=20=D0=BD=D0=B0=20=D1=80=D0=B0?= =?UTF-8?q?=D0=B7=D0=B1=D0=BE=D1=80=20=D0=BF=D0=B5=D1=80=D0=B5=D0=BD=D0=B5?= =?UTF-8?q?=D1=81=D0=B5=D0=BD=D0=B0=20=D0=B2=D0=BD=D1=83=D1=82=D1=80=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/SemicolonPresenceDiagnostic.java | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SemicolonPresenceDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SemicolonPresenceDiagnostic.java index 40701fafcf1..1908184fc5b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SemicolonPresenceDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SemicolonPresenceDiagnostic.java @@ -30,7 +30,6 @@ import com.github._1c_syntax.bsl.languageserver.providers.CodeActionProvider; import com.github._1c_syntax.bsl.languageserver.utils.Trees; import com.github._1c_syntax.bsl.parser.BSLParser; -import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.ParseTree; import org.eclipse.lsp4j.CodeAction; import org.eclipse.lsp4j.CodeActionParams; @@ -60,15 +59,15 @@ public SemicolonPresenceDiagnostic(DiagnosticInfo info) { @Override public ParseTree visitStatement(BSLParser.StatementContext ctx) { - if (Trees.treeContainsErrors(ctx)) { - return ctx; - } + if (ctx.preprocessor() == null + && ctx.SEMICOLON() == null + && ctx.getStop() != null) { - if (ctx.preprocessor() == null && ctx.SEMICOLON() == null) { - Token lastToken = ctx.getStop(); - if (lastToken != null) { - diagnosticStorage.addDiagnostic(lastToken); + if (Trees.treeContainsErrors(ctx)) { + return ctx; } + + diagnosticStorage.addDiagnostic(ctx.getStop()); } return super.visitStatement(ctx); } From a66c02fc57815706dfe3346d067ceda9a9703609 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Tue, 12 May 2020 11:30:10 +0300 Subject: [PATCH 285/444] =?UTF-8?q?FunctionShouldHaveReturn=20=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D0=BD=D0=BE=D1=81=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D0=BA=D0=B8=20=D1=80=D0=B0=D0=B7=D0=B1=D0=BE=D1=80=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/FunctionShouldHaveReturnDiagnostic.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionShouldHaveReturnDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionShouldHaveReturnDiagnostic.java index 2b462c98ece..24ab0bbf3f1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionShouldHaveReturnDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionShouldHaveReturnDiagnostic.java @@ -51,13 +51,12 @@ public FunctionShouldHaveReturnDiagnostic(DiagnosticInfo info) { @Override public ParseTree visitFunction(BSLParser.FunctionContext ctx) { - if (ctx.ENDFUNCTION_KEYWORD() == null - || Trees.treeContainsErrors(ctx)) { + if (ctx.ENDFUNCTION_KEYWORD() == null) { return ctx; } Collection tokens = Trees.findAllTokenNodes(ctx, BSLLexer.RETURN_KEYWORD); - if (tokens.isEmpty()) { + if (tokens.isEmpty() && !Trees.treeContainsErrors(ctx)) { BSLParser.SubNameContext subName = ctx.funcDeclaration().subName(); diagnosticStorage.addDiagnostic(subName); } From 88c042e12979e2167e70863046aa12b7ae202c38 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Tue, 12 May 2020 18:25:20 +0300 Subject: [PATCH 286/444] docs link fix --- docs/diagnostics/CompilationDirectiveNeedLess.md | 2 +- docs/en/diagnostics/CompilationDirectiveNeedLess.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/diagnostics/CompilationDirectiveNeedLess.md b/docs/diagnostics/CompilationDirectiveNeedLess.md index c976e86427b..e56511559d1 100644 --- a/docs/diagnostics/CompilationDirectiveNeedLess.md +++ b/docs/diagnostics/CompilationDirectiveNeedLess.md @@ -23,7 +23,7 @@ процедуры (функции) доступны в конечном итоге. ## Источники -* Источник: [Использование директив компиляции и инструкций препроцессора](https://its.1c.ru/db/v8std#content:453:hdoc) +* Источник: [Использование директив компиляции и инструкций препроцессора](https://its.1c.ru/db/v8std#content:439:hdoc) ## Сниппеты diff --git a/docs/en/diagnostics/CompilationDirectiveNeedLess.md b/docs/en/diagnostics/CompilationDirectiveNeedLess.md index 56ab7a91555..4a8b04fd05d 100644 --- a/docs/en/diagnostics/CompilationDirectiveNeedLess.md +++ b/docs/en/diagnostics/CompilationDirectiveNeedLess.md @@ -21,7 +21,7 @@ In server or client common modules, the execution context is obvious, so there i ## Sources -- Source: [The use of compilation directives and preprocessor instructions(RUS)](https://its.1c.ru/db/v8std#content:453:hdoc) +- Source: [The use of compilation directives and preprocessor instructions(RUS)](https://its.1c.ru/db/v8std#content:439:hdoc) ## Snippets From 508dff7f3684fa0f20951b409b78c83880b15a92 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Tue, 12 May 2020 21:28:50 +0300 Subject: [PATCH 287/444] MethodSize miniopt --- .../bsl/languageserver/diagnostics/MethodSizeDiagnostic.java | 2 +- src/test/resources/diagnostics/MethodSizeDiagnostic.bsl | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MethodSizeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MethodSizeDiagnostic.java index 9077a80aafa..3678287b87d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MethodSizeDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MethodSizeDiagnostic.java @@ -84,7 +84,7 @@ private boolean methodSizeExceedsLimit(int methodSize) { } private static int methodSize(BSLParser.SubCodeBlockContext ctx) { - if (ctx.getTokens().isEmpty()) { + if (ctx.codeBlock().getChildCount() == 0) { return 0; } Token start = ctx.getStart(); diff --git a/src/test/resources/diagnostics/MethodSizeDiagnostic.bsl b/src/test/resources/diagnostics/MethodSizeDiagnostic.bsl index 6d21547fbf3..073b4ce4f91 100644 --- a/src/test/resources/diagnostics/MethodSizeDiagnostic.bsl +++ b/src/test/resources/diagnostics/MethodSizeDiagnostic.bsl @@ -829,3 +829,7 @@ А = 0; КонецФункции + +Функция А(А=0) + +КонецФункции From 6af0f549375c6e915b0229e1b2dd94d6d22500f7 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Wed, 13 May 2020 07:02:43 +0300 Subject: [PATCH 288/444] CommonModuleNameWordsDiagnostic --- docs/diagnostics/CommonModuleNameWords.md | 41 +++++++ docs/diagnostics/index.md | 5 +- docs/en/diagnostics/CommonModuleNameWords.md | 44 +++++++ docs/en/diagnostics/index.md | 5 +- .../AbstractCommonModuleNameDiagnostic.java | 14 ++- .../CommonModuleNameWordsDiagnostic.java | 73 ++++++++++++ .../configuration/parameters-schema.json | 18 +++ .../languageserver/configuration/schema.json | 3 + ...monModuleNameWordsDiagnostic_en.properties | 3 + ...monModuleNameWordsDiagnostic_ru.properties | 3 + .../CommonModuleNameWordsDiagnosticTest.java | 111 ++++++++++++++++++ .../CommonModuleNameWordsDiagnostic.bsl | 1 + 12 files changed, 314 insertions(+), 7 deletions(-) create mode 100644 docs/diagnostics/CommonModuleNameWords.md create mode 100644 docs/en/diagnostics/CommonModuleNameWords.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/CommonModuleNameWordsDiagnostic.bsl diff --git a/docs/diagnostics/CommonModuleNameWords.md b/docs/diagnostics/CommonModuleNameWords.md new file mode 100644 index 00000000000..c533bdb6c7a --- /dev/null +++ b/docs/diagnostics/CommonModuleNameWords.md @@ -0,0 +1,41 @@ +# Нерекомендуемое имя общего модуля (CommonModuleNameWords) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Дефект кода` | `BSL`
`OS` | `Информационный` | `Да` | `1` | `standard` | + +## Параметры + +| Имя | Тип | Описание | Значение по умолчанию | +| :-: | :-: | :-- | :-: | +| `words` | `Строка` | ```Нерекомендуемые слова``` | `````` | + + +## Описание диагностики +Рекомендуется избегать в названии общего модуля таких общих слов как "Процедуры", "Функции", "Обработчики", + "Модуль", "Функциональность" и т.п. + +## Примеры + + +## Источники + +* Источник: [Стандарт: Правила создания общих модулей](https://its.1c.ru/db/v8std#content:469:hdoc:3.1) + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:CommonModuleNameWords-off +// BSLLS:CommonModuleNameWords-on +``` + +### Параметр конфигурационного файла + +```json +"CommonModuleNameWords": { + "words": "" +} +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index df5706650b9..ad208c20421 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,9 +8,9 @@ ## Список реализованных диагностик -Общее количество: **106** +Общее количество: **107** -* Дефект кода: **68** +* Дефект кода: **69** * Уязвимость: **2** * Ошибка: **33** * Потенциальная уязвимость: **3** @@ -33,6 +33,7 @@ | [CommonModuleNameGlobal](CommonModuleNameGlobal.md) | Пропущен постфикс "Глобальный" | Да | Важный | Дефект кода | `standard`
`badpractice`
`brainoverload` | | [CommonModuleNameGlobalClient](CommonModuleNameGlobalClient.md) | Глобальный модуль с постфиксом "Клиент" | Да | Важный | Дефект кода | `standard` | | [CommonModuleNameServerCall](CommonModuleNameServerCall.md) | Пропущен постфикс "ВызовСервера" | Да | Незначительный | Дефект кода | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameWords](CommonModuleNameWords.md) | Нерекомендуемое имя общего модуля | Да | Информационный | Дефект кода | `standard` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Директивы компиляции методов | Да | Важный | Дефект кода | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Лишняя директива компиляции | Да | Важный | Дефект кода | `clumsy`
`standard`
`unpredictable` | | [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Подряд идущие пустые строки | Да | Информационный | Дефект кода | `badpractice` | diff --git a/docs/en/diagnostics/CommonModuleNameWords.md b/docs/en/diagnostics/CommonModuleNameWords.md new file mode 100644 index 00000000000..53f911011d0 --- /dev/null +++ b/docs/en/diagnostics/CommonModuleNameWords.md @@ -0,0 +1,44 @@ +# Unrecommended common module name (CommonModuleNameWords) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Code smell` | `BSL`
`OS` | `Info` | `Yes` | `1` | `standard` | + +## Parameters + +| Name | Type | Description | Default value | +| :-: | :-: | :-- | :-: | +| `words` | `String` | ```Unrecommended words``` | `````` | + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:CommonModuleNameWords-off +// BSLLS:CommonModuleNameWords-on +``` + +### Parameter for config + +```json +"CommonModuleNameWords": { + "words": "" +} +``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index e0c9cb13820..1ab3ba79e4e 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,10 +8,10 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **106** +Total: **107** * Error: **33** -* Code smell: **68** +* Code smell: **69** * Vulnerability: **2** * Security Hotspot: **3** @@ -33,6 +33,7 @@ Total: **106** | [CommonModuleNameGlobal](CommonModuleNameGlobal.md) | Missed postfix "Global" | Yes | Major | Code smell | `standard`
`badpractice`
`brainoverload` | | [CommonModuleNameGlobalClient](CommonModuleNameGlobalClient.md) | Global module with postfix "Client" | Yes | Major | Code smell | `standard` | | [CommonModuleNameServerCall](CommonModuleNameServerCall.md) | Missed postfix "ServerCall" | Yes | Minor | Code smell | `standard`
`badpractice`
`unpredictable` | +| [CommonModuleNameWords](CommonModuleNameWords.md) | Unrecommended common module name | Yes | Info | Code smell | `standard` | | [CompilationDirectiveLost](CompilationDirectiveLost.md) | Methods compilation directive | Yes | Major | Code smell | `standard`
`unpredictable` | | [CompilationDirectiveNeedLess](CompilationDirectiveNeedLess.md) | Needless compilation directive | Yes | Major | Code smell | `clumsy`
`standard`
`unpredictable` | | [ConsecutiveEmptyLines](ConsecutiveEmptyLines.md) | Consecutive empty lines | Yes | Info | Code smell | `badpractice` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java index 3b54681df91..f6097d7fda2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java @@ -27,13 +27,17 @@ import com.github._1c_syntax.mdclasses.mdo.MDObjectBase; import com.github._1c_syntax.utils.CaseInsensitivePattern; -import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; abstract class AbstractCommonModuleNameDiagnostic extends AbstractDiagnostic { - private final Pattern pattern; + protected Pattern pattern; + + public AbstractCommonModuleNameDiagnostic(DiagnosticInfo info) { + super(info); + + } public AbstractCommonModuleNameDiagnostic(DiagnosticInfo info, String regexp) { super(info); @@ -54,10 +58,14 @@ protected void check(DocumentContext documentContext) { .filter(this::flagsCheck) .map(MDObjectBase::getName) .map(pattern::matcher) - .filter(Predicate.not(Matcher::find)) + .filter(this::matchCheck) .ifPresent(commonModule -> diagnosticStorage.addDiagnostic(documentContext.getTokensFromDefaultChannel().get(0))); } protected abstract boolean flagsCheck(CommonModule commonModule); + protected boolean matchCheck(Matcher matcher) { + return !matcher.find(); + } + } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic.java new file mode 100644 index 00000000000..405ff32ec55 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic.java @@ -0,0 +1,73 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticParameter; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.utils.CaseInsensitivePattern; + +import java.util.regex.Matcher; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.INFO, + minutesToFix = 5, + tags = { + DiagnosticTag.STANDARD + } + +) +public class CommonModuleNameWordsDiagnostic extends AbstractCommonModuleNameDiagnostic { + + private static final String DEFAULT_WORDS = "процедуры|procedures" + + "|функции|functions" + + "|обработчики|handlers" + + "|модуль|module" + + "|функциональность|functionality"; + + @DiagnosticParameter( + type = String.class + ) + private String words = DEFAULT_WORDS; + + public CommonModuleNameWordsDiagnostic(DiagnosticInfo info) { + super(info); + pattern = CaseInsensitivePattern.compile(words); + } + + @Override + protected boolean flagsCheck(CommonModule commonModule) { + return true; + } + + @Override + protected boolean matchCheck(Matcher matcher) { + return matcher.find(); + } + +} + diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index 9fc7822f6e4..f54eec0b8d4 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -186,6 +186,24 @@ "title": "Missed postfix \"ServerCall\"", "$id": "#/definitions/CommonModuleNameServerCall" }, + "CommonModuleNameWords": { + "description": "Unrecommended common module name", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Unrecommended common module name", + "properties": { + "words": { + "description": "Unrecommended words", + "default": "", + "type": "string", + "title": "Unrecommended words" + } + }, + "$id": "#/definitions/CommonModuleNameWords" + }, "CompilationDirectiveLost": { "description": "Methods compilation directive", "default": true, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index ca19c891e6f..f6fdce501e1 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -71,6 +71,9 @@ "CommonModuleNameServerCall": { "$ref": "parameters-schema.json#/definitions/CommonModuleNameServerCall" }, + "CommonModuleNameWords": { + "$ref": "parameters-schema.json#/definitions/CommonModuleNameWords" + }, "CompilationDirectiveLost": { "$ref": "parameters-schema.json#/definitions/CompilationDirectiveLost" }, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic_en.properties new file mode 100644 index 00000000000..5180bc94488 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic_en.properties @@ -0,0 +1,3 @@ +diagnosticMessage=Rename common module +diagnosticName=Unrecommended common module name +words=Unrecommended words \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic_ru.properties new file mode 100644 index 00000000000..b034196d17b --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic_ru.properties @@ -0,0 +1,3 @@ +diagnosticMessage=Переименуйте общий модуль +diagnosticName=Нерекомендуемое имя общего модуля +words=Нерекомендуемые слова diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnosticTest.java new file mode 100644 index 00000000000..6e8867e6281 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnosticTest.java @@ -0,0 +1,111 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.ServerContext; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.utils.Absolute; +import lombok.SneakyThrows; +import org.apache.commons.io.FileUtils; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Optional; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +class CommonModuleNameWordsDiagnosticTest extends AbstractDiagnosticTest { + + private CommonModule module; + private DocumentContext documentContext; + + CommonModuleNameWordsDiagnosticTest() { + super(CommonModuleNameWordsDiagnostic.class); + } + + private static final String PATH_TO_METADATA = "src/test/resources/metadata"; + private static final String PATH_TO_MODULE_FILE = "src/test/resources/metadata/CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; + + @Test + void test() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("СвойМодуль"); + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(5, 0, 1); + + } + + @Test + void testNegative() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("имя"); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @SneakyThrows + void getDocumentContextFromFile() { + + Path path = Absolute.path(PATH_TO_METADATA); + Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + + ServerContext serverContext = new ServerContext(path); + var configuration = serverContext.getConfiguration(); + documentContext = spy(new DocumentContext( + testFile.toUri(), + FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), + serverContext + )); + + + module = spy((CommonModule) configuration.getModulesByURI().get(documentContext.getUri())); + + } +} + diff --git a/src/test/resources/diagnostics/CommonModuleNameWordsDiagnostic.bsl b/src/test/resources/diagnostics/CommonModuleNameWordsDiagnostic.bsl new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/src/test/resources/diagnostics/CommonModuleNameWordsDiagnostic.bsl @@ -0,0 +1 @@ + From d8cae63025813614ac0c2ec550a7de5f16f7fdfd Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Wed, 13 May 2020 11:59:29 +0300 Subject: [PATCH 289/444] CommonModuleNameWords configure --- docs/en/diagnostics/CommonModuleNameWords.md | 2 +- .../AbstractCommonModuleNameDiagnostic.java | 7 ------ .../CommonModuleNameWordsDiagnostic.java | 14 ++++++++++- .../CommonModuleNameWordsDiagnosticTest.java | 25 +++++++++++++++++++ 4 files changed, 39 insertions(+), 9 deletions(-) diff --git a/docs/en/diagnostics/CommonModuleNameWords.md b/docs/en/diagnostics/CommonModuleNameWords.md index 53f911011d0..c7eb16dc71f 100644 --- a/docs/en/diagnostics/CommonModuleNameWords.md +++ b/docs/en/diagnostics/CommonModuleNameWords.md @@ -2,7 +2,7 @@ | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Code smell` | `BSL`
`OS` | `Info` | `Yes` | `1` | `standard` | +| `Code smell` | `BSL` | `Info` | `Yes` | `5` | `standard` | ## Parameters diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java index f6097d7fda2..6645e15b907 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java @@ -34,16 +34,9 @@ abstract class AbstractCommonModuleNameDiagnostic extends AbstractDiagnostic { protected Pattern pattern; - public AbstractCommonModuleNameDiagnostic(DiagnosticInfo info) { - super(info); - - } - public AbstractCommonModuleNameDiagnostic(DiagnosticInfo info, String regexp) { super(info); - pattern = CaseInsensitivePattern.compile(regexp); - } @Override diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic.java index 405ff32ec55..cd05f9303be 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic.java @@ -24,17 +24,24 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticParameter; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; import com.github._1c_syntax.utils.CaseInsensitivePattern; +import java.util.Map; import java.util.regex.Matcher; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, severity = DiagnosticSeverity.INFO, + scope = DiagnosticScope.BSL, + modules = { + ModuleType.CommonModule + }, minutesToFix = 5, tags = { DiagnosticTag.STANDARD @@ -55,7 +62,12 @@ public class CommonModuleNameWordsDiagnostic extends AbstractCommonModuleNameDia private String words = DEFAULT_WORDS; public CommonModuleNameWordsDiagnostic(DiagnosticInfo info) { - super(info); + super(info, DEFAULT_WORDS); + } + + @Override + public void configure(Map configuration) { + super.configure(configuration); pattern = CaseInsensitivePattern.compile(words); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnosticTest.java index 6e8867e6281..1abd72f1ef3 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnosticTest.java @@ -34,6 +34,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; +import java.util.Map; import java.util.Optional; import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; @@ -89,6 +90,30 @@ void testNegative() { } + @Test + void testConfigure() { + + getDocumentContextFromFile(); + + Map configuration = diagnosticInstance.getInfo().getDefaultConfiguration(); + configuration.put("words", "мой"); + diagnosticInstance.configure(configuration); + + // given + when(module.getName()).thenReturn("МойОбщий"); + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(5, 0, 1); + + } + + @SneakyThrows void getDocumentContextFromFile() { From e6eec3f59cc2075ae99f2d58712b0311df5dcad1 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Wed, 13 May 2020 13:56:02 +0300 Subject: [PATCH 290/444] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20=D0=BF=D1=80=D0=BE=D0=B1=D1=80=D0=BE=D1=81?= =?UTF-8?q?=20=D0=B4=D0=B5=D1=84=D0=BE=D0=BB=D1=82=D0=BD=D0=BE=D0=B3=D0=BE?= =?UTF-8?q?=20=D0=B7=D0=BD=D0=B0=D1=87=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=B2=20?= =?UTF-8?q?=D0=B4=D0=B0=D0=BD=D0=BD=D1=8B=D0=B5=20=D0=BE=20=D0=BF=D0=B0?= =?UTF-8?q?=D1=80=D0=B0=D0=BC=D0=B5=D1=82=D1=80=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/CommonModuleNameWords.md | 6 +++--- docs/en/diagnostics/CommonModuleNameWords.md | 4 ++-- .../diagnostics/CommonModuleNameWordsDiagnostic.java | 3 ++- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/diagnostics/CommonModuleNameWords.md b/docs/diagnostics/CommonModuleNameWords.md index c533bdb6c7a..f1f1187e201 100644 --- a/docs/diagnostics/CommonModuleNameWords.md +++ b/docs/diagnostics/CommonModuleNameWords.md @@ -2,13 +2,13 @@ | Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Дефект кода` | `BSL`
`OS` | `Информационный` | `Да` | `1` | `standard` | +| `Дефект кода` | `BSL` | `Информационный` | `Да` | `5` | `standard` | ## Параметры | Имя | Тип | Описание | Значение по умолчанию | | :-: | :-: | :-- | :-: | -| `words` | `Строка` | ```Нерекомендуемые слова``` | `````` | +| `words` | `Строка` | ```Нерекомендуемые слова``` | ```процедуры|procedures|функции|functions|обработчики|handlers|модуль|module|функциональность|functionality``` | ## Описание диагностики @@ -36,6 +36,6 @@ ```json "CommonModuleNameWords": { - "words": "" + "words": "процедуры|procedures|функции|functions|обработчики|handlers|модуль|module|функциональность|functionality" } ``` diff --git a/docs/en/diagnostics/CommonModuleNameWords.md b/docs/en/diagnostics/CommonModuleNameWords.md index c7eb16dc71f..17c055b6d41 100644 --- a/docs/en/diagnostics/CommonModuleNameWords.md +++ b/docs/en/diagnostics/CommonModuleNameWords.md @@ -8,7 +8,7 @@ | Name | Type | Description | Default value | | :-: | :-: | :-- | :-: | -| `words` | `String` | ```Unrecommended words``` | `````` | +| `words` | `String` | ```Unrecommended words``` | ```процедуры|procedures|функции|functions|обработчики|handlers|модуль|module|функциональность|functionality``` | ## Description @@ -39,6 +39,6 @@ ```json "CommonModuleNameWords": { - "words": "" + "words": "процедуры|procedures|функции|functions|обработчики|handlers|модуль|module|функциональность|functionality" } ``` diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic.java index cd05f9303be..1763f4bc2d0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic.java @@ -57,7 +57,8 @@ public class CommonModuleNameWordsDiagnostic extends AbstractCommonModuleNameDia "|функциональность|functionality"; @DiagnosticParameter( - type = String.class + type = String.class, + defaultValue = DEFAULT_WORDS ) private String words = DEFAULT_WORDS; From c175befc2f024fb85a051dde5d23daedf96dae3d Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Wed, 13 May 2020 14:07:49 +0300 Subject: [PATCH 291/444] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D0=B8=D0=BD=D1=81=D1=82=D1=80=D1=83=D0=BA?= =?UTF-8?q?=D1=86=D0=B8=D1=8F=20=D0=BF=D0=BE=20=D0=B8=D1=81=D0=BF=D0=BE?= =?UTF-8?q?=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D1=8E=20=D0=BA?= =?UTF-8?q?=D0=BE=D0=BD=D1=84=D0=B8=D0=B3=D1=83=D1=80=D0=B0=D1=86=D0=B8?= =?UTF-8?q?=D0=BE=D0=BD=D0=BD=D0=BE=D0=B3=D0=BE=20=D1=84=D0=B0=D0=B9=D0=BB?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/features/ConfigurationFile.md | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/docs/features/ConfigurationFile.md b/docs/features/ConfigurationFile.md index 60d326b9ca1..fb33c40d8c8 100644 --- a/docs/features/ConfigurationFile.md +++ b/docs/features/ConfigurationFile.md @@ -7,13 +7,17 @@ BSL Language Server предоставляет возможность измен |Наименование|Тип|Описание| |:--|:-:|:--| -|`diagnosticLanguage`|`Строка`|Этот параметр устанавливает язык отображения диагностированных замечаний. На данный момент поддерживаются два языка:
* `ru` - для русского языка (*используется по умолчанию*)
* `en` - для английского языка| -|`showCognitiveComplexityCodeLens`|`Булево`|В продвинутых редакторах кода/IDE *(например [Visual Studio Code](https://code.visualstudio.com/))*, этим параметром включается отображение значения [когнитивной сложности](../diagnostics/CognitiveComplexity.md) метода над его определением. По умолчанию параметр включен (*установлен в `true`*)| -|`showCyclomaticComplexityCodeLens`|`Булево`|По аналогии с `showCognitiveComplexityCodeLens`, этот параметр включает отображение значения [цикломатической сложности](../diagnostics/CyclomaticComplexity.md) метода. По умолчанию параметр включен (*установлен в `true`*)| -|`computeDiagnosticsTrigger`|`Строка`|С помощью этого параметра можно указать событие, при котором будет вызвана процедура анализа кода для диагностирования замечаний. Возможные значения:
* `onType` - при редактировании файла (онлайн) ***на больших файлах может ЗНАЧИТЕЛЬНО замедлять редактирование***
* `onSave` - при сохранении файла (*используется по умолчанию*)
* `never` - анализ выполняться не будет| -|`computeDiagnosticsSkipSupport`|`Строка`|Этим параметром настраивается режим пропуска файлов *(т.е. файлы не анализируются на предмет наличия замечаний)* **конфигурации 1С**, находящихся "на поддержке" конфигурации поставщика. Возможные значения:
* `withSupport` - пропускаются все модули, находящиеся "на поддержке" *(все виды "замков")*
* `withSupportLocked` - пропускаются только модули, находящиеся "на поддержке" с запретом изменений *("желтый закрытый замок")*
* `never` - режим поддержки не анализируется и модули не пропускаются *(установлен по умолчанию)*| +|`language`|`Строка`|Этот параметр устанавливает язык отображения диагностированных замечаний. На данный момент поддерживаются два языка:
* `ru` - для русского языка (*используется по умолчанию*)
* `en` - для английского языка| +|`codeLens`|`JSON-Объект`|Содержит настройки отображения `линз` в продвинутых кода/IDE *(например [Visual Studio Code](https://code.visualstudio.com/))*, в которых выводится различная информация на блоком кода. Свойства объекта| +|⤷   `showCognitiveComplexity`|`Булево`|Включается отображение значения [когнитивной сложности](../diagnostics/CognitiveComplexity.md) метода над его определением. По умолчанию параметр включен (*установлен в `true`*)| +|⤷   `showCyclomaticComplexity`|`Булево`|Включает отображение значения [цикломатической сложности](../diagnostics/CyclomaticComplexity.md) метода. По умолчанию параметр включен (*установлен в `true`*)| +|`diagnostics`|`JSON-Объект`|Содержит настройки диагностик| +|⤷   `computeTrigger`|`Строка`|С помощью этого параметра можно указать событие, при котором будет вызвана процедура анализа кода для диагностирования замечаний. Возможные значения:
* `onType` - при редактировании файла (онлайн) ***на больших файлах может ЗНАЧИТЕЛЬНО замедлять редактирование***
* `onSave` - при сохранении файла (*используется по умолчанию*)
* `never` - анализ выполняться не будет| +|⤷   `skipSupport`|`Строка`|Этим параметром настраивается режим пропуска файлов *(т.е. файлы не анализируются на предмет наличия замечаний)* **конфигурации 1С**, находящихся "на поддержке" конфигурации поставщика. Возможные значения:
* `withSupport` - пропускаются все модули, находящиеся "на поддержке" *(все виды "замков")*
* `withSupportLocked` - пропускаются только модули, находящиеся "на поддержке" с запретом изменений *("желтый закрытый замок")*
* `never` - режим поддержки не анализируется и модули не пропускаются *(установлен по умолчанию)*| +|⤷   `mode`|`Строка`|Настройка для управления режимом учета настроек диагностик. Возможные варианты:
* `OFF` - Все диагностики считаются выключенными, вне зависимости от их настроек
* `ON` - Все диагностики включенные по умолчанию считаются включенными, остальные - в зависимости от личных настроек
* `EXCEPT` - Все диагностистики, кроме указанных, считаются включенными
* `ONLY` - Только указанные диагностики считаются включенными
* `ALL` - Все диагностики считаются включенными| +|⤷   `parameters`|`JSON-Объект`|Параметр представляет собой коллекцию настроек диагностик. Элементами коллекции являются json-объекты следующей структуры:
* *ключ объекта* - строка, являющаяся ключом диагностики
* *значение объекта* - может принимать либо булево значение, и тогда интерпретируется как отключение диагностики (`false`) или ее включение с параметрами по умолчанию (`true`), либо значение типа `json-объект`, представляющего собой набор настроек диагностики.

Ключ, включена ли по умолчанию, а также описание возможных параметров и примеры для конфигурационного файла представлены на странице с описанием каждой диагностики.| |`traceLog`|`Строка`|Для логирования всех запросов *(входящих и исходящих)* между **BSL Language Server** и **Language Client** из используемого редактора/IDE, в этом параметре можно указать путь к файлу лога. Путь можно указывать как абсолютный, так и относительный *(от корня анализируемого проекта)*, по умолчанию значение не заполнено.

**ВНИМАНИЕ**

* При запуске **BSL Language Server** перезаписывает указанный файл
* Скорость взаимодействия между клиентом и сервером **ЗНАЧИТЕЛЬНО ЗАМЕДЛЯЕТСЯ**| -|`diagnostics`|`JSON-Объект`|Параметр представляет собой коллекцию настроек диагностик. Элементами коллекции являются json-объекты следующей структуры:
* *ключ объекта* - строка, являющаяся ключом диагностики
* *значение объекта* - может принимать либо булево значение, и тогда интерпретируется как отключение диагностики (`false`) или ее включение с параметрами по умолчанию (`true`), либо значение типа `json-объект`, представляющего собой набор настроек диагностики.

Ключ, включена ли по умолчанию, а также описание возможных параметров и примеры для конфигурационного файла представлены на странице с описанием каждой диагностики.| +|`configurationRoot`|`Строка`|Данный параметр предназначен для указания корневого каталога, в котором находятся файлы конфигурации 1С в каталоге проекта. Может быть полезен в случае нахождения нескольких каталогов конфигураций в одном каталоге проекта либо при сложной структуре каталога проекта. По умолчанию параметр не заполнен и `BSL Language Server` самостоятельно определяет расположение корневого каталога конфигурации| Для облегчения составления и редактирования конфигурационного файла можно использовать следующую JSON-схему: @@ -28,16 +32,20 @@ https://1c-syntax.github.io/bsl-language-server/configuration/schema.json * Устанавливает язык сообщений диагностик - английский; * Изменяет настройку диагностики [LineLength - Ограничение на длину строки](../diagnostics/LineLength.md), устанавливая предел длины строки в 140 символов; * Отключает диагностику [MethodSize - Ограничение на размер метода](../diagnostics/MethodSize.md). +* Включает расчет диагностик в непрерывном режиме (`computeTrigger = onType`) ```json { "$schema": "https://1c-syntax.github.io/bsl-language-server/configuration/schema.json", - "diagnosticLanguage": "en", + "language": "en", "diagnostics": { - "LineLength": { - "maxLineLength": 140 - }, - "MethodSize": false + "computeTrigger": "onType", + "parameters": { + "LineLength": { + "maxLineLength": 140 + }, + "MethodSize": false + } } } ``` From bf3ebf6ea3293e09da1f88e803054eb6e45185e0 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Wed, 13 May 2020 14:17:32 +0300 Subject: [PATCH 292/444] =?UTF-8?q?=D0=BF=D0=BE=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=B8=D0=BC=D1=8F=20=D0=BF=D0=B0=D1=80=D0=B0?= =?UTF-8?q?=D0=BC=D0=B5=D1=82=D1=80=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index 647313e9d87..57191b0584f 100644 --- a/docs/index.md +++ b/docs/index.md @@ -63,7 +63,7 @@ Commands: При запуске BSL Language Server в обычном режиме будет запущен сам Language Server, взаимодействующий по протоколу [LSP]([language server protocol](https://microsoft.github.io/language-server-protocol/)). Для взаимодействия используются stdin и stdout. -По умолчанию тексты диагностик выдаются на русском языке. Для переключения языка сообщений от движка диагностик необходимо настроить параметр `diagnosticLanguage` в конфигурационном файле или вызвав событие `workspace/didChangeConfiguration`: +По умолчанию тексты диагностик выдаются на русском языке. Для переключения языка сообщений от движка диагностик необходимо настроить параметр `language` в конфигурационном файле или вызвав событие `workspace/didChangeConfiguration`: From e8589511781055e8df6c3309d2597d9d4279dd73 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Wed, 13 May 2020 14:17:58 +0300 Subject: [PATCH 293/444] =?UTF-8?q?=D0=97=D0=B0=D0=BF=D1=83=D1=81=D0=BA=20?= =?UTF-8?q?=D0=B1=D0=B5=D0=BD=D1=87=D0=BC=D0=B0=D1=80=D0=BA=D0=B0=20=D1=82?= =?UTF-8?q?=D0=BE=D0=BB=D1=8C=D0=BA=D0=BE=20=D0=BD=D0=B0=20=D0=B8=D0=B7?= =?UTF-8?q?=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8=D0=B8=20=D0=B2=D0=B0=D0=B6?= =?UTF-8?q?=D0=BD=D1=8B=D1=85=20=D1=84=D0=B0=D0=B9=D0=BB=D0=BE=D0=B2=20?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D0=B5=D0=BA=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/benchmark.yml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index c0538220160..f6ff29eabf5 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -5,7 +5,21 @@ on: branches: - develop - master + paths: + - 'src/**' + - '.github/workflows/benchmark.yml' + - '.github/scripts/*.*' + - '*gradle*' + - 'gradle/wrapper/gradle-wrapper.properties' + - 'lombok.config' pull_request: + paths: + - 'src/**' + - '.github/workflows/benchmark.yml' + - '.github/scripts/*.*' + - '*gradle*' + - 'gradle/wrapper/gradle-wrapper.properties' + - 'lombok.config' jobs: Benchmark: From 8ef79b8fc6ac5537584026fa9254a76a86d84f46 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Wed, 13 May 2020 14:25:30 +0300 Subject: [PATCH 294/444] CommonModuleInvalidTypeDiagnostic --- docs/diagnostics/CommonModuleInvalidType.md | 41 ++++ docs/diagnostics/index.md | 5 +- .../en/diagnostics/CommonModuleInvalidType.md | 36 ++++ docs/en/diagnostics/index.md | 5 +- .../CommonModuleInvalidTypeDiagnostic.java | 94 +++++++++ .../configuration/parameters-schema.json | 12 +- .../languageserver/configuration/schema.json | 3 + ...nModuleInvalidTypeDiagnostic_en.properties | 2 + ...nModuleInvalidTypeDiagnostic_ru.properties | 2 + ...CommonModuleInvalidTypeDiagnosticTest.java | 183 ++++++++++++++++++ .../CommonModuleInvalidTypeDiagnostic.bsl | 1 + 11 files changed, 379 insertions(+), 5 deletions(-) create mode 100644 docs/diagnostics/CommonModuleInvalidType.md create mode 100644 docs/en/diagnostics/CommonModuleInvalidType.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/CommonModuleInvalidTypeDiagnostic.bsl diff --git a/docs/diagnostics/CommonModuleInvalidType.md b/docs/diagnostics/CommonModuleInvalidType.md new file mode 100644 index 00000000000..3170cdd5e04 --- /dev/null +++ b/docs/diagnostics/CommonModuleInvalidType.md @@ -0,0 +1,41 @@ +# Общий Модуль недопустимого типа (CommonModuleInvalidType) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Ошибка` | `BSL`
`OS` | `Важный` | `Да` | `5` | `standard`
`unpredictable` | + + +## Описание диагностики + +При разработке общих модулей следует выбирать один из четырех контекстов выполнения кода: + +|Тип общего модуля | Пример наименования | Вызов сервера | Сервер | Внешнее соединение | Клиент(обычное приложение) | Клиент(управляемое приложение)| +| -- | -- | -- | -- | -- | -- | -- | +| Серверный | ОбщегоНазначения (или ОбщегоНазначенияСервер) |   | + | + | + |   +| Серверный для вызова с клиента | ОбщегоНазначенияВызовСервера | + | + |   |   |   +| Клиентский | ОбщегоНазначенияКлиент (или ОбщегоНазначенияГлобальный) |   |   |   | + | + +| Клиент-серверный | ОбщегоНазначенияКлиентСервер |   | + | + | + | +| + + +## Примеры + + +## Источники + +* Источник: [Стандарт: Правила создания общих модулей](https://its.1c.ru/db/v8std#content:469:hdoc:1.2) + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:CommonModuleInvalidType-off +// BSLLS:CommonModuleInvalidType-on +``` + +### Параметр конфигурационного файла + +```json +"CommonModuleInvalidType": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index ad208c20421..468af110de6 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,11 +8,11 @@ ## Список реализованных диагностик -Общее количество: **107** +Общее количество: **108** * Дефект кода: **69** * Уязвимость: **2** -* Ошибка: **33** +* Ошибка: **34** * Потенциальная уязвимость: **3** | Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги | @@ -26,6 +26,7 @@ | [CommentedCode](CommentedCode.md) | Закомментированный фрагмент кода | Да | Незначительный | Дефект кода | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Нарушение правил работы с транзакциями для метода 'ЗафиксироватьТранзакцию' | Да | Важный | Ошибка | `standard` | | [CommonModuleAssign](CommonModuleAssign.md) | Присвоение общему модулю | Да | Блокирующий | Ошибка | `error` | +| [CommonModuleInvalidType](CommonModuleInvalidType.md) | Общий Модуль недопустимого типа | Да | Важный | Ошибка | `standard`
`unpredictable` | | [CommonModuleNameCached](CommonModuleNameCached.md) | Пропущен постфикс "ПовтИсп" | Да | Важный | Дефект кода | `standard`
`badpractice`
`unpredictable` | | [CommonModuleNameClient](CommonModuleNameClient.md) | Пропущен постфикс "Клиент" | Да | Незначительный | Дефект кода | `standard`
`badpractice`
`unpredictable` | | [CommonModuleNameClientServer](CommonModuleNameClientServer.md) | Пропущен постфикс "КлиентСервер" | Да | Важный | Дефект кода | `standard`
`badpractice`
`unpredictable` | diff --git a/docs/en/diagnostics/CommonModuleInvalidType.md b/docs/en/diagnostics/CommonModuleInvalidType.md new file mode 100644 index 00000000000..7bf5339835e --- /dev/null +++ b/docs/en/diagnostics/CommonModuleInvalidType.md @@ -0,0 +1,36 @@ +# Common module invalid type (CommonModuleInvalidType) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Error` | `BSL`
`OS` | `Major` | `Yes` | `5` | `standard`
`unpredictable` | + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:CommonModuleInvalidType-off +// BSLLS:CommonModuleInvalidType-on +``` + +### Parameter for config + +```json +"CommonModuleInvalidType": false +``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 1ab3ba79e4e..1c18665518d 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,9 +8,9 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **107** +Total: **108** -* Error: **33** +* Error: **34** * Code smell: **69** * Vulnerability: **2** * Security Hotspot: **3** @@ -26,6 +26,7 @@ Total: **107** | [CommentedCode](CommentedCode.md) | Commented out code | Yes | Minor | Code smell | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Violating transaction rules for the 'CommitTransaction' method | Yes | Major | Error | `standard` | | [CommonModuleAssign](CommonModuleAssign.md) | CommonModuleAssign | Yes | Blocker | Error | `error` | +| [CommonModuleInvalidType](CommonModuleInvalidType.md) | Common module invalid type | Yes | Major | Error | `standard`
`unpredictable` | | [CommonModuleNameCached](CommonModuleNameCached.md) | Missed postfix "Cached" | Yes | Major | Code smell | `standard`
`badpractice`
`unpredictable` | | [CommonModuleNameClient](CommonModuleNameClient.md) | Missed postfix "Client" | Yes | Minor | Code smell | `standard`
`badpractice`
`unpredictable` | | [CommonModuleNameClientServer](CommonModuleNameClientServer.md) | Missed postfix "ClientServer" | Yes | Major | Code smell | `standard`
`badpractice`
`unpredictable` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic.java new file mode 100644 index 00000000000..6d0e452047c --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic.java @@ -0,0 +1,94 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; + +import java.util.regex.Matcher; + +@DiagnosticMetadata( + type = DiagnosticType.ERROR, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 5, + tags = { + DiagnosticTag.STANDARD, + DiagnosticTag.UNPREDICTABLE + } + +) +public class CommonModuleInvalidTypeDiagnostic extends AbstractCommonModuleNameDiagnostic { + public CommonModuleInvalidTypeDiagnostic(DiagnosticInfo info) { + super(info, ""); + } + + @Override + protected boolean flagsCheck(CommonModule commonModule) { + + return !isServer(commonModule) + && !isServerCall(commonModule) + && !isClient(commonModule) + && !isClientServer(commonModule); + } + + private boolean isClientServer(CommonModule commonModule) { + return !commonModule.isServerCall() + && commonModule.isServer() + && commonModule.isExternalConnection() + && commonModule.isClientOrdinaryApplication() + && commonModule.isClientManagedApplication(); + } + + private boolean isClient(CommonModule commonModule) { + return !commonModule.isServerCall() + && !commonModule.isServer() + && !commonModule.isExternalConnection() + && commonModule.isClientOrdinaryApplication() + && commonModule.isClientManagedApplication(); + } + + private boolean isServerCall(CommonModule commonModule) { + return commonModule.isServerCall() + && commonModule.isServer() + && !commonModule.isExternalConnection() + && !commonModule.isClientOrdinaryApplication() + && !commonModule.isClientManagedApplication(); + } + + private boolean isServer(CommonModule commonModule) { + return !commonModule.isServerCall() + && commonModule.isServer() + && commonModule.isExternalConnection() + && commonModule.isClientOrdinaryApplication() + && !commonModule.isClientManagedApplication(); + } + + @Override + protected boolean matchCheck(Matcher matcher) { + return true; + } + +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index f54eec0b8d4..176c7ea9b93 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -116,6 +116,16 @@ "title": "CommonModuleAssign", "$id": "#/definitions/CommonModuleAssign" }, + "CommonModuleInvalidType": { + "description": "Common module invalid type", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Common module invalid type", + "$id": "#/definitions/CommonModuleInvalidType" + }, "CommonModuleNameCached": { "description": "Missed postfix \"Cached\"", "default": true, @@ -197,7 +207,7 @@ "properties": { "words": { "description": "Unrecommended words", - "default": "", + "default": "\u043f\u0440\u043e\u0446\u0435\u0434\u0443\u0440\u044b|procedures|\u0444\u0443\u043d\u043a\u0446\u0438\u0438|functions|\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u0447\u0438\u043a\u0438|handlers|\u043c\u043e\u0434\u0443\u043b\u044c|module|\u0444\u0443\u043d\u043a\u0446\u0438\u043e\u043d\u0430\u043b\u044c\u043d\u043e\u0441\u0442\u044c|functionality", "type": "string", "title": "Unrecommended words" } diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index f6fdce501e1..a7cdcb33a0e 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -50,6 +50,9 @@ "CommonModuleAssign": { "$ref": "parameters-schema.json#/definitions/CommonModuleAssign" }, + "CommonModuleInvalidType": { + "$ref": "parameters-schema.json#/definitions/CommonModuleInvalidType" + }, "CommonModuleNameCached": { "$ref": "parameters-schema.json#/definitions/CommonModuleNameCached" }, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic_en.properties new file mode 100644 index 00000000000..10e61dec27e --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Common module invalid type +diagnosticName=Common module invalid type diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic_ru.properties new file mode 100644 index 00000000000..0e5f9b0bf04 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Общий модуль недопустимого типа +diagnosticName=Общий Модуль недопустимого типа diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnosticTest.java new file mode 100644 index 00000000000..a9601717fbc --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnosticTest.java @@ -0,0 +1,183 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.ServerContext; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.utils.Absolute; +import lombok.SneakyThrows; +import org.apache.commons.io.FileUtils; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Optional; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +class CommonModuleInvalidTypeDiagnosticTest extends AbstractDiagnosticTest { + CommonModuleInvalidTypeDiagnosticTest() { + super(CommonModuleInvalidTypeDiagnostic.class); + } + + private CommonModule module; + private DocumentContext documentContext; + + private static final String PATH_TO_METADATA = "src/test/resources/metadata"; + private static final String PATH_TO_MODULE_FILE = "src/test/resources/metadata/CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; + + @Test + void testClientServer() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ПростоКлиентСервер"); + when(module.isServer()).thenReturn(Boolean.TRUE); + when(module.isServerCall()).thenReturn(Boolean.TRUE); + when(module.isExternalConnection()).thenReturn(Boolean.TRUE); + when(module.isClientOrdinaryApplication()).thenReturn(Boolean.TRUE); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(5, 0, 1); + + } + + @Test + void testUnknown() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("СОшибкой"); + when(module.isServer()).thenReturn(Boolean.TRUE); + when(module.isServerCall()).thenReturn(Boolean.TRUE); + when(module.isExternalConnection()).thenReturn(Boolean.FALSE); + when(module.isClientOrdinaryApplication()).thenReturn(Boolean.FALSE); + when(module.isClientManagedApplication()).thenReturn(Boolean.FALSE); + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @Test + void testServerCall() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ПростоВызовСерверат"); + when(module.isServer()).thenReturn(Boolean.TRUE); + when(module.isServerCall()).thenReturn(Boolean.TRUE); + when(module.isExternalConnection()).thenReturn(Boolean.FALSE); + when(module.isClientOrdinaryApplication()).thenReturn(Boolean.FALSE); + when(module.isClientManagedApplication()).thenReturn(Boolean.FALSE); + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @Test + void testServer() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ПростоСервер"); + when(module.isServer()).thenReturn(Boolean.TRUE); + when(module.isServerCall()).thenReturn(Boolean.FALSE); + when(module.isExternalConnection()).thenReturn(Boolean.TRUE); + when(module.isClientOrdinaryApplication()).thenReturn(Boolean.TRUE); + when(module.isClientManagedApplication()).thenReturn(Boolean.FALSE); + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @Test + void testClient() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ПростоКлиент"); + when(module.isServer()).thenReturn(Boolean.FALSE); + when(module.isExternalConnection()).thenReturn(Boolean.FALSE); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + when(module.isClientOrdinaryApplication()).thenReturn(Boolean.TRUE); + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @SneakyThrows + void getDocumentContextFromFile() { + + Path path = Absolute.path(PATH_TO_METADATA); + Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + + ServerContext serverContext = new ServerContext(path); + var configuration = serverContext.getConfiguration(); + documentContext = spy(new DocumentContext( + testFile.toUri(), + FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), + serverContext + )); + + module = spy((CommonModule) configuration.getModulesByURI().get(documentContext.getUri())); + + } +} + diff --git a/src/test/resources/diagnostics/CommonModuleInvalidTypeDiagnostic.bsl b/src/test/resources/diagnostics/CommonModuleInvalidTypeDiagnostic.bsl new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/src/test/resources/diagnostics/CommonModuleInvalidTypeDiagnostic.bsl @@ -0,0 +1 @@ + From 5a7980938c373c24547eda3d0d95df7294273119 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Wed, 13 May 2020 15:17:58 +0300 Subject: [PATCH 295/444] =?UTF-8?q?=D0=A3=D0=B7=D0=BE=D1=80=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/CommonModuleInvalidType.md | 4 ++-- docs/diagnostics/index.md | 2 +- docs/en/diagnostics/CommonModuleInvalidType.md | 2 +- docs/en/diagnostics/index.md | 2 +- .../diagnostics/CommonModuleInvalidTypeDiagnostic.java | 9 ++++++++- .../CommonModuleInvalidTypeDiagnostic_ru.properties | 2 +- .../CommonModuleInvalidTypeDiagnosticTest.java | 2 +- 7 files changed, 15 insertions(+), 8 deletions(-) diff --git a/docs/diagnostics/CommonModuleInvalidType.md b/docs/diagnostics/CommonModuleInvalidType.md index 3170cdd5e04..011e8845bb6 100644 --- a/docs/diagnostics/CommonModuleInvalidType.md +++ b/docs/diagnostics/CommonModuleInvalidType.md @@ -1,8 +1,8 @@ -# Общий Модуль недопустимого типа (CommonModuleInvalidType) +# Общий модуль недопустимого типа (CommonModuleInvalidType) | Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Ошибка` | `BSL`
`OS` | `Важный` | `Да` | `5` | `standard`
`unpredictable` | +| `Ошибка` | `BSL` | `Важный` | `Да` | `5` | `standard`
`unpredictable`
`design` | ## Описание диагностики diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 468af110de6..36e59e005a4 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -26,7 +26,7 @@ | [CommentedCode](CommentedCode.md) | Закомментированный фрагмент кода | Да | Незначительный | Дефект кода | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Нарушение правил работы с транзакциями для метода 'ЗафиксироватьТранзакцию' | Да | Важный | Ошибка | `standard` | | [CommonModuleAssign](CommonModuleAssign.md) | Присвоение общему модулю | Да | Блокирующий | Ошибка | `error` | -| [CommonModuleInvalidType](CommonModuleInvalidType.md) | Общий Модуль недопустимого типа | Да | Важный | Ошибка | `standard`
`unpredictable` | +| [CommonModuleInvalidType](CommonModuleInvalidType.md) | Общий модуль недопустимого типа | Да | Важный | Ошибка | `standard`
`unpredictable`
`design` | | [CommonModuleNameCached](CommonModuleNameCached.md) | Пропущен постфикс "ПовтИсп" | Да | Важный | Дефект кода | `standard`
`badpractice`
`unpredictable` | | [CommonModuleNameClient](CommonModuleNameClient.md) | Пропущен постфикс "Клиент" | Да | Незначительный | Дефект кода | `standard`
`badpractice`
`unpredictable` | | [CommonModuleNameClientServer](CommonModuleNameClientServer.md) | Пропущен постфикс "КлиентСервер" | Да | Важный | Дефект кода | `standard`
`badpractice`
`unpredictable` | diff --git a/docs/en/diagnostics/CommonModuleInvalidType.md b/docs/en/diagnostics/CommonModuleInvalidType.md index 7bf5339835e..4660ca77fba 100644 --- a/docs/en/diagnostics/CommonModuleInvalidType.md +++ b/docs/en/diagnostics/CommonModuleInvalidType.md @@ -2,7 +2,7 @@ | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Error` | `BSL`
`OS` | `Major` | `Yes` | `5` | `standard`
`unpredictable` | +| `Error` | `BSL` | `Major` | `Yes` | `5` | `standard`
`unpredictable`
`design` | ## Description diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 1c18665518d..b9121ad6aab 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -26,7 +26,7 @@ Total: **108** | [CommentedCode](CommentedCode.md) | Commented out code | Yes | Minor | Code smell | `standard`
`badpractice` | | [CommitTransactionOutsideTryCatch](CommitTransactionOutsideTryCatch.md) | Violating transaction rules for the 'CommitTransaction' method | Yes | Major | Error | `standard` | | [CommonModuleAssign](CommonModuleAssign.md) | CommonModuleAssign | Yes | Blocker | Error | `error` | -| [CommonModuleInvalidType](CommonModuleInvalidType.md) | Common module invalid type | Yes | Major | Error | `standard`
`unpredictable` | +| [CommonModuleInvalidType](CommonModuleInvalidType.md) | Common module invalid type | Yes | Major | Error | `standard`
`unpredictable`
`design` | | [CommonModuleNameCached](CommonModuleNameCached.md) | Missed postfix "Cached" | Yes | Major | Code smell | `standard`
`badpractice`
`unpredictable` | | [CommonModuleNameClient](CommonModuleNameClient.md) | Missed postfix "Client" | Yes | Minor | Code smell | `standard`
`badpractice`
`unpredictable` | | [CommonModuleNameClientServer](CommonModuleNameClientServer.md) | Missed postfix "ClientServer" | Yes | Major | Code smell | `standard`
`badpractice`
`unpredictable` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic.java index 6d0e452047c..834d4586a7b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic.java @@ -23,20 +23,27 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; import java.util.regex.Matcher; @DiagnosticMetadata( type = DiagnosticType.ERROR, severity = DiagnosticSeverity.MAJOR, + scope = DiagnosticScope.BSL, + modules = { + ModuleType.CommonModule + }, minutesToFix = 5, tags = { DiagnosticTag.STANDARD, - DiagnosticTag.UNPREDICTABLE + DiagnosticTag.UNPREDICTABLE, + DiagnosticTag.DESIGN } ) diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic_ru.properties index 0e5f9b0bf04..92b534b0a5b 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic_ru.properties @@ -1,2 +1,2 @@ diagnosticMessage=Общий модуль недопустимого типа -diagnosticName=Общий Модуль недопустимого типа +diagnosticName=Общий модуль недопустимого типа diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnosticTest.java index a9601717fbc..08c97f7cc4a 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnosticTest.java @@ -103,7 +103,7 @@ void testServerCall() { getDocumentContextFromFile(); // given - when(module.getName()).thenReturn("ПростоВызовСерверат"); + when(module.getName()).thenReturn("ПростоВызовСервера"); when(module.isServer()).thenReturn(Boolean.TRUE); when(module.isServerCall()).thenReturn(Boolean.TRUE); when(module.isExternalConnection()).thenReturn(Boolean.FALSE); From c80823ec75d9fecfe5c5bcfcb0c81057335da1d8 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Wed, 13 May 2020 15:32:08 +0300 Subject: [PATCH 296/444] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D0=BE=D1=82=D0=BE?= =?UTF-8?q?=D0=B2=D0=BA=D0=B8=20=D1=81=D1=82=D1=80=D0=B0=D0=BD=D0=B8=D1=86?= =?UTF-8?q?=20=D1=81=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC=D0=B5=D0=BD=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/faq.md | 1 + docs/en/index.md | 4 +++- docs/en/systemRequirements.md | 1 + docs/faq.md | 1 + docs/index.md | 2 ++ docs/systemRequirements.md | 1 + 6 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 docs/en/faq.md create mode 100644 docs/en/systemRequirements.md create mode 100644 docs/faq.md create mode 100644 docs/systemRequirements.md diff --git a/docs/en/faq.md b/docs/en/faq.md new file mode 100644 index 00000000000..554f7bdbbc7 --- /dev/null +++ b/docs/en/faq.md @@ -0,0 +1 @@ +# Frequently asked questions diff --git a/docs/en/index.md b/docs/en/index.md index 7b4d642e61f..2a8783d2cb3 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -22,6 +22,8 @@ - Reporters - Diagnostics - Features +- [Frequently asked questions](faq.md) +- [System requirements](systemRequirements.md) - Special thanks @@ -63,7 +65,7 @@ Commands: Starting BSL Language Server in standard mode will run the Language Server communicating via [LSP]([language server protocol](https://microsoft.github.io/language-server-protocol/)). stdin and stdout are used for communication. -By default diagnostics texts are displayed in Russian. To switch the diagnostics text language you need to set parameter `diagnosticLanguage` in configuration file or raise an event `workspace/didChangeConfiguration`: +By default diagnostics texts are displayed in Russian. To switch the diagnostics text language you need to set parameter `language` in configuration file or raise an event `workspace/didChangeConfiguration`: diff --git a/docs/en/systemRequirements.md b/docs/en/systemRequirements.md new file mode 100644 index 00000000000..0658719e7d7 --- /dev/null +++ b/docs/en/systemRequirements.md @@ -0,0 +1 @@ +# System requirements diff --git a/docs/faq.md b/docs/faq.md new file mode 100644 index 00000000000..6e33ee8180e --- /dev/null +++ b/docs/faq.md @@ -0,0 +1 @@ +# Часто задаваемые вопросы diff --git a/docs/index.md b/docs/index.md index 647313e9d87..33c782f25c3 100644 --- a/docs/index.md +++ b/docs/index.md @@ -22,6 +22,8 @@ * Репортеры * Диагностики * Дополнительные возможности +* [Часто задаваемые вопросы](faq.md) +* [Системные требования](systemRequirements.md) * Благодарности diff --git a/docs/systemRequirements.md b/docs/systemRequirements.md new file mode 100644 index 00000000000..fecdcd84e11 --- /dev/null +++ b/docs/systemRequirements.md @@ -0,0 +1 @@ +# Системные требования From 2a3ad58fc37900464e886120dad8059b2d119e6e Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Wed, 13 May 2020 15:42:04 +0300 Subject: [PATCH 297/444] test fix --- ...CommonModuleInvalidTypeDiagnosticTest.java | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnosticTest.java index 08c97f7cc4a..917bf8f286e 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnosticTest.java @@ -52,16 +52,16 @@ class CommonModuleInvalidTypeDiagnosticTest extends AbstractDiagnosticTest Date: Wed, 13 May 2020 15:50:48 +0300 Subject: [PATCH 298/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=B2=D0=B5=D1=80=D1=81=D0=B8=D0=B8=20java=20=D0=B8?= =?UTF-8?q?=20os?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/systemRequirements.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/systemRequirements.md b/docs/systemRequirements.md index fecdcd84e11..4ff09a1c276 100644 --- a/docs/systemRequirements.md +++ b/docs/systemRequirements.md @@ -1 +1,19 @@ # Системные требования + +Использование `BSL Language Server` имеет ряд ограничений, ниже приведены ключевые + +## Поддерживаемые версии Java + +`BSL Language Server` представляет собой консольное Java приложение, соответственно, для его функционирования необходимо наличие виртуальной машины Java на компьютере. + +На данный момент минимальной поддерживаемой версией является Java 11, но в рамках сборочных конвейеров происходит проверка работоспособности при использовании более свежих версий. На данный момент поддерживается Java 13. + +Кроме версии Java интересен и вендор JDK. В связи с изменившейся политикой лицензирования Oracle, рекомендуется использование открытых реализаций виртуальной машины `OpenJDK`: AdoptOpenJDK, Liberica JDK. + +## Поддерживаемые операционные системы + +`BSL Language Server` должен работать на всех системах под управлением современных десктопных и серверных операционных системах, для которых существует поддержка Java. В рамках сборочных ковейеров происходит тестирование наиболее популярных окружений: + +- гарантированно работает на последних версиях OS семейства Windows 7/10 включая серверные 2012 и выше +- поддерживаются OS на ядре Linux, в частности проводится тестирование каждого изменения на Ubuntu, в промышленной эксплуатации подтверждена работоспособность на CentOS версий 6 и 7. +- поддерживается MacOS последних версий From 8ebb3e946e73d1263a88ac0b6df2a9c2304ffaeb Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Wed, 13 May 2020 16:05:51 +0300 Subject: [PATCH 299/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=BF=D0=B0=D1=80=D1=83=20=D0=BF=D1=80=D0=B8=D0=BC?= =?UTF-8?q?=D0=B5=D1=80=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/faq.md | 12 ++++++++++++ docs/systemRequirements.md | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/docs/faq.md b/docs/faq.md index 6e33ee8180e..6cee76655e6 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -1 +1,13 @@ # Часто задаваемые вопросы + +В данном разделе собраны наиболее часто возникающие вопросы и ответы на них. + +1. Как изменить язык диагностических сообщений + +Для изменения языка выводимых сообщений с русского (по умолчанию) на английский можно с помощью конфигурационного файла. О возможностях конфигурирования можно узнать в [описании конфигурационного файла](features/ConfigurationFile.md) + +2. Как увеличить максимальную длину строки в диагностике `Ограничение на длину строки` + +Все диагностики имеет страницу с описанием в разделе `Диагностики`, например интересующая [Ограничение на длину строки](diagnostics/LineLength.md). Если диагностика может менять свое поведение, то на странице с описанием будут присутствовать параметры с описанием, на что они влияют. В данном случае - параметр `maxLineLength` как раз и отвечает за максимальную длину строки. + +3. \ No newline at end of file diff --git a/docs/systemRequirements.md b/docs/systemRequirements.md index 4ff09a1c276..eccd1d7df04 100644 --- a/docs/systemRequirements.md +++ b/docs/systemRequirements.md @@ -12,7 +12,7 @@ ## Поддерживаемые операционные системы -`BSL Language Server` должен работать на всех системах под управлением современных десктопных и серверных операционных системах, для которых существует поддержка Java. В рамках сборочных ковейеров происходит тестирование наиболее популярных окружений: +`BSL Language Server` должен работать на всех системах под управлением современных десктопных и серверных операционных систем, для которых существует поддержка Java. В рамках сборочных ковейеров происходит тестирование наиболее популярных окружений: - гарантированно работает на последних версиях OS семейства Windows 7/10 включая серверные 2012 и выше - поддерживаются OS на ядре Linux, в частности проводится тестирование каждого изменения на Ubuntu, в промышленной эксплуатации подтверждена работоспособность на CentOS версий 6 и 7. From ec6334326d391d5a7fb0683250841ba6d3c0736e Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Wed, 13 May 2020 16:26:32 +0300 Subject: [PATCH 300/444] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20?= =?UTF-8?q?=D0=B8=20=D0=BD=D0=BE=D0=B2=D1=8B=D0=B5=20=D0=BE=D1=82=D0=B2?= =?UTF-8?q?=D0=B5=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/faq.md | 11 ++++++++++- docs/systemRequirements.md | 4 ++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/docs/faq.md b/docs/faq.md index 6cee76655e6..005218fe700 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -10,4 +10,13 @@ Все диагностики имеет страницу с описанием в разделе `Диагностики`, например интересующая [Ограничение на длину строки](diagnostics/LineLength.md). Если диагностика может менять свое поведение, то на странице с описанием будут присутствовать параметры с описанием, на что они влияют. В данном случае - параметр `maxLineLength` как раз и отвечает за максимальную длину строки. -3. \ No newline at end of file +3. Как отключить Lens о когнитивной диагностики + +Для отключения `линзы` с информацией о когнитивной сложности стоит воспользоваться конфигурационным файлом, в котором для параметра `showCognitiveComplexity` установить значение `false`. О возможностях конфигурирования можно узнать в [описании конфигурационного файла](features/ConfigurationFile.md) + +4. Я считаю, что диагностика работает неправильно. Что делать + +В случае сомнения (или уверенности) в том, что диагностика работает неверно есть два пути + +- обратиться в чате [telegram](https://t.me/bsl_language_server) с ситуацией, возможно все-таки ошибки нет +- создать ишью ([issue](https://github.com/1c-syntax/bsl-language-server/issues)) в репозитории проекта соответствующего типа, куда приложить описание ошибки и, очень желательно, примеры кода, где диагностика работает неверно. diff --git a/docs/systemRequirements.md b/docs/systemRequirements.md index eccd1d7df04..bf83c2fba34 100644 --- a/docs/systemRequirements.md +++ b/docs/systemRequirements.md @@ -6,13 +6,13 @@ `BSL Language Server` представляет собой консольное Java приложение, соответственно, для его функционирования необходимо наличие виртуальной машины Java на компьютере. -На данный момент минимальной поддерживаемой версией является Java 11, но в рамках сборочных конвейеров происходит проверка работоспособности при использовании более свежих версий. На данный момент поддерживается Java 13. +На данный момент минимальной поддерживаемой версией является Java 11, но в рамках сборочных конвейеров происходит проверка работоспособности при использовании более свежих версий. На данный момент поддерживаются Java версий 11, 13 и 14. Кроме версии Java интересен и вендор JDK. В связи с изменившейся политикой лицензирования Oracle, рекомендуется использование открытых реализаций виртуальной машины `OpenJDK`: AdoptOpenJDK, Liberica JDK. ## Поддерживаемые операционные системы -`BSL Language Server` должен работать на всех системах под управлением современных десктопных и серверных операционных систем, для которых существует поддержка Java. В рамках сборочных ковейеров происходит тестирование наиболее популярных окружений: +`BSL Language Server` должен работать на всех системах под управлением современных десктопных и серверных операционных систем, для которых существует поддержка Java. В рамках сборочных конвейеров происходит тестирование наиболее популярных окружений: - гарантированно работает на последних версиях OS семейства Windows 7/10 включая серверные 2012 и выше - поддерживаются OS на ядре Linux, в частности проводится тестирование каждого изменения на Ubuntu, в промышленной эксплуатации подтверждена работоспособность на CentOS версий 6 и 7. From a2a0e83f705178bce3e3031c0fb046c3545a3e2c Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Wed, 13 May 2020 17:09:53 +0300 Subject: [PATCH 301/444] type in abstract class --- .../AbstractCommonModuleNameDiagnostic.java | 32 +++++++++++++++++++ .../CommonModuleInvalidTypeDiagnostic.java | 32 ------------------- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java index 6645e15b907..58cf77773a6 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java @@ -61,4 +61,36 @@ protected boolean matchCheck(Matcher matcher) { return !matcher.find(); } + protected static boolean isClientServer(CommonModule commonModule) { + return !commonModule.isServerCall() + && commonModule.isServer() + && commonModule.isExternalConnection() +// && commonModule.isClientOrdinaryApplication() + && commonModule.isClientManagedApplication(); + } + + protected static boolean isClient(CommonModule commonModule) { + return !commonModule.isServerCall() + && !commonModule.isServer() + && !commonModule.isExternalConnection() +// && commonModule.isClientOrdinaryApplication() + && commonModule.isClientManagedApplication(); + } + + protected static boolean isServerCall(CommonModule commonModule) { + return commonModule.isServerCall() + && commonModule.isServer() + && !commonModule.isExternalConnection() +// && !commonModule.isClientOrdinaryApplication() + && !commonModule.isClientManagedApplication(); + } + + protected static boolean isServer(CommonModule commonModule) { + return !commonModule.isServerCall() + && commonModule.isServer() + && commonModule.isExternalConnection() +// && commonModule.isClientOrdinaryApplication() + && !commonModule.isClientManagedApplication(); + } + } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic.java index 834d4586a7b..4c024bbf128 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic.java @@ -61,38 +61,6 @@ protected boolean flagsCheck(CommonModule commonModule) { && !isClientServer(commonModule); } - private boolean isClientServer(CommonModule commonModule) { - return !commonModule.isServerCall() - && commonModule.isServer() - && commonModule.isExternalConnection() - && commonModule.isClientOrdinaryApplication() - && commonModule.isClientManagedApplication(); - } - - private boolean isClient(CommonModule commonModule) { - return !commonModule.isServerCall() - && !commonModule.isServer() - && !commonModule.isExternalConnection() - && commonModule.isClientOrdinaryApplication() - && commonModule.isClientManagedApplication(); - } - - private boolean isServerCall(CommonModule commonModule) { - return commonModule.isServerCall() - && commonModule.isServer() - && !commonModule.isExternalConnection() - && !commonModule.isClientOrdinaryApplication() - && !commonModule.isClientManagedApplication(); - } - - private boolean isServer(CommonModule commonModule) { - return !commonModule.isServerCall() - && commonModule.isServer() - && commonModule.isExternalConnection() - && commonModule.isClientOrdinaryApplication() - && !commonModule.isClientManagedApplication(); - } - @Override protected boolean matchCheck(Matcher matcher) { return true; From 4bb5c5ec16109e628ef8aceaaab9d20650966c4c Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Wed, 13 May 2020 17:11:15 +0300 Subject: [PATCH 302/444] other diags use abstract type --- .../CommonModuleNameClientDiagnostic.java | 3 +-- ...ommonModuleNameClientServerDiagnostic.java | 2 +- ...ommonModuleNameGlobalClientDiagnostic.java | 2 +- .../CommonModuleNameServerCallDiagnostic.java | 2 +- .../CommonModuleNameClientDiagnosticTest.java | 20 +++++++++++++++++++ ...nModuleNameClientServerDiagnosticTest.java | 1 + ...nModuleNameGlobalClientDiagnosticTest.java | 4 ++++ ...monModuleNameServerCallDiagnosticTest.java | 2 +- 8 files changed, 30 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java index 4583ccf34d3..dd888de3c28 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java @@ -55,8 +55,7 @@ public CommonModuleNameClientDiagnostic(DiagnosticInfo info) { @Override protected boolean flagsCheck(CommonModule commonModule) { return !commonModule.isGlobal() - && commonModule.isClientManagedApplication() - && !commonModule.isServerCall(); + && isClient(commonModule); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java index 9bf906774b5..a0afab1ac81 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java @@ -54,6 +54,6 @@ public CommonModuleNameClientServerDiagnostic(DiagnosticInfo info) { @Override protected boolean flagsCheck(CommonModule commonModule) { - return commonModule.isServer() && commonModule.isClientManagedApplication(); + return isClientServer(commonModule); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java index a3418f144c3..bd919182260 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java @@ -52,6 +52,6 @@ public CommonModuleNameGlobalClientDiagnostic(DiagnosticInfo info) { @Override protected boolean flagsCheck(CommonModule commonModule) { - return commonModule.isGlobal() && commonModule.isClientManagedApplication(); + return commonModule.isGlobal() && isClient(commonModule); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java index 8b4af0d9dcc..e4e19a93546 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java @@ -54,6 +54,6 @@ public CommonModuleNameServerCallDiagnostic(DiagnosticInfo info) { @Override protected boolean flagsCheck(CommonModule commonModule) { - return commonModule.isServer() && commonModule.isServerCall(); + return isServerCall(commonModule); } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java index ef4511bc442..a5817c271b6 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java @@ -74,6 +74,26 @@ void test() { } + @Test + void testClientServer() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТо"); + when(module.isServer()).thenReturn(Boolean.TRUE); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + @Test void testNegative() { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java index 2adfde03167..e0a12944271 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java @@ -61,6 +61,7 @@ void test() { when(module.getName()).thenReturn("ЧтоТо"); when(module.isServer()).thenReturn(Boolean.TRUE); when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + when(module.isExternalConnection()).thenReturn(Boolean.TRUE); when(documentContext.getMdObject()).thenReturn(Optional.of(module)); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java index eb4980d0cd5..de21b6c0bbe 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java @@ -61,6 +61,8 @@ void test() { when(module.getName()).thenReturn("ЧтоТоКлиентГлобальный"); when(module.isGlobal()).thenReturn(Boolean.TRUE); when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + when(module.isServerCall()).thenReturn(Boolean.FALSE); + when(module.isServer()).thenReturn(Boolean.FALSE); when(documentContext.getMdObject()).thenReturn(Optional.of(module)); @@ -83,6 +85,8 @@ void testEng() { when(module.getName()).thenReturn("ЧтоТоClientGlobal"); when(module.isGlobal()).thenReturn(Boolean.TRUE); when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + when(module.isServerCall()).thenReturn(Boolean.FALSE); + when(module.isServer()).thenReturn(Boolean.FALSE); when(documentContext.getMdObject()).thenReturn(Optional.of(module)); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java index eef9a811986..87c81347b70 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java @@ -60,7 +60,7 @@ void test() { // given when(module.getName()).thenReturn("ЧтоТо"); when(module.isServer()).thenReturn(Boolean.TRUE); - when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + when(module.isClientManagedApplication()).thenReturn(Boolean.FALSE); when(module.isServerCall()).thenReturn(Boolean.TRUE); when(documentContext.getMdObject()).thenReturn(Optional.of(module)); From 8907137dae159a7ca45f616e886c31ebcda566ec Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Wed, 13 May 2020 17:20:12 +0300 Subject: [PATCH 303/444] Update gradle.yml --- .github/workflows/gradle.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index dbb6080d29e..1a739d31b8a 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -8,7 +8,7 @@ jobs: strategy: fail-fast: false matrix: - java_version: ['11', '13'] + java_version: ['11', '14'] os: [ubuntu-latest, windows-latest, macOS-latest] steps: - uses: actions/checkout@v1 From 5e969f4d6c41cd44a0e6fbd39ecc2ec57bce32e5 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Wed, 13 May 2020 18:20:31 +0300 Subject: [PATCH 304/444] isClientOrdinaryApplication --- .../diagnostics/AbstractCommonModuleNameDiagnostic.java | 8 ++++---- .../diagnostics/CommonModuleNameClientDiagnosticTest.java | 1 + .../CommonModuleNameClientServerDiagnosticTest.java | 1 + .../CommonModuleNameGlobalClientDiagnosticTest.java | 2 ++ 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java index 58cf77773a6..1dc0b0a7081 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java @@ -65,7 +65,7 @@ protected static boolean isClientServer(CommonModule commonModule) { return !commonModule.isServerCall() && commonModule.isServer() && commonModule.isExternalConnection() -// && commonModule.isClientOrdinaryApplication() + && commonModule.isClientOrdinaryApplication() && commonModule.isClientManagedApplication(); } @@ -73,7 +73,7 @@ protected static boolean isClient(CommonModule commonModule) { return !commonModule.isServerCall() && !commonModule.isServer() && !commonModule.isExternalConnection() -// && commonModule.isClientOrdinaryApplication() + && commonModule.isClientOrdinaryApplication() && commonModule.isClientManagedApplication(); } @@ -81,7 +81,7 @@ protected static boolean isServerCall(CommonModule commonModule) { return commonModule.isServerCall() && commonModule.isServer() && !commonModule.isExternalConnection() -// && !commonModule.isClientOrdinaryApplication() + && !commonModule.isClientOrdinaryApplication() && !commonModule.isClientManagedApplication(); } @@ -89,7 +89,7 @@ protected static boolean isServer(CommonModule commonModule) { return !commonModule.isServerCall() && commonModule.isServer() && commonModule.isExternalConnection() -// && commonModule.isClientOrdinaryApplication() + && commonModule.isClientOrdinaryApplication() && !commonModule.isClientManagedApplication(); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java index a5817c271b6..3cdb88e9a4d 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java @@ -61,6 +61,7 @@ void test() { when(module.getName()).thenReturn("ЧтоТо"); when(module.isServer()).thenReturn(Boolean.FALSE); when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + when(module.isClientOrdinaryApplication()).thenReturn(Boolean.TRUE); when(documentContext.getMdObject()).thenReturn(Optional.of(module)); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java index e0a12944271..355ffe445b3 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java @@ -61,6 +61,7 @@ void test() { when(module.getName()).thenReturn("ЧтоТо"); when(module.isServer()).thenReturn(Boolean.TRUE); when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + when(module.isClientOrdinaryApplication()).thenReturn(Boolean.TRUE); when(module.isExternalConnection()).thenReturn(Boolean.TRUE); when(documentContext.getMdObject()).thenReturn(Optional.of(module)); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java index de21b6c0bbe..45bff436bd7 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java @@ -61,6 +61,7 @@ void test() { when(module.getName()).thenReturn("ЧтоТоКлиентГлобальный"); when(module.isGlobal()).thenReturn(Boolean.TRUE); when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + when(module.isClientOrdinaryApplication()).thenReturn(Boolean.TRUE); when(module.isServerCall()).thenReturn(Boolean.FALSE); when(module.isServer()).thenReturn(Boolean.FALSE); @@ -85,6 +86,7 @@ void testEng() { when(module.getName()).thenReturn("ЧтоТоClientGlobal"); when(module.isGlobal()).thenReturn(Boolean.TRUE); when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + when(module.isClientOrdinaryApplication()).thenReturn(Boolean.TRUE); when(module.isServerCall()).thenReturn(Boolean.FALSE); when(module.isServer()).thenReturn(Boolean.FALSE); From 73e094b3592c43cdadf55a22999041a05656a7c9 Mon Sep 17 00:00:00 2001 From: Alexey Sosnoviy Date: Wed, 13 May 2020 22:41:16 +0300 Subject: [PATCH 305/444] =?UTF-8?q?=D0=9D=D0=B5=D0=BE=D0=B1=D1=8F=D0=B7?= =?UTF-8?q?=D0=B0=D1=82=D0=B5=D0=BB=D1=8C=D0=BD=D0=BE=D1=81=D1=82=D1=8C=20?= =?UTF-8?q?isClientOrdinaryApplication?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractCommonModuleNameDiagnostic.java | 16 ++++--- .../CommonModuleNameClientDiagnosticTest.java | 25 ++++++++++ ...nModuleNameClientServerDiagnosticTest.java | 25 ++++++++++ ...monModuleNameServerCallDiagnosticTest.java | 46 +++++++++++++++++++ 4 files changed, 105 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java index 1dc0b0a7081..25616ecf4bb 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java @@ -65,32 +65,34 @@ protected static boolean isClientServer(CommonModule commonModule) { return !commonModule.isServerCall() && commonModule.isServer() && commonModule.isExternalConnection() - && commonModule.isClientOrdinaryApplication() - && commonModule.isClientManagedApplication(); + && isClientApplication(commonModule); } protected static boolean isClient(CommonModule commonModule) { return !commonModule.isServerCall() && !commonModule.isServer() && !commonModule.isExternalConnection() - && commonModule.isClientOrdinaryApplication() - && commonModule.isClientManagedApplication(); + && isClientApplication(commonModule); } protected static boolean isServerCall(CommonModule commonModule) { return commonModule.isServerCall() && commonModule.isServer() && !commonModule.isExternalConnection() - && !commonModule.isClientOrdinaryApplication() - && !commonModule.isClientManagedApplication(); + && !isClientApplication(commonModule); } protected static boolean isServer(CommonModule commonModule) { return !commonModule.isServerCall() && commonModule.isServer() && commonModule.isExternalConnection() - && commonModule.isClientOrdinaryApplication() +// && commonModule.isClientOrdinaryApplication() && !commonModule.isClientManagedApplication(); } + private static boolean isClientApplication(CommonModule commonModule) { + return commonModule.isClientOrdinaryApplication() + || commonModule.isClientManagedApplication(); + } + } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java index 3cdb88e9a4d..10830940b8a 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java @@ -75,6 +75,31 @@ void test() { } + @Test + void testClient() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТо"); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + when(module.isServer()).thenReturn(Boolean.FALSE); + when(module.isExternalConnection()).thenReturn(Boolean.FALSE); + when(module.isClientOrdinaryApplication()).thenReturn(Boolean.FALSE); + when(module.isServerCall()).thenReturn(Boolean.FALSE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(5, 0, 1); + + } + @Test void testClientServer() { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java index 355ffe445b3..f1223265d43 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java @@ -76,6 +76,31 @@ void test() { } + @Test + void testClientServer() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТо"); + when(module.isClientManagedApplication()).thenReturn(Boolean.TRUE); + when(module.isServer()).thenReturn(Boolean.TRUE); + when(module.isExternalConnection()).thenReturn(Boolean.TRUE); + when(module.isClientOrdinaryApplication()).thenReturn(Boolean.FALSE); + when(module.isServerCall()).thenReturn(Boolean.FALSE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(5, 0, 1); + + } + @Test void testNegative() { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java index 87c81347b70..6f78d4ff091 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnosticTest.java @@ -75,6 +75,52 @@ void test() { } + @Test + void testServer() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТо"); + when(module.isClientManagedApplication()).thenReturn(Boolean.FALSE); + when(module.isServer()).thenReturn(Boolean.TRUE); + when(module.isExternalConnection()).thenReturn(Boolean.TRUE); + when(module.isClientOrdinaryApplication()).thenReturn(Boolean.FALSE); + when(module.isServerCall()).thenReturn(Boolean.FALSE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(0); + + } + + @Test + void testServerCall() { + + getDocumentContextFromFile(); + + // given + when(module.getName()).thenReturn("ЧтоТо"); + when(module.isClientManagedApplication()).thenReturn(Boolean.FALSE); + when(module.isServer()).thenReturn(Boolean.TRUE); + when(module.isExternalConnection()).thenReturn(Boolean.FALSE); + when(module.isClientOrdinaryApplication()).thenReturn(Boolean.FALSE); + when(module.isServerCall()).thenReturn(Boolean.TRUE); + + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + // when + List diagnostics = diagnosticInstance.getDiagnostics(documentContext); + + //then + assertThat(diagnostics).hasSize(1); + + } + @Test void TestNegative() { From 4216938269de79bb1aae542fffc1de17125ec6a2 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Thu, 14 May 2020 08:52:24 +0300 Subject: [PATCH 306/444] =?UTF-8?q?=D0=9C=D0=B5=D0=BB=D0=BA=D0=B8=D0=B5=20?= =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/faq.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/faq.md b/docs/faq.md index 005218fe700..5b75b194307 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -2,21 +2,27 @@ В данном разделе собраны наиболее часто возникающие вопросы и ответы на них. -1. Как изменить язык диагностических сообщений +1. Как изменить язык диагностических сообщений? Для изменения языка выводимых сообщений с русского (по умолчанию) на английский можно с помощью конфигурационного файла. О возможностях конфигурирования можно узнать в [описании конфигурационного файла](features/ConfigurationFile.md) -2. Как увеличить максимальную длину строки в диагностике `Ограничение на длину строки` +2. Как увеличить максимальную длину строки в диагностике `Ограничение на длину строки`? Все диагностики имеет страницу с описанием в разделе `Диагностики`, например интересующая [Ограничение на длину строки](diagnostics/LineLength.md). Если диагностика может менять свое поведение, то на странице с описанием будут присутствовать параметры с описанием, на что они влияют. В данном случае - параметр `maxLineLength` как раз и отвечает за максимальную длину строки. -3. Как отключить Lens о когнитивной диагностики +3. Как отключить Lens о когнитивной диагностики? Для отключения `линзы` с информацией о когнитивной сложности стоит воспользоваться конфигурационным файлом, в котором для параметра `showCognitiveComplexity` установить значение `false`. О возможностях конфигурирования можно узнать в [описании конфигурационного файла](features/ConfigurationFile.md) -4. Я считаю, что диагностика работает неправильно. Что делать +4. Я считаю, что диагностика работает неправильно. Что делать? В случае сомнения (или уверенности) в том, что диагностика работает неверно есть два пути - обратиться в чате [telegram](https://t.me/bsl_language_server) с ситуацией, возможно все-таки ошибки нет - создать ишью ([issue](https://github.com/1c-syntax/bsl-language-server/issues)) в репозитории проекта соответствующего типа, куда приложить описание ошибки и, очень желательно, примеры кода, где диагностика работает неверно. + +5. `BSL Language Server` и SonarQube плагин это одно и тоже? + +`BSL Language Server` является самостоятельным приложением, реализацией серверной части протокола LSP. Плагин для SonarQube использует `BSL Language Server` для выполнения анализа исходного кода языка BSL (конфигурации 1С, скрипты 1Scipt и OSWeb). + +`BSL Language Server` может быть использован с любым приложением, имеющим реализацию LSP клиента, на данный момент это плагины для [VS code](https://github.com/1c-syntax/vsc-language-1c-bsl/), [1C:Enterprise development tools](https://github.com/DoublesunRUS/ru.capralow.dt.bslls.validator) (собственная реализация, без LSP), плагин для [SonarQube](https://github.com/1c-syntax/sonar-bsl-plugin-community), [Phoenix BSL](https://github.com/otymko/phoenixbsl) From bc118c2d7aac45c5ac92edcefe5d1c83c1cf9b1d Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Thu, 14 May 2020 09:56:34 +0300 Subject: [PATCH 307/444] #566 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Диагностики UsingModalWindows и UsingSynchronousCalls стали использовать соответствующие флаги --- docs/diagnostics/UsingModalWindows.md | 2 +- docs/diagnostics/UsingSynchronousCalls.md | 2 +- docs/diagnostics/index.md | 4 +- docs/en/diagnostics/UsingModalWindows.md | 2 +- docs/en/diagnostics/UsingSynchronousCalls.md | 2 +- docs/en/diagnostics/index.md | 4 +- .../UsingModalWindowsDiagnostic.java | 13 +++++- .../UsingSynchronousCallsDiagnostic.java | 13 +++++- .../configuration/parameters-schema.json | 6 +-- .../UsingModalWindowsDiagnosticTest.java | 41 ++++++++++++++++++- .../UsingSynchronousCallsDiagnosticTest.java | 41 ++++++++++++++++++- 11 files changed, 111 insertions(+), 19 deletions(-) diff --git a/docs/diagnostics/UsingModalWindows.md b/docs/diagnostics/UsingModalWindows.md index 31b9631f038..5a55f7e351c 100644 --- a/docs/diagnostics/UsingModalWindows.md +++ b/docs/diagnostics/UsingModalWindows.md @@ -2,7 +2,7 @@ | Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Дефект кода` | `BSL` | `Важный` | `Нет` | `15` | `standard` | +| `Дефект кода` | `BSL` | `Важный` | `Да` | `15` | `standard` | ## Описание диагностики diff --git a/docs/diagnostics/UsingSynchronousCalls.md b/docs/diagnostics/UsingSynchronousCalls.md index e62a9a4007d..746f13e692e 100644 --- a/docs/diagnostics/UsingSynchronousCalls.md +++ b/docs/diagnostics/UsingSynchronousCalls.md @@ -2,7 +2,7 @@ | Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Дефект кода` | `BSL` | `Важный` | `Нет` | `15` | `standard` | +| `Дефект кода` | `BSL` | `Важный` | `Да` | `15` | `standard` | ## Описание диагностики diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index ad208c20421..a3dcc1c89c6 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -117,10 +117,10 @@ | [UsingHardcodeNetworkAddress](UsingHardcodeNetworkAddress.md) | Хранение ip-адресов в коде | Да | Критичный | Уязвимость | `standard` | | [UsingHardcodePath](UsingHardcodePath.md) | Хранение путей к файлам в коде | Да | Критичный | Ошибка | `standard` | | [UsingHardcodeSecretInformation](UsingHardcodeSecretInformation.md) | Хранение конфиденциальной информации в коде | Да | Критичный | Уязвимость | `standard` | -| [UsingModalWindows](UsingModalWindows.md) | Использование модальных окон | Нет | Важный | Дефект кода | `standard` | +| [UsingModalWindows](UsingModalWindows.md) | Использование модальных окон | Да | Важный | Дефект кода | `standard` | | [UsingObjectNotAvailableUnix](UsingObjectNotAvailableUnix.md) | Использование объектов недоступных в Unix системах | Да | Критичный | Ошибка | `standard`
`lockinos` | | [UsingServiceTag](UsingServiceTag.md) | Использование служебных тегов | Да | Информационный | Дефект кода | `badpractice` | -| [UsingSynchronousCalls](UsingSynchronousCalls.md) | Использование синхронных вызовов | Нет | Важный | Дефект кода | `standard` | +| [UsingSynchronousCalls](UsingSynchronousCalls.md) | Использование синхронных вызовов | Да | Важный | Дефект кода | `standard` | | [UsingThisForm](UsingThisForm.md) | Использование устаревшего свойства "ЭтаФорма" | Да | Незначительный | Дефект кода | `standard`
`deprecated` | | [WrongUseOfRollbackTransactionMethod](WrongUseOfRollbackTransactionMethod.md) | Некорректное использование метода ОтменитьТранзакцию() | Да | Критичный | Ошибка | `standard` | | [YoLetterUsage](YoLetterUsage.md) | Использование буквы "ё" в текстах модулей | Да | Информационный | Дефект кода | `standard` | \ No newline at end of file diff --git a/docs/en/diagnostics/UsingModalWindows.md b/docs/en/diagnostics/UsingModalWindows.md index 4cce7608c10..35343337293 100644 --- a/docs/en/diagnostics/UsingModalWindows.md +++ b/docs/en/diagnostics/UsingModalWindows.md @@ -2,7 +2,7 @@ | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Code smell` | `BSL` | `Major` | `No` | `15` | `standard` | +| `Code smell` | `BSL` | `Major` | `Yes` | `15` | `standard` | ## Description diff --git a/docs/en/diagnostics/UsingSynchronousCalls.md b/docs/en/diagnostics/UsingSynchronousCalls.md index fa7d3f40018..b188c7e3f51 100644 --- a/docs/en/diagnostics/UsingSynchronousCalls.md +++ b/docs/en/diagnostics/UsingSynchronousCalls.md @@ -2,7 +2,7 @@ | Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | | :-: | :-: | :-: | :-: | :-: | :-: | -| `Code smell` | `BSL` | `Major` | `No` | `15` | `standard` | +| `Code smell` | `BSL` | `Major` | `Yes` | `15` | `standard` | ## Description diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 1ab3ba79e4e..8a8975e2b02 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -117,10 +117,10 @@ Total: **107** | [UsingHardcodeNetworkAddress](UsingHardcodeNetworkAddress.md) | Using hardcode ip addresses in code | Yes | Critical | Vulnerability | `standard` | | [UsingHardcodePath](UsingHardcodePath.md) | Using hardcode file paths in code | Yes | Critical | Error | `standard` | | [UsingHardcodeSecretInformation](UsingHardcodeSecretInformation.md) | Storing confidential information in code | Yes | Critical | Vulnerability | `standard` | -| [UsingModalWindows](UsingModalWindows.md) | Using modal windows | No | Major | Code smell | `standard` | +| [UsingModalWindows](UsingModalWindows.md) | Using modal windows | Yes | Major | Code smell | `standard` | | [UsingObjectNotAvailableUnix](UsingObjectNotAvailableUnix.md) | Using unavailable in Unix objects | Yes | Critical | Error | `standard`
`lockinos` | | [UsingServiceTag](UsingServiceTag.md) | Using service tags | Yes | Info | Code smell | `badpractice` | -| [UsingSynchronousCalls](UsingSynchronousCalls.md) | Using synchronous calls | No | Major | Code smell | `standard` | +| [UsingSynchronousCalls](UsingSynchronousCalls.md) | Using synchronous calls | Yes | Major | Code smell | `standard` | | [UsingThisForm](UsingThisForm.md) | Using deprecated property "ThisForm" | Yes | Minor | Code smell | `standard`
`deprecated` | | [WrongUseOfRollbackTransactionMethod](WrongUseOfRollbackTransactionMethod.md) | Not recommended using of RollbackTransaction method | Yes | Critical | Error | `standard` | | [YoLetterUsage](YoLetterUsage.md) | Using Russian character "yo" ("ё") in code | Yes | Info | Code smell | `standard` | \ No newline at end of file diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnostic.java index ebc25f7e5e2..ace9daa0e4e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnostic.java @@ -21,6 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCompatibilityMode; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; @@ -28,6 +29,7 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.mdclasses.metadata.additional.UseMode; import org.antlr.v4.runtime.tree.ParseTree; import java.util.HashMap; @@ -39,10 +41,10 @@ severity = DiagnosticSeverity.MAJOR, scope = DiagnosticScope.BSL, minutesToFix = 15, - activatedByDefault = false, tags = { DiagnosticTag.STANDARD - } + }, + compatibilityMode = DiagnosticCompatibilityMode.COMPATIBILITY_MODE_8_3_3 ) public class UsingModalWindowsDiagnostic extends AbstractVisitorDiagnostic { @@ -86,6 +88,13 @@ public UsingModalWindowsDiagnostic(DiagnosticInfo info) { @Override public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { + var configuration = documentContext.getServerContext().getConfiguration(); + // если использование модальных окон разрешено (без предупреждение), то + // ничего не диагностируется + if (configuration.getModalityUseMode() == UseMode.USE) { + return ctx; + } + String methodName = ctx.methodName().getText(); if (modalityMethods.matcher(methodName).matches()) { diagnosticStorage.addDiagnostic(ctx, diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnostic.java index 76dd40a94f0..e7645bc2f4e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnostic.java @@ -21,6 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCompatibilityMode; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; @@ -29,6 +30,7 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.utils.Trees; import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.mdclasses.metadata.additional.UseMode; import org.antlr.v4.runtime.tree.ParseTree; import java.util.HashMap; @@ -40,10 +42,10 @@ severity = DiagnosticSeverity.MAJOR, scope = DiagnosticScope.BSL, minutesToFix = 15, - activatedByDefault = false, tags = { DiagnosticTag.STANDARD - } + }, + compatibilityMode = DiagnosticCompatibilityMode.COMPATIBILITY_MODE_8_3_3 ) public class UsingSynchronousCallsDiagnostic extends AbstractVisitorDiagnostic { private static final Pattern MODALITY_METHODS = Pattern.compile( @@ -124,6 +126,13 @@ public UsingSynchronousCallsDiagnostic(DiagnosticInfo info) { @Override public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { + var configuration = documentContext.getServerContext().getConfiguration(); + // если использование синхронных вызовов разрешено (без предупреждение), то + // ничего не диагностируется + if (configuration.getSynchronousExtensionAndAddInCallUseMode() == UseMode.USE) { + return ctx; + } + String methodName = ctx.methodName().getText(); if (MODALITY_METHODS.matcher(methodName).matches()) { BSLParser.SubContext rootParent = (BSLParser.SubContext) Trees.getRootParent(ctx, BSLParser.RULE_sub); diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index f54eec0b8d4..eb2089cc696 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -197,7 +197,7 @@ "properties": { "words": { "description": "Unrecommended words", - "default": "", + "default": "\u043f\u0440\u043e\u0446\u0435\u0434\u0443\u0440\u044b|procedures|\u0444\u0443\u043d\u043a\u0446\u0438\u0438|functions|\u043e\u0431\u0440\u0430\u0431\u043e\u0442\u0447\u0438\u043a\u0438|handlers|\u043c\u043e\u0434\u0443\u043b\u044c|module|\u0444\u0443\u043d\u043a\u0446\u0438\u043e\u043d\u0430\u043b\u044c\u043d\u043e\u0441\u0442\u044c|functionality", "type": "string", "title": "Unrecommended words" } @@ -1292,7 +1292,7 @@ }, "UsingModalWindows": { "description": "Using modal windows", - "default": false, + "default": true, "type": [ "boolean", "object" @@ -1330,7 +1330,7 @@ }, "UsingSynchronousCalls": { "description": "Using synchronous calls", - "default": false, + "default": true, "type": [ "boolean", "object" diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnosticTest.java index 40445f36f52..683755ad385 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnosticTest.java @@ -21,22 +21,34 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.ServerContext; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.mdclasses.metadata.additional.UseMode; +import com.github._1c_syntax.utils.Absolute; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; +import java.nio.file.Paths; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; class UsingModalWindowsDiagnosticTest extends AbstractDiagnosticTest { UsingModalWindowsDiagnosticTest() { super(UsingModalWindowsDiagnostic.class); } + private static final String PATH_TO_METADATA = "src/test/resources/metadata"; + private static final String PATH_TO_MODULE_FILE = "src/test/resources/metadata/CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; + @Test - void test() { - List diagnostics = getDiagnostics(); + void testDontUse() { + + var documentContext = getDocumentContextWithUseFlag(UseMode.DONT_USE); + List diagnostics = getDiagnostics(documentContext); assertThat(diagnostics).hasSize(12); assertThat(diagnostics) @@ -65,5 +77,30 @@ void test() { .anyMatch(diagnostic -> diagnostic.getRange().equals(Ranges.create(186, 4, 186, 88)) && diagnostic.getMessage().matches(".*(модального|modal).*ПоместитьФайл.*НачатьПомещениеФайла.*")); } + + @Test + void testUse() { + + DocumentContext documentContext = getDocumentContextWithUseFlag(UseMode.USE); + List diagnostics = getDiagnostics(documentContext); + assertThat(diagnostics).hasSize(0); + } + + private DocumentContext getDocumentContextWithUseFlag(UseMode useMode) { + var path = Absolute.path(PATH_TO_METADATA); + var testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + + var serverContext = spy(new ServerContext(path)); + var configuration = spy(serverContext.getConfiguration()); + when(configuration.getModalityUseMode()).thenReturn(useMode); + when(serverContext.getConfiguration()).thenReturn(configuration); + + return new DocumentContext( + testFile.toUri(), + getText(), + serverContext + ); + } + } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnosticTest.java index 2096fa3d0d7..f14aa789dcf 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnosticTest.java @@ -21,22 +21,34 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.ServerContext; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.mdclasses.metadata.additional.UseMode; +import com.github._1c_syntax.utils.Absolute; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; +import java.nio.file.Paths; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; class UsingSynchronousCallsDiagnosticTest extends AbstractDiagnosticTest { UsingSynchronousCallsDiagnosticTest() { super(UsingSynchronousCallsDiagnostic.class); } + private static final String PATH_TO_METADATA = "src/test/resources/metadata"; + private static final String PATH_TO_MODULE_FILE = "src/test/resources/metadata/CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; + @Test - void test() { - List diagnostics = getDiagnostics(); + void testDontUse() { + + var documentContext = getDocumentContextWithUseFlag(UseMode.DONT_USE); + List diagnostics = getDiagnostics(documentContext); assertThat(diagnostics).hasSize(28); assertThat(diagnostics) @@ -97,4 +109,29 @@ void test() { .anyMatch(diagnostic -> diagnostic.getRange().equals(Ranges.create(391, 4, 391, 38)) && diagnostic.getMessage().matches(".*(синхронного|synchronous).*ЗапуститьПриложение.*НачатьЗапускПриложения.*")); } + + @Test + void testUse() { + + DocumentContext documentContext = getDocumentContextWithUseFlag(UseMode.USE); + List diagnostics = getDiagnostics(documentContext); + assertThat(diagnostics).hasSize(0); + } + + private DocumentContext getDocumentContextWithUseFlag(UseMode useMode) { + var path = Absolute.path(PATH_TO_METADATA); + var testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + + var serverContext = spy(new ServerContext(path)); + var configuration = spy(serverContext.getConfiguration()); + when(configuration.getSynchronousExtensionAndAddInCallUseMode()).thenReturn(useMode); + when(serverContext.getConfiguration()).thenReturn(configuration); + + return new DocumentContext( + testFile.toUri(), + getText(), + serverContext + ); + } + } From 9837bd2a0856c86c62161db75239fbb15ea1c447 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Thu, 14 May 2020 12:47:53 +0300 Subject: [PATCH 308/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D1=8B=20=D0=B4=D0=B8=D0=B0=D0=B3=D0=BD=D0=BE=D1=81?= =?UTF-8?q?=D1=82=D0=B8=D0=BA=D0=B8=20=D0=BD=D0=B0=20=D0=B8=D1=81=D0=BF?= =?UTF-8?q?=D0=BE=D0=BB=D0=BD=D1=8F=D0=B5=D0=BC=D1=8B=D0=B9=20=D0=BD=D0=B0?= =?UTF-8?q?=20=D1=81=D0=B5=D1=80=D0=B2=D0=B5=D1=80=D0=B5=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/ExecuteExternalCode.md | 43 +++++++++ .../ExecuteExternalCodeInCommonModule.md | 43 +++++++++ docs/diagnostics/index.md | 6 +- docs/en/diagnostics/ExecuteExternalCode.md | 36 +++++++ .../ExecuteExternalCodeInCommonModule.md | 36 +++++++ docs/en/diagnostics/index.md | 6 +- ...AbstractExecuteExternalCodeDiagnostic.java | 57 +++++++++++ .../ExecuteExternalCodeDiagnostic.java | 87 +++++++++++++++++ ...eExternalCodeInCommonModuleDiagnostic.java | 68 +++++++++++++ .../bsl/languageserver/utils/Keywords.java | 2 + .../configuration/parameters-schema.json | 20 ++++ .../languageserver/configuration/schema.json | 6 ++ ...xecuteExternalCodeDiagnostic_en.properties | 2 + ...xecuteExternalCodeDiagnostic_ru.properties | 2 + ...CodeInCommonModuleDiagnostic_en.properties | 2 + ...CodeInCommonModuleDiagnostic_ru.properties | 2 + .../ExecuteExternalCodeDiagnosticTest.java | 51 ++++++++++ ...ernalCodeInCommonModuleDiagnosticTest.java | 96 +++++++++++++++++++ .../ExecuteExternalCodeDiagnostic.bsl | 33 +++++++ ...teExternalCodeInCommonModuleDiagnostic.bsl | 12 +++ 20 files changed, 606 insertions(+), 4 deletions(-) create mode 100644 docs/diagnostics/ExecuteExternalCode.md create mode 100644 docs/diagnostics/ExecuteExternalCodeInCommonModule.md create mode 100644 docs/en/diagnostics/ExecuteExternalCode.md create mode 100644 docs/en/diagnostics/ExecuteExternalCodeInCommonModule.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractExecuteExternalCodeDiagnostic.java create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnostic.java create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnostic_ru.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnosticTest.java create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/ExecuteExternalCodeDiagnostic.bsl create mode 100644 src/test/resources/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.bsl diff --git a/docs/diagnostics/ExecuteExternalCode.md b/docs/diagnostics/ExecuteExternalCode.md new file mode 100644 index 00000000000..c68e6c22604 --- /dev/null +++ b/docs/diagnostics/ExecuteExternalCode.md @@ -0,0 +1,43 @@ +# Выполнение произвольного кода на сервере (ExecuteExternalCode) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Уязвимость` | `BSL` | `Критичный` | `Да` | `1` | `error`
`standard` | + + +## Описание диагностики + + +При разработке решений следует учитывать, что опасно использование не только непосредственного выполнения кода, написанного в режиме Предприятие, но и алгоритмов, где методами `Выполнить` или `Вычислить` исполняется код в серверных функциях и процедурах. +Запрещено использование методов `Выполнить` и `Вычислить` в серверных методах модулей форм, команд, объектов и т.д. + +**Ограничение не распространяется на код, выполняемый на клиенте.** + +## Примеры + + +## Источники + + + +* [Ограничения на использование Выполнить и Вычислить на сервере](https://its.1c.ru/db/v8std#content:770:hdoc) + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:ExecuteExternalCode-off +// BSLLS:ExecuteExternalCode-on +``` + +### Параметр конфигурационного файла + +```json +"ExecuteExternalCode": false +``` diff --git a/docs/diagnostics/ExecuteExternalCodeInCommonModule.md b/docs/diagnostics/ExecuteExternalCodeInCommonModule.md new file mode 100644 index 00000000000..23d931e886f --- /dev/null +++ b/docs/diagnostics/ExecuteExternalCodeInCommonModule.md @@ -0,0 +1,43 @@ +# Выполнение произвольного кода в общем модуле на сервере (ExecuteExternalCodeInCommonModule) + +| Тип | Поддерживаются
языки | Важность | Включена
по умолчанию | Время на
исправление (мин) | Тэги | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Потенциальная уязвимость` | `BSL` | `Критичный` | `Да` | `15` | `badpractice`
`standard` | + + +## Описание диагностики + + +При разработке решений следует учитывать, что опасно использование не только непосредственного выполнения кода, написанного в режиме Предприятие, но и алгоритмов, где методами `Выполнить` или `Вычислить` исполняется код в серверных функциях и процедурах. +Если выполнение произвольного кода необходимо, то такой код должен предварительно располагаться в общем модуле и пройти аудит. + +**Ограничение не распространяется на код, выполняемый на клиенте.** + +## Примеры + + +## Источники + + + +* [Ограничения на использование Выполнить и Вычислить на сервере](https://its.1c.ru/db/v8std#content:770:hdoc) + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:ExecuteExternalCodeInCommonModule-off +// BSLLS:ExecuteExternalCodeInCommonModule-on +``` + +### Параметр конфигурационного файла + +```json +"ExecuteExternalCodeInCommonModule": false +``` diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index 1f8526ece6e..a653372432c 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -11,9 +11,9 @@ Общее количество: **108** * Дефект кода: **69** -* Уязвимость: **2** +* Уязвимость: **3** * Ошибка: **34** -* Потенциальная уязвимость: **3** +* Потенциальная уязвимость: **4** | Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги | | --- | --- | :-: | --- | --- | --- | @@ -54,6 +54,8 @@ | [EmptyRegion](EmptyRegion.md) | Область не должна быть пустой | Да | Информационный | Дефект кода | `standard` | | [EmptyStatement](EmptyStatement.md) | Пустой оператор | Да | Информационный | Дефект кода | `badpractice` | | [ExcessiveAutoTestCheck](ExcessiveAutoTestCheck.md) | Избыточная проверка параметра АвтоТест | Да | Незначительный | Дефект кода | `standard`
`deprecated` | +| [ExecuteExternalCode](ExecuteExternalCode.md) | Выполнение произвольного кода на сервере | Да | Критичный | Уязвимость | `error`
`standard` | +| [ExecuteExternalCodeInCommonModule](ExecuteExternalCodeInCommonModule.md) | Выполнение произвольного кода в общем модуле на сервере | Да | Критичный | Потенциальная уязвимость | `badpractice`
`standard` | | [ExtraCommas](ExtraCommas.md) | Запятые без указания параметра в конце вызова метода | Да | Важный | Дефект кода | `standard`
`badpractice` | | [FormDataToValue](FormDataToValue.md) | Использование метода ДанныеФормыВЗначение | Да | Информационный | Дефект кода | `badpractice` | | [FunctionNameStartsWithGet](FunctionNameStartsWithGet.md) | Имя функции не должно начинаться с "Получить" | Нет | Информационный | Дефект кода | `standard` | diff --git a/docs/en/diagnostics/ExecuteExternalCode.md b/docs/en/diagnostics/ExecuteExternalCode.md new file mode 100644 index 00000000000..678a7df908b --- /dev/null +++ b/docs/en/diagnostics/ExecuteExternalCode.md @@ -0,0 +1,36 @@ +# Executing of external code on the server (ExecuteExternalCode) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Vulnerability` | `BSL` | `Critical` | `Yes` | `1` | `error`
`standard` | + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:ExecuteExternalCode-off +// BSLLS:ExecuteExternalCode-on +``` + +### Parameter for config + +```json +"ExecuteExternalCode": false +``` diff --git a/docs/en/diagnostics/ExecuteExternalCodeInCommonModule.md b/docs/en/diagnostics/ExecuteExternalCodeInCommonModule.md new file mode 100644 index 00000000000..e70751a4e9a --- /dev/null +++ b/docs/en/diagnostics/ExecuteExternalCodeInCommonModule.md @@ -0,0 +1,36 @@ +# Executing of external code in a common module on the server (ExecuteExternalCodeInCommonModule) + +| Type | Scope | Severity | Activated
by default | Minutes
to fix | Tags | +| :-: | :-: | :-: | :-: | :-: | :-: | +| `Security Hotspot` | `BSL` | `Critical` | `Yes` | `15` | `badpractice`
`standard` | + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:ExecuteExternalCodeInCommonModule-off +// BSLLS:ExecuteExternalCodeInCommonModule-on +``` + +### Parameter for config + +```json +"ExecuteExternalCodeInCommonModule": false +``` diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 3db8aec78ff..0ceefdfe898 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -12,8 +12,8 @@ Total: **108** * Error: **34** * Code smell: **69** -* Vulnerability: **2** -* Security Hotspot: **3** +* Vulnerability: **3** +* Security Hotspot: **4** | Key | Name| Enabled by default | Severity | Type | Tags | | --- | --- | :-: | --- | --- | --- | @@ -54,6 +54,8 @@ Total: **108** | [EmptyRegion](EmptyRegion.md) | The region should not be empty | Yes | Info | Code smell | `standard` | | [EmptyStatement](EmptyStatement.md) | Empty statement | Yes | Info | Code smell | `badpractice` | | [ExcessiveAutoTestCheck](ExcessiveAutoTestCheck.md) | Excessive AutoTest Check | Yes | Minor | Code smell | `standard`
`deprecated` | +| [ExecuteExternalCode](ExecuteExternalCode.md) | Executing of external code on the server | Yes | Critical | Vulnerability | `error`
`standard` | +| [ExecuteExternalCodeInCommonModule](ExecuteExternalCodeInCommonModule.md) | Executing of external code in a common module on the server | Yes | Critical | Security Hotspot | `badpractice`
`standard` | | [ExtraCommas](ExtraCommas.md) | Commas without a parameter at the end of a method call | Yes | Major | Code smell | `standard`
`badpractice` | | [FormDataToValue](FormDataToValue.md) | FormDataToValue method call | Yes | Info | Code smell | `badpractice` | | [FunctionNameStartsWithGet](FunctionNameStartsWithGet.md) | Function name shouldn't start with "Получить" | No | Info | Code smell | `standard` | diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractExecuteExternalCodeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractExecuteExternalCodeDiagnostic.java new file mode 100644 index 00000000000..d7da12a239e --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractExecuteExternalCodeDiagnostic.java @@ -0,0 +1,57 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.utils.Keywords; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.utils.CaseInsensitivePattern; +import org.antlr.v4.runtime.tree.ParseTree; + +import java.util.Optional; +import java.util.regex.Pattern; + +abstract class AbstractExecuteExternalCodeDiagnostic extends AbstractVisitorDiagnostic { + + private static final Pattern EVAL_METHOD_NAME = CaseInsensitivePattern.compile( + String.format("^(%s|%s)$", Keywords.EVAL_EN, Keywords.EVAL_RU)); + + public AbstractExecuteExternalCodeDiagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + public ParseTree visitExecuteStatement(BSLParser.ExecuteStatementContext ctx) { + diagnosticStorage.addDiagnostic(ctx); + return super.visitExecuteStatement(ctx); + } + + @Override + public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { + Optional.of(ctx) + .filter(it -> EVAL_METHOD_NAME.matcher(it.methodName().getText()).matches()) + .ifPresent(diagnosticStorage::addDiagnostic); + + return super.visitGlobalMethodCall(ctx); + } + +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnostic.java new file mode 100644 index 00000000000..a7686c23de9 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnostic.java @@ -0,0 +1,87 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; +import org.antlr.v4.runtime.tree.ParseTree; + +@DiagnosticMetadata( + type = DiagnosticType.VULNERABILITY, + severity = DiagnosticSeverity.CRITICAL, + minutesToFix = 1, + scope = DiagnosticScope.BSL, + tags = { + DiagnosticTag.ERROR, + DiagnosticTag.STANDARD + }, + modules = { + ModuleType.CommandModule, + ModuleType.ExternalConnectionModule, + ModuleType.FormModule, + ModuleType.HTTPServiceModule, + ModuleType.ObjectModule, + ModuleType.OrdinaryApplicationModule, + ModuleType.RecordSetModule, + ModuleType.ValueManagerModule, + ModuleType.WEBServiceModule, + ModuleType.SessionModule + } +) +public class ExecuteExternalCodeDiagnostic extends AbstractExecuteExternalCodeDiagnostic { + + public ExecuteExternalCodeDiagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + public ParseTree visitFunction(BSLParser.FunctionContext ctx) { + + // если только клиентская аннотация, тогда ничего не делаем + if (ctx.funcDeclaration().compilerDirective().stream() + .anyMatch(compilerDirectiveContext + -> compilerDirectiveContext.getStop().getType() == BSLParser.ANNOTATION_ATCLIENT_SYMBOL)) { + return ctx; + } + + return super.visitFunction(ctx); + } + + @Override + public ParseTree visitProcedure(BSLParser.ProcedureContext ctx) { + + // если только клиентская аннотация, тогда ничего не делаем + if (ctx.procDeclaration().compilerDirective().stream() + .anyMatch(compilerDirectiveContext + -> compilerDirectiveContext.getStop().getType() == BSLParser.ANNOTATION_ATCLIENT_SYMBOL)) { + return ctx; + } + + return super.visitProcedure(ctx); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.java new file mode 100644 index 00000000000..bb80c0568ef --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.java @@ -0,0 +1,68 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; +import org.antlr.v4.runtime.tree.ParseTree; + +@DiagnosticMetadata( + type = DiagnosticType.SECURITY_HOTSPOT, + severity = DiagnosticSeverity.CRITICAL, + minutesToFix = 15, + scope = DiagnosticScope.BSL, + tags = { + DiagnosticTag.BADPRACTICE, + DiagnosticTag.STANDARD + }, + modules = { + ModuleType.CommonModule + } +) +public class ExecuteExternalCodeInCommonModuleDiagnostic extends AbstractExecuteExternalCodeDiagnostic { + public ExecuteExternalCodeInCommonModuleDiagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + public ParseTree visitFile(BSLParser.FileContext ctx) { + // если модуль не серверный, не внешнее соединение и не обычный клиент, то не проверяем + if (documentContext.getMdObject() + .filter(CommonModule.class::isInstance) + .map(CommonModule.class::cast) + .filter(commonModule -> commonModule.isServer() + || commonModule.isClientOrdinaryApplication() + || commonModule.isExternalConnection()) + .isEmpty()) { + return ctx; + } + + return super.visitFile(ctx); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Keywords.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Keywords.java index eab018bf849..7998516b8c8 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Keywords.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Keywords.java @@ -151,6 +151,8 @@ public final class Keywords { public static final String EXECUTE_UP_RU = "ВЫПОЛНИТЬ"; public static final String EXECUTE_EN = "Execute"; public static final String EXECUTE_UP_EN = "EXECUTE"; + public static final String EVAL_RU = "Вычислить"; + public static final String EVAL_EN = "Eval"; public static final String ADD_HANDLER_RU = "ДобавитьОбработчик"; public static final String ADD_HANDLER_UP_RU = "ДОБАВИТЬОБРАБОТЧИК"; public static final String ADD_HANDLER_EN = "AddHandler"; diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index 41fc71b7ad0..b8bc8634d20 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -442,6 +442,26 @@ "title": "Excessive AutoTest Check", "$id": "#/definitions/ExcessiveAutoTestCheck" }, + "ExecuteExternalCode": { + "description": "Executing of external code on the server", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Executing of external code on the server", + "$id": "#/definitions/ExecuteExternalCode" + }, + "ExecuteExternalCodeInCommonModule": { + "description": "Executing of external code in a common module on the server", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Executing of external code in a common module on the server", + "$id": "#/definitions/ExecuteExternalCodeInCommonModule" + }, "ExtraCommas": { "description": "Commas without a parameter at the end of a method call", "default": true, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index a7cdcb33a0e..153fd814a0f 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -134,6 +134,12 @@ "ExcessiveAutoTestCheck": { "$ref": "parameters-schema.json#/definitions/ExcessiveAutoTestCheck" }, + "ExecuteExternalCode": { + "$ref": "parameters-schema.json#/definitions/ExecuteExternalCode" + }, + "ExecuteExternalCodeInCommonModule": { + "$ref": "parameters-schema.json#/definitions/ExecuteExternalCodeInCommonModule" + }, "ExtraCommas": { "$ref": "parameters-schema.json#/definitions/ExtraCommas" }, diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnostic_en.properties new file mode 100644 index 00000000000..f9daa82b245 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=It is forbidden to execute external code on the server +diagnosticName=Executing of external code on the server diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnostic_ru.properties new file mode 100644 index 00000000000..79fa02fac93 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Запрещено выполнение произвольного кода на сервере +diagnosticName=Выполнение произвольного кода на сервере diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic_en.properties new file mode 100644 index 00000000000..6b8e3bef996 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Execution of external code in a common module on a server is a potential vulnerability +diagnosticName=Executing of external code in a common module on the server \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic_ru.properties new file mode 100644 index 00000000000..caf27d928cf --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Выполнение произвольного кода в общем модуле на сервере является потенциальной уязвимостью +diagnosticName=Выполнение произвольного кода в общем модуле на сервере diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnosticTest.java new file mode 100644 index 00000000000..44564af3a3e --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnosticTest.java @@ -0,0 +1,51 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class ExecuteExternalCodeDiagnosticTest extends AbstractDiagnosticTest { + ExecuteExternalCodeDiagnosticTest() { + super(ExecuteExternalCodeDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(5); + assertThat(diagnostics, true) + .hasRange(8, 4, 21) + .hasRange(13, 4, 21) + .hasRange(18, 12, 29) + .hasRange(23, 12, 29) + .hasRange(31, 12, 29) + ; + + } +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnosticTest.java new file mode 100644 index 00000000000..ff2fdf640f1 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnosticTest.java @@ -0,0 +1,96 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.ServerContext; +import com.github._1c_syntax.mdclasses.mdo.CommonModule; +import com.github._1c_syntax.utils.Absolute; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.nio.file.Paths; +import java.util.List; +import java.util.Optional; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +class ExecuteExternalCodeInCommonModuleDiagnosticTest extends AbstractDiagnosticTest { + ExecuteExternalCodeInCommonModuleDiagnosticTest() { + super(ExecuteExternalCodeInCommonModuleDiagnostic.class); + } + + private static final String PATH_TO_METADATA = "src/test/resources/metadata"; + private static final String PATH_TO_MODULE_FILE = "src/test/resources/metadata/CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; + + private CommonModule module; + private DocumentContext documentContext; + + @Test + void testIsServer() { + + getDocumentContextFromFile(); + when(module.isServer()).thenReturn(Boolean.TRUE); + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + List diagnostics = getDiagnostics(documentContext); + + assertThat(diagnostics).hasSize(2); + assertThat(diagnostics, true) + .hasRange(2, 4, 21) + .hasRange(6, 12, 29) + ; + } + + @Test + void testIsNonServer() { + + getDocumentContextFromFile(); + when(module.isServer()).thenReturn(Boolean.FALSE); + when(module.isClientOrdinaryApplication()).thenReturn(Boolean.FALSE); + when(module.isExternalConnection()).thenReturn(Boolean.FALSE); + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + List diagnostics = getDiagnostics(documentContext); + + assertThat(diagnostics).isEmpty(); + } + + private void getDocumentContextFromFile() { + var path = Absolute.path(PATH_TO_METADATA); + var testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + + var serverContext = new ServerContext(path); + var configuration = spy(serverContext.getConfiguration()); + + documentContext = spy(new DocumentContext( + testFile.toUri(), + getText(), + serverContext + )); + + module = spy((CommonModule) configuration.getModulesByURI().get(documentContext.getUri())); + + } +} diff --git a/src/test/resources/diagnostics/ExecuteExternalCodeDiagnostic.bsl b/src/test/resources/diagnostics/ExecuteExternalCodeDiagnostic.bsl new file mode 100644 index 00000000000..e9de31b4370 --- /dev/null +++ b/src/test/resources/diagnostics/ExecuteExternalCodeDiagnostic.bsl @@ -0,0 +1,33 @@ + +&НаКлиенте +Процедура ВыполнитьПроизвольныйКодНаКлиенте(Строка) + Выполнить(Строка); +КонецПроцедуры + +&НаСервере +Процедура ВыполнитьПроизвольныйКодНаСервере(Строка) + Выполнить(Строка); +КонецПроцедуры + +&НаСервереБезКонтекста +Процедура ВыполнитьПроизвольныйКодНаСервереБезКонтекста(Строка) + Выполнить(Строка); +КонецПроцедуры + +&НаКлиентеНаСервереБезКонтекста +Функция РассчитатьЧтоТоИзСтрокиБезКонтекст(Строка) + Возврат Вычислить(Строка); +КонецФункции + +&НаКлиентеНаСервере +Функция РассчитатьЧтоТоИзСтроки(Строка) + Возврат Вычислить(Строка); +КонецФункции + +Функция БезОшибок(Строка) + Возврат ВычислитьЧтоТо(Строка); +КонецФункции + +Функция МетодБезДеректив(Строка) + Возврат Вычислить(Строка); +КонецФункции diff --git a/src/test/resources/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.bsl b/src/test/resources/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.bsl new file mode 100644 index 00000000000..87b2e14d305 --- /dev/null +++ b/src/test/resources/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.bsl @@ -0,0 +1,12 @@ + +Процедура ВыполнитьПроизвольныйКод(Строка) + Выполнить(Строка); +КонецПроцедуры + +Функция РассчитатьЧтоТоИзСтроки(Строка) + Возврат Вычислить(Строка); +КонецФункции + +Функция БезОшибок(Строка) + Возврат ВычислитьЧтоТо(Строка); +КонецФункции From ba4b43f3ecbb4438b8d2148ffd4fa64420a12257 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Thu, 14 May 2020 12:51:53 +0300 Subject: [PATCH 309/444] precommit --- docs/diagnostics/index.md | 2 +- docs/en/diagnostics/index.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/diagnostics/index.md b/docs/diagnostics/index.md index a653372432c..5e73c492b46 100644 --- a/docs/diagnostics/index.md +++ b/docs/diagnostics/index.md @@ -8,7 +8,7 @@ ## Список реализованных диагностик -Общее количество: **108** +Общее количество: **110** * Дефект кода: **69** * Уязвимость: **3** diff --git a/docs/en/diagnostics/index.md b/docs/en/diagnostics/index.md index 0ceefdfe898..9873463279a 100644 --- a/docs/en/diagnostics/index.md +++ b/docs/en/diagnostics/index.md @@ -8,7 +8,7 @@ To escape individual sections of code or files from triggering diagnostics, you ## Implemented diagnostics -Total: **108** +Total: **110** * Error: **34** * Code smell: **69** From 814d78c21efa2eca7afcc02e7243fa442cb7a603 Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Thu, 14 May 2020 13:20:17 +0300 Subject: [PATCH 310/444] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D1=82=D0=B5=D1=81=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../resources/diagnostics/ExecuteExternalCodeDiagnostic.bsl | 5 +++++ .../ExecuteExternalCodeInCommonModuleDiagnostic.bsl | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/src/test/resources/diagnostics/ExecuteExternalCodeDiagnostic.bsl b/src/test/resources/diagnostics/ExecuteExternalCodeDiagnostic.bsl index e9de31b4370..9ebf1705440 100644 --- a/src/test/resources/diagnostics/ExecuteExternalCodeDiagnostic.bsl +++ b/src/test/resources/diagnostics/ExecuteExternalCodeDiagnostic.bsl @@ -31,3 +31,8 @@ Функция МетодБезДеректив(Строка) Возврат Вычислить(Строка); КонецФункции + +&НаКлиенте +Функция ВычислениеНаКлиенте(Строка) + Возврат Вычислить(Строка); +КонецФункции diff --git a/src/test/resources/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.bsl b/src/test/resources/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.bsl index 87b2e14d305..a4bcf06c056 100644 --- a/src/test/resources/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.bsl +++ b/src/test/resources/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.bsl @@ -10,3 +10,8 @@ Функция БезОшибок(Строка) Возврат ВычислитьЧтоТо(Строка); КонецФункции + +&НаКлиенте +Функция ВычислениеНаКлиенте(Строка) + Возврат Вычислить(Строка); +КонецФункции From b47e84cb803aa7b0fc45306b2f6e8c5f5346e50b Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Thu, 14 May 2020 13:23:24 +0300 Subject: [PATCH 311/444] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D1=82=D0=B5=D1=81=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...ernalCodeInCommonModuleDiagnosticTest.java | 37 +++++++++++++++++++ ...teExternalCodeInCommonModuleDiagnostic.bsl | 4 -- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnosticTest.java index ff2fdf640f1..10d2aa5e6d7 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnosticTest.java @@ -63,6 +63,43 @@ void testIsServer() { ; } + @Test + void testIsExternal() { + + getDocumentContextFromFile(); + when(module.isServer()).thenReturn(Boolean.FALSE); + when(module.isClientOrdinaryApplication()).thenReturn(Boolean.FALSE); + when(module.isExternalConnection()).thenReturn(Boolean.TRUE); + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + List diagnostics = getDiagnostics(documentContext); + + assertThat(diagnostics).hasSize(2); + assertThat(diagnostics, true) + .hasRange(2, 4, 21) + .hasRange(6, 12, 29) + ; + } + + @Test + void testIsOrdinary() { + + getDocumentContextFromFile(); + when(module.isServer()).thenReturn(Boolean.FALSE); + when(module.isClientOrdinaryApplication()).thenReturn(Boolean.TRUE); + when(module.isExternalConnection()).thenReturn(Boolean.FALSE); + when(module.isClientManagedApplication()).thenReturn(Boolean.FALSE); + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + + List diagnostics = getDiagnostics(documentContext); + + assertThat(diagnostics).hasSize(2); + assertThat(diagnostics, true) + .hasRange(2, 4, 21) + .hasRange(6, 12, 29) + ; + } + @Test void testIsNonServer() { diff --git a/src/test/resources/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.bsl b/src/test/resources/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.bsl index a4bcf06c056..dcfa2a695de 100644 --- a/src/test/resources/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.bsl +++ b/src/test/resources/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.bsl @@ -11,7 +11,3 @@ Возврат ВычислитьЧтоТо(Строка); КонецФункции -&НаКлиенте -Функция ВычислениеНаКлиенте(Строка) - Возврат Вычислить(Строка); -КонецФункции From 2aefb34a8931c42041c7d1bb26ab8191e302560f Mon Sep 17 00:00:00 2001 From: Maximov Valery Date: Fri, 15 May 2020 09:11:53 +0300 Subject: [PATCH 312/444] Update docs/faq.md Co-authored-by: Nikita Gryzlov --- docs/faq.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/faq.md b/docs/faq.md index 5b75b194307..9212686f81a 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -25,4 +25,11 @@ `BSL Language Server` является самостоятельным приложением, реализацией серверной части протокола LSP. Плагин для SonarQube использует `BSL Language Server` для выполнения анализа исходного кода языка BSL (конфигурации 1С, скрипты 1Scipt и OSWeb). -`BSL Language Server` может быть использован с любым приложением, имеющим реализацию LSP клиента, на данный момент это плагины для [VS code](https://github.com/1c-syntax/vsc-language-1c-bsl/), [1C:Enterprise development tools](https://github.com/DoublesunRUS/ru.capralow.dt.bslls.validator) (собственная реализация, без LSP), плагин для [SonarQube](https://github.com/1c-syntax/sonar-bsl-plugin-community), [Phoenix BSL](https://github.com/otymko/phoenixbsl) +`BSL Language Server` может быть использован с любым приложением, имеющим реализацию LSP клиента. Проверенные подключения: +* плагин для [VS code](https://github.com/1c-syntax/vsc-language-1c-bsl/); +* дополнительная утилита для Конфигуратора [Phoenix BSL](https://github.com/otymko/phoenixbsl); +* плагин для Sublime Text [https://github.com/sublimelsp/LSP]. + +Так же через прямой импорт `BSL Language Server` работают: +* плагин для [1C:Enterprise development tools](https://github.com/DoublesunRUS/ru.capralow.dt.bslls.validator) (собственная реализация, без LSP); +* плагин для [SonarQube](https://github.com/1c-syntax/sonar-bsl-plugin-community); From b8c6354b6cbe21c25e0519a50a651949a66d39c7 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Fri, 15 May 2020 09:59:37 +0300 Subject: [PATCH 313/444] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=87=D1=82=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F=20=D1=87=D0=B0=D1=81=D1=82=D0=B8=D1=87=D0=BD=D0=BE=20?= =?UTF-8?q?=D0=B7=D0=B0=D0=B4=D0=B0=D0=BD=D0=BD=D0=BE=D0=B9=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=BD=D1=84=D0=B8=D0=B3=D1=83=D1=80=D0=B0=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../codelens/CodeLensOptions.java | 3 ++- .../diagnostics/DiagnosticsOptions.java | 3 ++- .../LanguageServerConfigurationTest.java | 27 +++++++++++++++++++ .../.partial-bsl-language-server.json | 9 +++++++ 4 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 src/test/resources/.partial-bsl-language-server.json diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/CodeLensOptions.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/CodeLensOptions.java index 7b0eab8ee15..de5f466b76e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/CodeLensOptions.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/CodeLensOptions.java @@ -21,6 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.configuration.codelens; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; @@ -30,7 +31,7 @@ * Корневой класс для настройки {@link com.github._1c_syntax.bsl.languageserver.providers.CodeLensProvider} */ @Data -@AllArgsConstructor +@AllArgsConstructor(onConstructor = @__({@JsonCreator(mode = JsonCreator.Mode.DISABLED)})) @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class CodeLensOptions { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java index 2cbee0dde56..f53e3977293 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java @@ -21,6 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.configuration.diagnostics; +import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.databind.ParametersDeserializer; @@ -36,7 +37,7 @@ * Корневой класс для настройки {@link com.github._1c_syntax.bsl.languageserver.providers.DiagnosticProvider} */ @Data -@AllArgsConstructor +@AllArgsConstructor(onConstructor = @__({@JsonCreator(mode = JsonCreator.Mode.DISABLED)})) @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class DiagnosticsOptions { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java index b903401b556..c1fc77b6683 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java @@ -21,7 +21,10 @@ */ package com.github._1c_syntax.bsl.languageserver.configuration; +import com.github._1c_syntax.bsl.languageserver.configuration.codelens.CodeLensOptions; import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.DiagnosticsOptions; +import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Mode; +import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.SkipSupport; import com.github._1c_syntax.utils.Absolute; import org.eclipse.lsp4j.jsonrpc.messages.Either; import org.junit.jupiter.api.BeforeEach; @@ -43,6 +46,8 @@ class LanguageServerConfigurationTest { private static final String PATH_TO_CONFIGURATION_FILE = "./src/test/resources/.bsl-language-server.json"; private static final String PATH_TO_EMPTY_CONFIGURATION_FILE = "./src/test/resources/.empty-bsl-language-server.json"; private static final String PATH_TO_METADATA = "src/test/resources/metadata"; + private static final String PATH_TO_PARTIAL_CONFIGURATION_FILE + = "./src/test/resources/.partial-bsl-language-server.json"; @BeforeEach void startUp() throws IOException { @@ -130,4 +135,26 @@ void test_GetCustomConfigurationRoot() { } + @Test + void testPartialInitialization() { + // given + File configurationFile = new File(PATH_TO_PARTIAL_CONFIGURATION_FILE); + + // when + LanguageServerConfiguration configuration = LanguageServerConfiguration.create(configurationFile); + + CodeLensOptions codeLensOptions = configuration.getCodeLensOptions(); + DiagnosticsOptions diagnosticsOptions = configuration.getDiagnosticsOptions(); + + // then + assertThat(codeLensOptions.isShowCognitiveComplexity()).isTrue(); + assertThat(codeLensOptions.isShowCyclomaticComplexity()).isFalse(); + + assertThat(configuration.getLanguage()).isEqualTo(DEFAULT_LANGUAGE); + + assertThat(diagnosticsOptions.getMode()).isEqualTo(Mode.ON); + assertThat(diagnosticsOptions.getSkipSupport()).isEqualTo(SkipSupport.NEVER); + assertThat(diagnosticsOptions.getParameters()).isEmpty(); + } + } \ No newline at end of file diff --git a/src/test/resources/.partial-bsl-language-server.json b/src/test/resources/.partial-bsl-language-server.json new file mode 100644 index 00000000000..3c4a11dd320 --- /dev/null +++ b/src/test/resources/.partial-bsl-language-server.json @@ -0,0 +1,9 @@ +{ + "$schema": "https://1c-syntax.github.io/bsl-language-server/dev/configuration/schema.json", + "codeLens": { + "showCyclomaticComplexity": false + }, + "diagnostics": { + "mode": "on" + } +} From 367314ee5106b4233087ad8ee54c93b2369f56b0 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Fri, 15 May 2020 15:10:05 +0300 Subject: [PATCH 314/444] =?UTF-8?q?=D0=A5=D0=B5=D0=BB=D0=BF=D0=B5=D1=80=20?= =?UTF-8?q?=D0=B4=D0=BB=D1=8F=20=D0=B5=D0=B4=D0=B8=D0=BD=D0=BE=D0=BE=D0=B1?= =?UTF-8?q?=D1=80=D0=B0=D0=B7=D0=BD=D0=BE=D0=B3=D0=BE=20=D1=87=D1=82=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D1=8F=20=D1=80=D0=B5=D1=81=D1=83=D1=80=D1=81=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../diagnostics/metadata/DiagnosticInfo.java | 10 +--- .../bsl/languageserver/utils/Resources.java | 57 +++++++++++++++++++ 2 files changed, 60 insertions(+), 7 deletions(-) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Resources.java diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java index 5e9ecbe2977..58a2d3cb9f9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java @@ -23,7 +23,7 @@ import com.github._1c_syntax.bsl.languageserver.configuration.Language; import com.github._1c_syntax.bsl.languageserver.diagnostics.BSLDiagnostic; -import com.github._1c_syntax.bsl.languageserver.utils.UTF8Control; +import com.github._1c_syntax.bsl.languageserver.utils.Resources; import com.github._1c_syntax.mdclasses.metadata.additional.ModuleType; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; @@ -35,10 +35,8 @@ import java.util.Arrays; import java.util.EnumMap; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Optional; -import java.util.ResourceBundle; import java.util.stream.Collectors; import static com.github._1c_syntax.bsl.languageserver.configuration.Language.DEFAULT_LANGUAGE; @@ -109,13 +107,11 @@ public String getMessage(Object... args) { } public String getResourceString(String key) { - String languageCode = language.getLanguageCode(); - Locale locale = Locale.forLanguageTag(languageCode); - return ResourceBundle.getBundle(diagnosticClass.getName(), locale, new UTF8Control()).getString(key).intern(); + return Resources.getResourceString(language, diagnosticClass, key); } public String getResourceString(String key, Object... args) { - return String.format(getResourceString(key), args).intern(); + return Resources.getResourceString(language, diagnosticClass, key, args); } public DiagnosticType getType() { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Resources.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Resources.java new file mode 100644 index 00000000000..ce7b523e0fc --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Resources.java @@ -0,0 +1,57 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.utils; + +import com.github._1c_syntax.bsl.languageserver.configuration.Language; +import lombok.experimental.UtilityClass; + +import java.util.Locale; +import java.util.ResourceBundle; + +/** + * Вспомогательный класс для оптимизированного чтения ресурсов прикладных классов с учетом {@link Language}. + */ +@UtilityClass +public class Resources { + + /** + * @param language Язык получения ресурсной строки. + * @param clazz Класс, ресурсы которого необходимо прочитать. + * @param key Ключ из {@link ResourceBundle}. + * @return Содержимое ресурса. + */ + public String getResourceString(Language language, Class clazz, String key) { + String languageCode = language.getLanguageCode(); + Locale locale = Locale.forLanguageTag(languageCode); + return ResourceBundle.getBundle(clazz.getName(), locale, new UTF8Control()).getString(key).intern(); + } + /** + * @param language Язык получения ресурсной строки. + * @param clazz Класс, ресурсы которого необходимо прочитать. + * @param key Ключ из {@link ResourceBundle}. + * @param args Аргументы для форматирования ресурсной строки. + * @return Содержимое ресурса. + */ + public String getResourceString(Language language, Class clazz, String key, Object... args) { + return String.format(getResourceString(language, clazz, key), args).intern(); + } +} From cff8e785d69c1ded31fe7c369453ed521563af07 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Fri, 15 May 2020 15:10:49 +0300 Subject: [PATCH 315/444] =?UTF-8?q?=D0=9F=D0=B0=D1=80=D0=B0=D0=BC=D0=B5?= =?UTF-8?q?=D1=82=D1=80=D1=8B=20document=20link=20+=20tooltip?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../LanguageServerConfiguration.java | 5 ++ .../documentlink/DocumentLinkOptions.java | 40 +++++++++ .../documentlink/package-info.java | 26 ++++++ .../providers/DocumentLinkProvider.java | 38 +++++++-- .../DocumentLinkProvider_en.properties | 1 + .../DocumentLinkProvider_ru.properties | 1 + .../providers/DocumentLinkProviderTest.java | 84 +++++++++++++++++++ 7 files changed, 186 insertions(+), 9 deletions(-) create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/DocumentLinkOptions.java create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/package-info.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider_ru.properties diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java index ca9aa5ee0d8..a3026b80f82 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java @@ -27,6 +27,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.github._1c_syntax.bsl.languageserver.configuration.codelens.CodeLensOptions; import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.DiagnosticsOptions; +import com.github._1c_syntax.bsl.languageserver.configuration.documentlink.DocumentLinkOptions; import com.github._1c_syntax.utils.Absolute; import lombok.AllArgsConstructor; import lombok.Data; @@ -68,6 +69,9 @@ public final class LanguageServerConfiguration { @JsonProperty("codeLens") private final CodeLensOptions codeLensOptions; + @JsonProperty("documentLink") + private final DocumentLinkOptions documentLinkOptions; + @Nullable private File traceLog; @@ -79,6 +83,7 @@ private LanguageServerConfiguration() { Language.DEFAULT_LANGUAGE, new DiagnosticsOptions(), new CodeLensOptions(), + new DocumentLinkOptions(), null, null ); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/DocumentLinkOptions.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/DocumentLinkOptions.java new file mode 100644 index 00000000000..b4142087701 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/DocumentLinkOptions.java @@ -0,0 +1,40 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.configuration.documentlink; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * Корневой класс для настройки {@link com.github._1c_syntax.bsl.languageserver.providers.DocumentLinkProvider} + */ +@Data +@AllArgsConstructor(onConstructor = @__({@JsonCreator(mode = JsonCreator.Mode.DISABLED)})) +@NoArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class DocumentLinkOptions { + private boolean useDevSite; + private String siteRoot = "https://1c-syntax.github.io/bsl-language-server"; +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/package-info.java new file mode 100644 index 00000000000..2c15f7357ea --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/package-info.java @@ -0,0 +1,26 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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. + */ + +/** + * Пакет содержит настройки {@link com.github._1c_syntax.bsl.languageserver.providers.DocumentLinkProvider} + */ +package com.github._1c_syntax.bsl.languageserver.configuration.documentlink; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java index 0e4faeb3aa0..e6fc10c4545 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java @@ -25,18 +25,17 @@ import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCode; +import com.github._1c_syntax.bsl.languageserver.utils.Resources; import org.eclipse.lsp4j.DocumentLink; -import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; /** * Класс-провайдер для реализации формирования ссылки на страницу с информацией по диагностике */ public class DocumentLinkProvider { private final DiagnosticProvider diagnosticProvider; - private static final String SITE_URL_RU = "https://1c-syntax.github.io/bsl-language-server/diagnostics/"; - private static final String SITE_URL_EN = "https://1c-syntax.github.io/bsl-language-server/en/diagnostics/"; private final LanguageServerConfiguration configuration; public DocumentLinkProvider(LanguageServerConfiguration configuration, DiagnosticProvider diagnosticProvider) { @@ -45,11 +44,32 @@ public DocumentLinkProvider(LanguageServerConfiguration configuration, Diagnosti } public List getDocumentLinks(DocumentContext documentContext) { - List documentLinks = new ArrayList<>(); - var siteDiagnosticsUrl = configuration.getLanguage() == Language.EN ? SITE_URL_EN : SITE_URL_RU; - diagnosticProvider.getComputedDiagnostics(documentContext) - .forEach(diagnostic -> documentLinks.add(new DocumentLink(diagnostic.getRange(), - siteDiagnosticsUrl + DiagnosticCode.getStringValue(diagnostic.getCode())))); - return documentLinks; + + var linkOptions = configuration.getDocumentLinkOptions(); + var language = configuration.getLanguage(); + + var siteRoot = linkOptions.getSiteRoot(); + var devSuffix = linkOptions.isUseDevSite() ? "/dev" : ""; + var languageSuffix = language == Language.EN ? "/en" : ""; + + var siteDiagnosticsUrl = String.format( + "%s%s%s/diagnostics/", + siteRoot, + devSuffix, + languageSuffix + ); + + var tooltip = Resources.getResourceString(language, this.getClass(), "tooltip"); + + return diagnosticProvider.getComputedDiagnostics(documentContext).stream() + .map(diagnostic -> + new DocumentLink( + diagnostic.getRange(), + siteDiagnosticsUrl + DiagnosticCode.getStringValue(diagnostic.getCode()), + null, + tooltip + ) + ) + .collect(Collectors.toList()); } } diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider_en.properties new file mode 100644 index 00000000000..740413d43fe --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider_en.properties @@ -0,0 +1 @@ +tooltip=Diagnostics documentation diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider_ru.properties new file mode 100644 index 00000000000..3b3dd7d1be5 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider_ru.properties @@ -0,0 +1 @@ +tooltip=Документация диагностики diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProviderTest.java index 4e3e792668d..77c3f922eab 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProviderTest.java @@ -21,6 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.providers; +import com.github._1c_syntax.bsl.languageserver.configuration.Language; import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.diagnostics.DiagnosticSupplier; @@ -81,6 +82,89 @@ void testGetDocumentLinksEn() { .hasSize(3); } + @Test + void testDevSite() { + // given + var configuration = LanguageServerConfiguration.create(); + var documentLinkOptions = configuration.getDocumentLinkOptions(); + var documentContext = getDocumentContext(); + var documentLinkProvider = getDocumentLinkProvider(configuration, documentContext); + + // when + documentLinkOptions.setUseDevSite(false); + var documentLinks = documentLinkProvider.getDocumentLinks(documentContext); + + // then + assertThat(documentLinks) + .allMatch(documentLink -> !documentLink.getTarget().contains("/dev/")); + + // when + documentLinkOptions.setUseDevSite(true); + documentLinks = documentLinkProvider.getDocumentLinks(documentContext); + + // then + assertThat(documentLinks) + .allMatch(documentLink -> documentLink.getTarget().contains("/dev/")); + + // when + documentLinkOptions.setUseDevSite(true); + configuration.setLanguage(Language.EN); + documentLinks = documentLinkProvider.getDocumentLinks(documentContext); + + // then + assertThat(documentLinks) + .allMatch(documentLink -> documentLink.getTarget().contains("/dev/")) + .allMatch(documentLink -> documentLink.getTarget().contains("/en/")); + + } + + @Test + void testTooltip() { + var configuration = LanguageServerConfiguration.create(); + var documentContext = getDocumentContext(); + var documentLinkProvider = getDocumentLinkProvider(configuration, documentContext); + + // when + configuration.setLanguage(Language.RU); + var documentLinks = documentLinkProvider.getDocumentLinks(documentContext); + + // then + assertThat(documentLinks) + .allMatch(documentLink -> documentLink.getTooltip().contains("Документация")); + + // when + configuration.setLanguage(Language.EN); + documentLinks = documentLinkProvider.getDocumentLinks(documentContext); + + // then + assertThat(documentLinks) + .allMatch(documentLink -> documentLink.getTooltip().contains("documentation")); + } + + @Test + void testSiteRoot() { + var configuration = LanguageServerConfiguration.create(); + var documentContext = getDocumentContext(); + var documentLinkProvider = getDocumentLinkProvider(configuration, documentContext); + + // when + var documentLinks = documentLinkProvider.getDocumentLinks(documentContext); + + // then + assertThat(documentLinks) + .allMatch(documentLink -> documentLink.getTarget().startsWith("https://1c-syntax")); + + // when + configuration.getDocumentLinkOptions().setSiteRoot("https://fake"); + documentLinks = documentLinkProvider.getDocumentLinks(documentContext); + + // then + assertThat(documentLinks) + .allMatch(documentLink -> !documentLink.getTarget().startsWith("https://1c-syntax")) + .allMatch(documentLink -> documentLink.getTarget().startsWith("https://fake")) + ; + } + @NotNull private DocumentLinkProvider getDocumentLinkProvider(LanguageServerConfiguration configuration, DocumentContext documentContext) { var diagnosticSupplier = new DiagnosticSupplier(configuration); From e08586d298d94081f33e76293109f7e37a6e99dc Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Fri, 15 May 2020 15:21:13 +0300 Subject: [PATCH 316/444] isUseDevSite -> useDevSite --- .idea/jsonSchemas.xml | 24 +++++++++++++++++++ .../documentlink/DocumentLinkOptions.java | 7 ++++++ .../providers/DocumentLinkProvider.java | 2 +- 3 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 .idea/jsonSchemas.xml diff --git a/.idea/jsonSchemas.xml b/.idea/jsonSchemas.xml new file mode 100644 index 00000000000..01a2f6fa813 --- /dev/null +++ b/.idea/jsonSchemas.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/DocumentLinkOptions.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/DocumentLinkOptions.java index b4142087701..28fe7760d0c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/DocumentLinkOptions.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/DocumentLinkOptions.java @@ -23,8 +23,10 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Data; +import lombok.Getter; import lombok.NoArgsConstructor; /** @@ -35,6 +37,11 @@ @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class DocumentLinkOptions { + @Getter(AccessLevel.NONE) private boolean useDevSite; private String siteRoot = "https://1c-syntax.github.io/bsl-language-server"; + + public boolean useDevSite() { + return useDevSite; + } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java index e6fc10c4545..5d5870d0ddf 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java @@ -49,7 +49,7 @@ public List getDocumentLinks(DocumentContext documentContext) { var language = configuration.getLanguage(); var siteRoot = linkOptions.getSiteRoot(); - var devSuffix = linkOptions.isUseDevSite() ? "/dev" : ""; + var devSuffix = linkOptions.useDevSite() ? "/dev" : ""; var languageSuffix = language == Language.EN ? "/en" : ""; var siteDiagnosticsUrl = String.format( From b45bdec6ddcd62f40453a7e905893b2949c8d154 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Fri, 15 May 2020 15:21:33 +0300 Subject: [PATCH 317/444] =?UTF-8?q?=D0=A0=D0=B0=D1=81=D1=88=D0=B8=D1=80?= =?UTF-8?q?=D0=B5=D0=BD=D1=8B=20=D1=82=D0=B5=D1=81=D1=82=D1=8B=20=D0=BD?= =?UTF-8?q?=D0=B0=20=D0=BE=D1=81=D0=BD=D0=BE=D0=B2=D0=BD=D0=BE=D0=B9=20?= =?UTF-8?q?=D0=BA=D0=BB=D0=B0=D1=81=D1=81=20=D0=BA=D0=BE=D0=BD=D1=84=D0=B8?= =?UTF-8?q?=D0=B3=D1=83=D1=80=D0=B0=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../configuration/LanguageServerConfigurationTest.java | 2 ++ src/test/resources/.bsl-language-server.json | 3 +++ 2 files changed, 5 insertions(+) diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java index c1fc77b6683..229a5472f20 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java @@ -99,6 +99,8 @@ void createFromFile() { Path configurationRoot = configuration.getConfigurationRoot(); assertThat(configurationRoot).isNotEqualTo(null); + assertThat(configuration.getDocumentLinkOptions().useDevSite()).isTrue(); + } @Test diff --git a/src/test/resources/.bsl-language-server.json b/src/test/resources/.bsl-language-server.json index b06e9d59b29..20d02460c0f 100644 --- a/src/test/resources/.bsl-language-server.json +++ b/src/test/resources/.bsl-language-server.json @@ -15,6 +15,9 @@ "MethodSize": false } }, + "documentLink": { + "useDevSite": true + }, "traceLog": "build/.trace.log", "configurationRoot": "src/test/resources/metadata" } From c22adf6b832a2303a8600cfee59f09a5cd2b6c49 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Fri, 15 May 2020 15:25:12 +0300 Subject: [PATCH 318/444] =?UTF-8?q?=D0=A1=D1=85=D0=B5=D0=BC=D0=B0=20+=20?= =?UTF-8?q?=D0=B4=D0=BE=D0=BA=D1=83=D0=BC=D0=B5=D0=BD=D1=82=D0=B0=D1=86?= =?UTF-8?q?=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/features/ConfigurationFile.md | 3 +++ .../languageserver/configuration/schema.json | 20 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/docs/features/ConfigurationFile.md b/docs/features/ConfigurationFile.md index fb33c40d8c8..a22e9ac295c 100644 --- a/docs/features/ConfigurationFile.md +++ b/docs/features/ConfigurationFile.md @@ -16,6 +16,9 @@ BSL Language Server предоставляет возможность измен |⤷   `skipSupport`|`Строка`|Этим параметром настраивается режим пропуска файлов *(т.е. файлы не анализируются на предмет наличия замечаний)* **конфигурации 1С**, находящихся "на поддержке" конфигурации поставщика. Возможные значения:
* `withSupport` - пропускаются все модули, находящиеся "на поддержке" *(все виды "замков")*
* `withSupportLocked` - пропускаются только модули, находящиеся "на поддержке" с запретом изменений *("желтый закрытый замок")*
* `never` - режим поддержки не анализируется и модули не пропускаются *(установлен по умолчанию)*| |⤷   `mode`|`Строка`|Настройка для управления режимом учета настроек диагностик. Возможные варианты:
* `OFF` - Все диагностики считаются выключенными, вне зависимости от их настроек
* `ON` - Все диагностики включенные по умолчанию считаются включенными, остальные - в зависимости от личных настроек
* `EXCEPT` - Все диагностистики, кроме указанных, считаются включенными
* `ONLY` - Только указанные диагностики считаются включенными
* `ALL` - Все диагностики считаются включенными| |⤷   `parameters`|`JSON-Объект`|Параметр представляет собой коллекцию настроек диагностик. Элементами коллекции являются json-объекты следующей структуры:
* *ключ объекта* - строка, являющаяся ключом диагностики
* *значение объекта* - может принимать либо булево значение, и тогда интерпретируется как отключение диагностики (`false`) или ее включение с параметрами по умолчанию (`true`), либо значение типа `json-объект`, представляющего собой набор настроек диагностики.

Ключ, включена ли по умолчанию, а также описание возможных параметров и примеры для конфигурационного файла представлены на странице с описанием каждой диагностики.| +|`documentLink`|`JSON-Объект`|Содержит настройки ссылок на документацию| +|⤷   `useDevSite`|`Булево`|При включении настройки формирующиеся ссылки на документацию будут вести на develop-версию сайта. По умолчанию параметр выключен (*установлен в `false`*)| +|⤷   `siteRoot`|`Строка`|Путь к корню сайта с документацией. По умолчанию параметр имеет значение `"https://1c-syntax.github.io/bsl-language-server"` | |`traceLog`|`Строка`|Для логирования всех запросов *(входящих и исходящих)* между **BSL Language Server** и **Language Client** из используемого редактора/IDE, в этом параметре можно указать путь к файлу лога. Путь можно указывать как абсолютный, так и относительный *(от корня анализируемого проекта)*, по умолчанию значение не заполнено.

**ВНИМАНИЕ**

* При запуске **BSL Language Server** перезаписывает указанный файл
* Скорость взаимодействия между клиентом и сервером **ЗНАЧИТЕЛЬНО ЗАМЕДЛЯЕТСЯ**| |`configurationRoot`|`Строка`|Данный параметр предназначен для указания корневого каталога, в котором находятся файлы конфигурации 1С в каталоге проекта. Может быть полезен в случае нахождения нескольких каталогов конфигураций в одном каталоге проекта либо при сложной структуре каталога проекта. По умолчанию параметр не заполнен и `BSL Language Server` самостоятельно определяет расположение корневого каталога конфигурации| diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 153fd814a0f..ae234928712 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -393,6 +393,26 @@ } } }, + "documentLink": { + "$id": "#/properties/documentLink", + "type": "object", + "title": "Document link configuration.", + "default": null, + "properties": { + "useDevSite": { + "$id": "#/properties/useDevSite", + "type": "boolean", + "title": "Use develop version of site for documentation links.", + "default": false + }, + "siteRoot": { + "$id": "#/properties/siteRoot", + "type": "string", + "title": "Root URL for documentation links.", + "default": "https://1c-syntax.github.io/bsl-language-server" + } + } + }, "diagnostics": { "$id": "#/properties/diagnostics", "type": "object", From bbbda213f8c2a9b9b66c8209daa7a88c80c7eb9d Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Tue, 19 May 2020 13:59:11 +0300 Subject: [PATCH 319/444] =?UTF-8?q?=D0=9E=D1=87=D0=B8=D1=81=D1=82=D0=BA?= =?UTF-8?q?=D0=B0=20=D1=81=D0=B8=D0=BC=D0=B2=D0=BE=D0=BB=D1=8C=D0=BD=D0=BE?= =?UTF-8?q?=D0=B3=D0=BE=20=D0=B4=D0=B5=D1=80=D0=B5=D0=B2=D0=B0=20=D0=BF?= =?UTF-8?q?=D1=80=D0=B8=20=D0=BF=D0=B5=D1=80=D0=B5=D1=81=D1=82=D1=80=D0=BE?= =?UTF-8?q?=D0=B9=D0=BA=D0=B5=20=D0=BA=D0=BE=D0=BD=D1=82=D0=B5=D0=BA=D1=81?= =?UTF-8?q?=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../_1c_syntax/bsl/languageserver/context/DocumentContext.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java index b5a3027834a..922a1317730 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java @@ -196,6 +196,7 @@ public Optional getMdObject() { public void rebuild(String content) { computeLock.lock(); clearSecondaryData(); + symbolTree.clear(); this.content = content; tokenizer = new Tokenizer(content); computeLock.unlock(); From e651c692d35b7114f5e41b0f2c26847f8f9d7689 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Fri, 8 May 2020 17:58:56 +0300 Subject: [PATCH 320/444] =?UTF-8?q?=D0=94=D1=80=D0=B0=D1=84=D1=82=20=D0=B4?= =?UTF-8?q?=D0=B8=D0=B0=D0=B3=D0=BD=D0=BE=D1=81=D1=82=D0=B8=D0=BA=D0=B8=20?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=B2=D1=8B=D0=B7=D0=BE=D0=B2=20=D1=83=D1=81?= =?UTF-8?q?=D1=82=D0=B0=D1=80=D0=B5=D0=B2=D1=88=D0=B8=D1=85=20=D0=BC=D0=B5?= =?UTF-8?q?=D1=82=D0=BE=D0=B4=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/diagnostics/DeprecatedMethodCall.md | 36 ++++++ docs/en/diagnostics/DeprecatedMethodCall.md | 36 ++++++ .../DeprecatedMethodCallDiagnostic.java | 107 ++++++++++++++++++ .../languageserver/utils/MdoRefBuilder.java | 47 ++++++++ ...precatedMethodCallDiagnostic_en.properties | 2 + ...precatedMethodCallDiagnostic_ru.properties | 2 + .../DeprecatedMethodCallDiagnosticTest.java | 46 ++++++++ .../DeprecatedMethodCallDiagnostic.bsl | 1 + 8 files changed, 277 insertions(+) create mode 100644 docs/diagnostics/DeprecatedMethodCall.md create mode 100644 docs/en/diagnostics/DeprecatedMethodCall.md create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnostic.java create mode 100644 src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MdoRefBuilder.java create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnostic_en.properties create mode 100644 src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnostic_ru.properties create mode 100644 src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnosticTest.java create mode 100644 src/test/resources/diagnostics/DeprecatedMethodCallDiagnostic.bsl diff --git a/docs/diagnostics/DeprecatedMethodCall.md b/docs/diagnostics/DeprecatedMethodCall.md new file mode 100644 index 00000000000..6fcb1ecdbe5 --- /dev/null +++ b/docs/diagnostics/DeprecatedMethodCall.md @@ -0,0 +1,36 @@ +# () + + + +## + + +## Описание диагностики + + +## Примеры + + +## Источники + + + +## Сниппеты + + +### Экранирование кода + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Параметр конфигурационного файла + +```json +"": +``` \ No newline at end of file diff --git a/docs/en/diagnostics/DeprecatedMethodCall.md b/docs/en/diagnostics/DeprecatedMethodCall.md new file mode 100644 index 00000000000..4e7e0f78ada --- /dev/null +++ b/docs/en/diagnostics/DeprecatedMethodCall.md @@ -0,0 +1,36 @@ +# + + + +## + + +## Description + + +## Examples + + +## Sources + + + +## Snippets + + +### Diagnostic ignorance in code + +```bsl +// BSLLS:-off +// BSLLS:-on +``` + +### Parameter for config + +```json +"": +``` diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnostic.java new file mode 100644 index 00000000000..5edc85f6a18 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnostic.java @@ -0,0 +1,107 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.MdoRefBuilder; +import com.github._1c_syntax.bsl.parser.BSLParser; +import org.antlr.v4.runtime.Token; +import org.antlr.v4.runtime.tree.ParseTree; + +import javax.annotation.CheckForNull; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 1, + tags = { + DiagnosticTag.DEPRECATED, + DiagnosticTag.DESIGN + } + +) +public class DeprecatedMethodCallDiagnostic extends AbstractVisitorDiagnostic { + public DeprecatedMethodCallDiagnostic(DiagnosticInfo info) { + super(info); + } + + @Override + public ParseTree visitCallStatement(BSLParser.CallStatementContext ctx) { + + if (ctx.globalMethodCall() != null) { + return super.visitCallStatement(ctx); + } + + String mdoRef = MdoRefBuilder.getMdoRef(documentContext, ctx); + if (mdoRef.isEmpty()) { + return super.visitCallStatement(ctx); + } + + var documentContexts = documentContext.getServerContext().getDocuments(mdoRef); + if (documentContexts == null) { + return super.visitCallStatement(ctx); + } + + Token methodName = getMethodName(ctx); + if (methodName == null) { + return super.visitCallStatement(ctx); + } + + String methodNameText = methodName.getText(); + + documentContexts.values().stream() + .map(DocumentContext::getSymbolTree) + .flatMap(symbolTree -> symbolTree.getMethods().stream()) + .filter(methodSymbol -> methodSymbol.isDeprecated() + && methodSymbol.getName().equalsIgnoreCase(methodNameText)) + .findAny() + .ifPresent(methodSymbol -> diagnosticStorage.addDiagnostic(methodName)); + + return super.visitCallStatement(ctx); + } + + @CheckForNull + private static Token getMethodName(BSLParser.CallStatementContext ctx) { + + var modifiers = ctx.modifier(); + if (modifiers.isEmpty()) { + return getMethodName(ctx.accessCall()); + } else { + // пока только общие модули + BSLParser.ModifierContext firstModifier = modifiers.get(0); + if (firstModifier.accessCall() != null) { + return getMethodName(firstModifier.accessCall()); + } + } + + return null; + } + + private static Token getMethodName(BSLParser.AccessCallContext ctx) { + return ctx.methodCall().methodName().getStart(); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MdoRefBuilder.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MdoRefBuilder.java new file mode 100644 index 00000000000..7158b29b826 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MdoRefBuilder.java @@ -0,0 +1,47 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.utils; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.parser.BSLParser; +import lombok.experimental.UtilityClass; + +@UtilityClass +public class MdoRefBuilder { + + public String getMdoRef(DocumentContext documentContext, BSLParser.CallStatementContext callStatement) { + String mdoRef = ""; + + if (callStatement.IDENTIFIER() != null) { + var commonModuleName = callStatement.IDENTIFIER().getText(); + var commonModule = documentContext.getServerContext() + .getConfiguration() + .getCommonModule(commonModuleName); + if (commonModule.isPresent()) { + mdoRef = commonModule.orElseThrow().getMdoRef(); + } + } + + return mdoRef; + } + +} diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnostic_en.properties new file mode 100644 index 00000000000..bae879b1aa4 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Remove deprecated method call +diagnosticName=Deprecated methods should not be used diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnostic_ru.properties new file mode 100644 index 00000000000..2c67956a6ea --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Удалите вызов устаревшего метода +diagnosticName=Устаревшие методы не должны использоваться diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnosticTest.java new file mode 100644 index 00000000000..6ea1ff1ade8 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnosticTest.java @@ -0,0 +1,46 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright © 2018-2020 + * Alexey Sosnoviy , Nikita Gryzlov 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.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class DeprecatedMethodCallDiagnosticTest extends AbstractDiagnosticTest { + DeprecatedMethodCallDiagnosticTest() { + super(DeprecatedMethodCallDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasRange(6, 0, 6, 20); + + } +} diff --git a/src/test/resources/diagnostics/DeprecatedMethodCallDiagnostic.bsl b/src/test/resources/diagnostics/DeprecatedMethodCallDiagnostic.bsl new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/src/test/resources/diagnostics/DeprecatedMethodCallDiagnostic.bsl @@ -0,0 +1 @@ + From 9b6c683e1590124c2946c4ac32d1f638ba307435 Mon Sep 17 00:00:00 2001 From: Nikita Gryzlov Date: Tue, 19 May 2020 18:13:28 +0300 Subject: [PATCH 321/444] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BA=D0=BE=D0=BD=D1=84=D0=B8=D0=B3?= =?UTF-8?q?=D1=83=D1=80=D0=B0=D1=86=D0=B8=D0=B8=20=D0=B2=20=D1=80=D0=B5?= =?UTF-8?q?=D1=81=D1=83=D1=80=D1=81=D0=B0=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../computer/MethodSymbolComputerTest.java | 15 +- .../NonStandardRegionDiagnosticTest.java | 2 +- .../DeprecatedMethodCallDiagnostic.bsl | 14 ++ ...\276\321\207\320\275\320\270\320\2721.xml" | 11 +- ...1\213\320\261\320\276\321\200\320\260.xml" | 6 +- .../Ext/Form.xml" | 5 +- .../Ext/Form/Module.bsl" | 2 +- ...0\277\320\270\321\201\320\272\320\260.xml" | 6 +- .../Ext/Form.xml" | 5 +- ...0\274\320\265\320\275\321\202\320\260.xml" | 2 +- .../Ext/Form.xml" | 2 +- ...0\234\320\260\320\272\320\265\321\202.xml" | 2 +- ...\276\320\274\320\260\320\275\320\2641.xml" | 27 +++ ...0\276\320\264\321\203\320\273\321\214.xml" | 2 +- .../Ext/Module.bsl" | 24 ++- .../resources/metadata/ConfigDumpInfo.xml | 43 +++-- src/test/resources/metadata/Configuration.xml | 166 ++++++++++++------ ...\264\320\265\320\275\320\270\320\2711.xml" | 4 +- .../Ext/ManagerModule.bsl" | 19 ++ ...1\201\321\201\320\272\320\270\320\271.xml" | 2 +- 20 files changed, 263 insertions(+), 96 deletions(-) create mode 100644 "src/test/resources/metadata/CommandGroups/\320\223\321\200\321\203\320\277\320\277\320\260\320\232\320\276\320\274\320\260\320\275\320\2641.xml" create mode 100644 "src/test/resources/metadata/InformationRegisters/\320\240\320\265\320\263\320\270\321\201\321\202\321\200\320\241\320\262\320\265\320\264\320\265\320\275\320\270\320\2711/Ext/ManagerModule.bsl" diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java index a87d3889c4d..db2a620cf92 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java @@ -115,9 +115,9 @@ void testMdoRef() throws IOException { var path = Absolute.path(PATH_TO_METADATA); var serverContext = new ServerContext(path); - checkModule(serverContext, PATH_TO_MODULE_FILE, "CommonModule.ПервыйОбщийМодуль"); - checkModule(serverContext, PATH_TO_CATALOG_FILE, "Catalog.Справочник1"); - checkModule(serverContext, PATH_TO_CATALOG_MODULE_FILE, "Catalog.Справочник1"); + checkModule(serverContext, PATH_TO_MODULE_FILE, "CommonModule.ПервыйОбщийМодуль", 5); + checkModule(serverContext, PATH_TO_CATALOG_FILE, "Catalog.Справочник1", 1); + checkModule(serverContext, PATH_TO_CATALOG_MODULE_FILE, "Catalog.Справочник1", 1); } @Test @@ -131,12 +131,17 @@ void testParseError() { } - private void checkModule(ServerContext serverContext, String path, String mdoRef) throws IOException { + private void checkModule( + ServerContext serverContext, + String path, + String mdoRef, + int methodsCount + ) throws IOException { var file = new File(PATH_TO_METADATA, path); var uri = Absolute.uri(file); var documentContext = serverContext.addDocument(uri, FileUtils.readFileToString(file, StandardCharsets.UTF_8)); List methods = documentContext.getSymbolTree().getMethods(); - assertThat(methods.size()).isEqualTo(1); + assertThat(methods.size()).isEqualTo(methodsCount); assertThat(methods.get(0).getName()).isEqualTo("Тест"); assertThat(methods.get(0).getMdoRef()).isEqualTo(mdoRef); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnosticTest.java index d653f9ec34e..9736e9eb9e2 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnosticTest.java @@ -141,7 +141,7 @@ void testCommonModule() throws IOException { .hasRange(41, 1, 63) .hasRange(45, 1, 31) .hasRange(49, 1, 27) - .hasRange(57, 1, 18) + .hasRange(77, 1, 18) ; } diff --git a/src/test/resources/diagnostics/DeprecatedMethodCallDiagnostic.bsl b/src/test/resources/diagnostics/DeprecatedMethodCallDiagnostic.bsl index 8b137891791..827d2cbf37f 100644 --- a/src/test/resources/diagnostics/DeprecatedMethodCallDiagnostic.bsl +++ b/src/test/resources/diagnostics/DeprecatedMethodCallDiagnostic.bsl @@ -1 +1,15 @@ +ПервыйОбщийМодуль.УстаревшаяПроцедура(); +ПервыйОбщийМодуль.НеУстаревшаяПроцедура(); + +ПервыйОбщийМодуль.УстаревшаяФункция(); +ПервыйОбщийМодуль.НеУстаревшаяФункция(); + +А = ПервыйОбщийМодуль.УстаревшаяФункция(); +А = ПервыйОбщийМодуль.НеУстаревшаяФункция(); + +Если ПервыйОбщийМодуль.УстаревшаяФункция() Тогда +КонецЕсли; + +Если ПервыйОбщийМодуль.НеУстаревшаяФункция() Тогда +КонецЕсли; diff --git "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721.xml" "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721.xml" index 10535036b21..b6dffa7188f 100644 --- "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721.xml" +++ "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721.xml" @@ -1,5 +1,5 @@  - + @@ -77,6 +77,9 @@ Use Auto + DontUse + false + false @@ -115,6 +118,7 @@ ForItem DontIndex Use + Use @@ -154,6 +158,7 @@ ForItem DontIndex Use + Use @@ -188,6 +193,7 @@ ForItem DontIndex Use + Use @@ -243,6 +249,7 @@ Auto DontIndex Use + Use @@ -279,6 +286,7 @@ Auto DontIndex Use + Use @@ -300,6 +308,7 @@ + Auto diff --git "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\222\321\213\320\261\320\276\321\200\320\260.xml" "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\222\321\213\320\261\320\276\321\200\320\260.xml" index 6f9f9427c24..737b09ec892 100644 --- "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\222\321\213\320\261\320\276\321\200\320\260.xml" +++ "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\222\321\213\320\261\320\276\321\200\320\260.xml" @@ -1,5 +1,5 @@  - +

ФормаВыбора @@ -13,8 +13,8 @@ Managed false - PersonalComputer - MobileDevice + PlatformApplication + MobilePlatformApplication
diff --git "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\222\321\213\320\261\320\276\321\200\320\260/Ext/Form.xml" "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\222\321\213\320\261\320\276\321\200\320\260/Ext/Form.xml" index 6202649bcaf..0372c191190 100644 --- "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\222\321\213\320\261\320\276\321\200\320\260/Ext/Form.xml" +++ "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\222\321\213\320\261\320\276\321\200\320\260/Ext/Form.xml" @@ -1,5 +1,5 @@  -
+ LockOwnerWindow @@ -23,6 +23,7 @@ true ExpandTopLevel true + AsFile Список Список.DefaultPicture false @@ -144,8 +145,6 @@ Normal b75fecce-942b-4aed-abc9-e6a02e460fb3 - Normal - 911b6018-f537-43e8-a417-da56b22f9aec diff --git "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\222\321\213\320\261\320\276\321\200\320\260/Ext/Form/Module.bsl" "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\222\321\213\320\261\320\276\321\200\320\260/Ext/Form/Module.bsl" index 9346b751efd..53f90c0ae1c 100644 --- "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\222\321\213\320\261\320\276\321\200\320\260/Ext/Form/Module.bsl" +++ "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\222\321\213\320\261\320\276\321\200\320\260/Ext/Form/Module.bsl" @@ -1,4 +1,4 @@ - + &НаКлиенте Процедура ВнешнееСобытие(Источник, Событие, Данные) diff --git "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\241\320\277\320\270\321\201\320\272\320\260.xml" "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\241\320\277\320\270\321\201\320\272\320\260.xml" index 10e894ea42c..3a191ee8be4 100644 --- "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\241\320\277\320\270\321\201\320\272\320\260.xml" +++ "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\241\320\277\320\270\321\201\320\272\320\260.xml" @@ -1,5 +1,5 @@  - + ФормаСписка @@ -13,8 +13,8 @@ Managed false - PersonalComputer - MobileDevice + PlatformApplication + MobilePlatformApplication diff --git "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\241\320\277\320\270\321\201\320\272\320\260/Ext/Form.xml" "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\241\320\277\320\270\321\201\320\272\320\260/Ext/Form.xml" index 7e5ed25c3df..5dfb799090a 100644 --- "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\241\320\277\320\270\321\201\320\272\320\260/Ext/Form.xml" +++ "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\241\320\277\320\270\321\201\320\272\320\260/Ext/Form.xml" @@ -1,5 +1,5 @@  -
+ @@ -21,6 +21,7 @@ true ExpandTopLevel true + AsFile Список Список.DefaultPicture false @@ -142,8 +143,6 @@ Normal b75fecce-942b-4aed-abc9-e6a02e460fb3 - Normal - 911b6018-f537-43e8-a417-da56b22f9aec diff --git "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\255\320\273\320\265\320\274\320\265\320\275\321\202\320\260.xml" "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\255\320\273\320\265\320\274\320\265\320\275\321\202\320\260.xml" index fa87e95322a..605c7a56b4f 100644 --- "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\255\320\273\320\265\320\274\320\265\320\275\321\202\320\260.xml" +++ "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\255\320\273\320\265\320\274\320\265\320\275\321\202\320\260.xml" @@ -1,5 +1,5 @@  - + ФормаЭлемента diff --git "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\255\320\273\320\265\320\274\320\265\320\275\321\202\320\260/Ext/Form.xml" "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\255\320\273\320\265\320\274\320\265\320\275\321\202\320\260/Ext/Form.xml" index 4f9cc18865d..0916909bfa1 100644 --- "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\255\320\273\320\265\320\274\320\265\320\275\321\202\320\260/Ext/Form.xml" +++ "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Forms/\320\244\320\276\321\200\320\274\320\260\320\255\320\273\320\265\320\274\320\265\320\275\321\202\320\260/Ext/Form.xml" @@ -1,5 +1,5 @@  - + LockOwnerWindow Items diff --git "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Templates/\320\234\320\260\320\272\320\265\321\202.xml" "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Templates/\320\234\320\260\320\272\320\265\321\202.xml" index 5c3bc8d9dee..ad77dfe09a4 100644 --- "a/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Templates/\320\234\320\260\320\272\320\265\321\202.xml" +++ "b/src/test/resources/metadata/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Templates/\320\234\320\260\320\272\320\265\321\202.xml" @@ -1,5 +1,5 @@  - +