-
Notifications
You must be signed in to change notification settings - Fork 109
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3187 from AlexPCRus/alexpc-patch-2
Новая диагностика "Зарезервированные имена параметров"
- Loading branch information
Showing
9 changed files
with
238 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
# Зарезервированные имена параметра (ReservedParameterNames) | ||
|
||
<!-- Блоки выше заполняются автоматически, не трогать --> | ||
## Описание диагностики | ||
Если имя параметра совпадает с именем системного перечисления, то невозможно будет обратиться к значениям этого системного перечисления, потому что параметр его скроет. | ||
Синтаксическая проверка кода модуля не выявит такую ошибку. Чтобы предотвратить эту ситуацию имя параметра не должно совпадать с именами системных перечислений. | ||
Список зарезервированных слов задается регулярным выражением. | ||
Поиск производится без учета регистра символов. | ||
|
||
**Примеры настройки:** | ||
|
||
"ВидГруппыФормы|ВидПоляФормы" | ||
|
||
## Источники | ||
<!-- Необходимо указывать ссылки на все источники, из которых почерпнута информация для создания диагностики --> | ||
|
||
* Источник: [Стандарт: Параметры процедур и функций](https://its.1c.ru/db/v8std/content/640/hdoc) | ||
* Источник: [Стандарт: Правила образования имен переменных](https://its.1c.ru/db/v8std#content:454:hdoc) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
# Reserved parameter names (ReservedParameterNames) | ||
|
||
<!-- Блоки выше заполняются автоматически, не трогать --> | ||
## Description | ||
|
||
|
||
If a parameter name matches one of a system enumeration's name, then all values of that enumeration will not be available in the local context. | ||
Module code's syntax checking will not detect an error. To prevent this situation, a parameter name should not match all names of system enumerations. | ||
|
||
Parameter names should not contain reserved words such as system enumerations. | ||
The list of reserved words is set by a regular expression. | ||
The search is case-insensitive. | ||
|
||
**For example:** | ||
|
||
"FormGroupType|FormFieldType" | ||
|
||
## Sources | ||
<!-- Необходимо указывать ссылки на все источники, из которых почерпнута информация для создания диагностики --> | ||
|
||
* Source: [Standard: Procedure and Function Parameters (RU)](https://its.1c.ru/db/v8std/content/640/hdoc) | ||
* Source: [Standard: Rules for generating variable names (RU)](https://its.1c.ru/db/v8std#content:454:hdoc) |
89 changes: 89 additions & 0 deletions
89
...om/github/_1c_syntax/bsl/languageserver/diagnostics/ReservedParameterNamesDiagnostic.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
/* | ||
* This file is a part of BSL Language Server. | ||
* | ||
* Copyright (c) 2018-2024 | ||
* 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.context.symbol.MethodSymbol; | ||
import com.github._1c_syntax.bsl.languageserver.context.symbol.ParameterDefinition; | ||
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.utils.CaseInsensitivePattern; | ||
|
||
import java.util.List; | ||
import java.util.Map; | ||
import java.util.regex.Pattern; | ||
|
||
@DiagnosticMetadata( | ||
type = DiagnosticType.CODE_SMELL, | ||
severity = DiagnosticSeverity.MAJOR, | ||
minutesToFix = 5, | ||
tags = { | ||
DiagnosticTag.STANDARD, | ||
DiagnosticTag.BADPRACTICE | ||
} | ||
) | ||
public class ReservedParameterNamesDiagnostic extends AbstractSymbolTreeDiagnostic { | ||
|
||
private static final String RESERVED_WORDS_DEFAULT = ""; | ||
|
||
@DiagnosticParameter(type = String.class) | ||
private Pattern reservedWords = CaseInsensitivePattern.compile(RESERVED_WORDS_DEFAULT); | ||
|
||
@Override | ||
public void configure(Map<String, Object> configuration) { | ||
|
||
var incomingMask = (String) configuration.getOrDefault("reservedWords", RESERVED_WORDS_DEFAULT); | ||
|
||
this.reservedWords = CaseInsensitivePattern.compile("^" + incomingMask.trim() + "$"); | ||
} | ||
|
||
@Override | ||
protected void check() { | ||
|
||
if (reservedWords.pattern().isBlank()) { | ||
return; | ||
} | ||
super.check(); | ||
} | ||
|
||
@Override | ||
public void visitMethod(MethodSymbol methodSymbol) { | ||
|
||
List<ParameterDefinition> parameters = methodSymbol.getParameters(); | ||
checkParameterName(parameters); | ||
} | ||
|
||
private void checkParameterName(List<ParameterDefinition> parameters) { | ||
|
||
parameters.forEach((ParameterDefinition parameter) -> { | ||
|
||
var matcher = reservedWords.matcher(parameter.getName()); | ||
if (matcher.find()) { | ||
diagnosticStorage.addDiagnostic(parameter.getRange(), info.getMessage(parameter.getName())); | ||
} | ||
}); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
3 changes: 3 additions & 0 deletions
3
.../_1c_syntax/bsl/languageserver/diagnostics/ReservedParameterNamesDiagnostic_en.properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
diagnosticMessage=Rename parameter "%s" that matches one of reserved words. | ||
diagnosticName=Reserved parameter names | ||
reservedWords=Regular expression for reserved parameter names. |
3 changes: 3 additions & 0 deletions
3
.../_1c_syntax/bsl/languageserver/diagnostics/ReservedParameterNamesDiagnostic_ru.properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
diagnosticMessage=Переименуйте параметр "%s" так, чтобы он не совпадал с зарезервированным словом. | ||
diagnosticName=Зарезервированные имена параметров | ||
reservedWords=Регулярное выражение для зарезервированных имен параметров. |
75 changes: 75 additions & 0 deletions
75
...java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ReservedParameterNamesTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
/* | ||
* This file is a part of BSL Language Server. | ||
* | ||
* Copyright (c) 2018-2024 | ||
* 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 java.util.Map; | ||
|
||
import org.junit.jupiter.params.ParameterizedTest; | ||
import org.junit.jupiter.params.provider.ValueSource; | ||
|
||
import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; | ||
|
||
class ReservedParameterNamesDiagnosticTest extends AbstractDiagnosticTest<ReservedParameterNamesDiagnostic> { | ||
ReservedParameterNamesDiagnosticTest() { | ||
super(ReservedParameterNamesDiagnostic.class); | ||
} | ||
|
||
@Test | ||
void testEmpty() { | ||
List<Diagnostic> diagnostics = getDiagnostics(); | ||
assertThat(diagnostics).isEmpty(); | ||
} | ||
|
||
@Test | ||
void testPositive() { | ||
|
||
Map<String, Object> configuration = diagnosticInstance.info.getDefaultConfiguration(); | ||
configuration.put("reservedWords", "ВидГруппыФормы"); | ||
diagnosticInstance.configure(configuration); | ||
|
||
List<Diagnostic> diagnostics = getDiagnostics(); | ||
|
||
assertThat(diagnostics).hasSize(1); | ||
assertThat(diagnostics, true) | ||
.hasMessageOnRange("Переименуйте параметр \"ВидГруппыФормы\" чтобы он не совпадал с зарезервированным словом.", | ||
2, 16, 30); | ||
|
||
} | ||
|
||
@ParameterizedTest | ||
@ValueSource(strings = {" ", "ВидГруппы", "ВидГруппыФормыРасширенный"}) | ||
void testNegative(String testWord) { | ||
|
||
Map<String, Object> configuration = diagnosticInstance.info.getDefaultConfiguration(); | ||
configuration.put("reservedWords", testWord); | ||
diagnosticInstance.configure(configuration); | ||
|
||
List<Diagnostic> diagnostics = getDiagnostics(); | ||
assertThat(diagnostics).isEmpty(); | ||
|
||
} | ||
|
||
} |
7 changes: 7 additions & 0 deletions
7
src/test/resources/diagnostics/ReservedParameterNamesDiagnostic.bsl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
// при наличии в списке зарезервированного имени перечисления ВидГруппыФормы должен сработать тест | ||
|
||
Процедура Тест1(ВидГруппыФормы) // здесь должен сработать тест | ||
|
||
А = ВидГруппыФормы.ОбычнаяГруппа; | ||
|
||
КонецПроцедуры |