Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Правило Отключение проверок всего модуля - DisableAllDiagnostics - ГОТОВО #3075

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions docs/diagnostics/DisableAllDiagnostics.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Отключение всех проверок модуля (DisableAllDiagnostics)

<!-- Блоки выше заполняются автоматически, не трогать -->
## Описание диагностики
<!-- Описание диагностики заполняется вручную. Необходимо понятным языком описать смысл и схему работу -->
Правило срабатывает на отключение проверки кода всего модуля через специальный комментарий `// BSLLS-off` или `BSLLS-выкл`
Copy link
Member

Choose a reason for hiding this comment

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

Сначала описать проблему и варианты решения, а логику работы описать ниже

Подобные отключения могут привести к пропуску важных и полезных замечаний по коду всего модуля и понижению качества решения на 1С.

Рекомендуется точечно отключать срабатывания конкретных правил на нужных строках через `// BSLLS:КлючДиагностики-off` или `// BSLLS:КлючДиагностики-выкл`
Например, `// BSLLS:MethodSize-off или // BSLLS:MethodSize-выкл`

Более подробную информацию смотрите в разделе документации [Экранирование кода от диагностик](https://1c-syntax.github.io/bsl-language-server/features/DiagnosticIgnorance/)

## Примеры
<!-- В данном разделе приводятся примеры, на которые диагностика срабатывает, а также можно привести пример, как можно исправить ситуацию -->

## Источники
<!-- Необходимо указывать ссылки на все источники, из которых почерпнута информация для создания диагностики -->
<!-- Примеры источников

* Источник: [Стандарт: Тексты модулей](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) -->
16 changes: 16 additions & 0 deletions docs/en/diagnostics/DisableAllDiagnostics.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Disable all diagnostics for module (DisableAllDiagnostics)

<!-- Блоки выше заполняются автоматически, не трогать -->
## Description
<!-- Описание диагностики заполняется вручную. Необходимо понятным языком описать смысл и схему работу -->

## Examples
<!-- В данном разделе приводятся примеры, на которые диагностика срабатывает, а также можно привести пример, как можно исправить ситуацию -->

## Sources
<!-- Необходимо указывать ссылки на все источники, из которых почерпнута информация для создания диагностики -->
<!-- Примеры источников

* Источник: [Стандарт: Тексты модулей](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) -->
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import com.github._1c_syntax.bsl.languageserver.context.symbol.annotations.Annotation;
import com.github._1c_syntax.bsl.languageserver.context.symbol.annotations.AnnotationKind;
import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCode;
import com.github._1c_syntax.bsl.languageserver.utils.Ranges;
import com.github._1c_syntax.bsl.parser.BSLLexer;
import com.github._1c_syntax.utils.CaseInsensitivePattern;
import edu.umd.cs.findbugs.annotations.Nullable;
Expand All @@ -37,6 +38,7 @@
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
Expand Down Expand Up @@ -74,6 +76,7 @@ public class DiagnosticIgnoranceComputer implements Computer<DiagnosticIgnorance

private final Map<DiagnosticCode, List<Range<Integer>>> diagnosticIgnorance = new HashMap<>();
private final Map<DiagnosticCode, Deque<Integer>> ignoranceStack = new HashMap<>();
private final List<org.eclipse.lsp4j.Range> ignoreOffList = new ArrayList<>();
Copy link
Member

Choose a reason for hiding this comment

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

это какой-то не тот рендж

Copy link
Member

Choose a reason for hiding this comment

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

Copy link
Member

Choose a reason for hiding this comment

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

Не вижу причин хранить это отдельно. Вся инфа есть в Data классе по ключу DiagnosticCode("all")


public DiagnosticIgnoranceComputer(DocumentContext documentContext) {
this.documentContext = documentContext;
Expand All @@ -86,14 +89,12 @@ public Data compute() {
ignoranceStack.clear();

List<Token> codeTokens = documentContext.getTokensFromDefaultChannel();
if (codeTokens.isEmpty()) {
return new Data(diagnosticIgnorance);
if (!codeTokens.isEmpty()) {
computeCommentsIgnorance(codeTokens);
computeExtensionIgnorance();
}
return new Data(diagnosticIgnorance, ignoreOffList);

computeCommentsIgnorance(codeTokens);
computeExtensionIgnorance();

return new Data(diagnosticIgnorance);
}

private void computeExtensionIgnorance() {
Expand Down Expand Up @@ -197,6 +198,10 @@ private DiagnosticCode checkIgnoreOff(
Deque<Integer> stack = ignoranceStack.computeIfAbsent(key, s -> new ArrayDeque<>());
stack.push(comment.getLine());

if (ignoreOff.equals(IGNORE_ALL_OFF)){
Copy link
Member

Choose a reason for hiding this comment

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

отформатировать

ignoreOffList.add(Ranges.create(comment));
}

return key;
}

Expand Down Expand Up @@ -245,6 +250,11 @@ private static DiagnosticCode getKey(Matcher matcher) {
@AllArgsConstructor
public static class Data {
private final Map<DiagnosticCode, List<Range<Integer>>> diagnosticIgnorance;
private final List<org.eclipse.lsp4j.Range> ignoreOffList;

public List<org.eclipse.lsp4j.Range> getIgnoreOffList() {
return Collections.unmodifiableList(ignoreOffList);
}

public boolean diagnosticShouldBeIgnored(Diagnostic diagnostic) {
if (diagnosticIgnorance.isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* This file is a part of BSL Language Server.
*
* Copyright (c) 2018-2023
* Alexey Sosnoviy <[email protected]>, Nikita Fedkin <[email protected]> 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.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;

@DiagnosticMetadata(
type = DiagnosticType.CODE_SMELL,
severity = DiagnosticSeverity.MAJOR,
minutesToFix = 1,
tags = {
DiagnosticTag.BADPRACTICE,
DiagnosticTag.SUSPICIOUS
}

)
public class DisableAllDiagnosticsDiagnostic extends AbstractDiagnostic {

@Override
protected void check() {
documentContext.getDiagnosticIgnorance().getIgnoreOffList()
.forEach(diagnosticStorage::addDiagnostic);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -500,6 +500,16 @@
"title": "Deprecated ManagedForm type",
"$id": "#/definitions/DeprecatedTypeManagedForm"
},
"DisableAllDiagnostics": {
"description": "Disable all diagnostics for module",
"default": true,
"type": [
"boolean",
"object"
],
"title": "Disable all diagnostics for module",
"$id": "#/definitions/DisableAllDiagnostics"
},
"DuplicateRegion": {
"description": "Duplicate regions",
"default": true,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
diagnosticMessage=Check disabling the analysis of the entire module
diagnosticName=Disable all diagnostics for module
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
diagnosticMessage=Проверьте отключение анализа всего модуля
diagnosticName=Отключение всех проверок модуля
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* This file is a part of BSL Language Server.
*
* Copyright (c) 2018-2023
* Alexey Sosnoviy <[email protected]>, Nikita Fedkin <[email protected]> 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;
import static com.github._1c_syntax.bsl.languageserver.util.TestUtils.getDocumentContextFromFile;

class DisableAllDiagnosticsDiagnosticTest extends AbstractDiagnosticTest<DisableAllDiagnosticsDiagnostic> {
DisableAllDiagnosticsDiagnosticTest() {
super(DisableAllDiagnosticsDiagnostic.class);
}

@Test
void test() {

String filePath = "./src/test/resources/context/computer/DiagnosticIgnoranceComputerTest.bsl";
final var documentContext = getDocumentContextFromFile(filePath);

List<Diagnostic> diagnostics = getDiagnostics(documentContext);

assertThat(diagnostics).hasSize(2);
assertThat(diagnostics, true)
.hasRange(0, 0, 12)
.hasRange(33, 0, 13);
}

@Test
void testOnAndOff() {
Copy link
Member

Choose a reason for hiding this comment

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

добавить тесты

  • ТОЛЬКО отключение в начале модуля
  • несколько включений \ отлкючений в модуле


List<Diagnostic> diagnostics = getDiagnostics();

assertThat(diagnostics).hasSize(1);
assertThat(diagnostics, true)
.hasRange(9, 0, 13);
}
}
11 changes: 11 additions & 0 deletions src/test/resources/diagnostics/DisableAllDiagnosticsDiagnostic.bsl
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
//

Если Истина Тогда
//а
А = 0
КонецЕсли;

// BSLLS-on

// BSLLS-выкл
// BSLLS-вкл
Loading