Skip to content

Commit ee42006

Browse files
authored
Merge pull request #1635 from huxuxuya/feature/IncorrectLineBreak
2 parents cdb4a78 + cf8b460 commit ee42006

File tree

13 files changed

+429
-5
lines changed

13 files changed

+429
-5
lines changed

.idea/libraries-with-intellij-classes.xml

Lines changed: 65 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/misc.xml

Lines changed: 2 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Неправильный перенос выражения (IncorrectLineBreak)
2+
3+
Тип | Поддерживаются<br>языки | Важность | Включена<br>по умолчанию | Время на<br>исправление (мин) | Тэги
4+
:-: | :-: | :-: | :-: | :-: | :-:
5+
`Дефект кода` | `BSL`<br>`OS` | `Информационный` | `Да` | `2` | `standard`<br>`badpractice`
6+
7+
<!-- Блоки выше заполняются автоматически, не трогать -->
8+
## Описание диагностики
9+
<!-- Описание диагностики заполняется вручную. Необходимо понятным языком описать смысл и схему работу -->
10+
11+
Длинные арифметические выражения переносятся следующим образом:
12+
в одной строке может находиться более одного операнда;
13+
при переносе знаки операции пишутся в начале строки (а не в конце предыдущей строки);
14+
операнды на новой строке предваряются стандартным отступом, либо выравниваются по началу первого операнда без учета знаков операций.
15+
16+
При необходимости параметры процедур, функций и методов следует переносить следующим образом:
17+
18+
* параметры выравниваются по началу первого параметра, либо предваряются стандартным отступом;
19+
* закрывающая скобка и разделитель операторов ";" пишутся в той же строке, что и последний параметр;
20+
* также допустим и способ форматирования, который предлагает функция автоформатирования в конфигураторе
21+
22+
Сложные логические условия в Если…ИначеЕсли…КонецЕсли следует переносить следующим образом:
23+
24+
* каждое элементарное условие нужно начинать с новой строки, если длина строки превышает ограничение в 120 символов;
25+
* логические операторы И, ИЛИ ставятся в начале строки, а не в конце предыдущей строки;
26+
* все условия предваряются стандартным отступом, либо выравниваются по началу первого условия, без учета логического оператора (для выравнивания выражений относительно первой строки рекомендуется использовать пробелы).
27+
28+
## Примеры
29+
<!-- В данном разделе приводятся примеры, на которые диагностика срабатывает, а также можно привести пример, как можно исправить ситуацию -->
30+
31+
```bsl
32+
СуммаДокумента = СуммаБезСкидки +
33+
СуммаРучнойСкидки +
34+
СуммаАвтоматическойСкидки;
35+
```
36+
37+
## Источники
38+
<!-- Необходимо указывать ссылки на все источники, из которых почерпнута информация для создания диагностики -->
39+
40+
* Источник: [Стандарт: Перенос выражений](https://its.1c.ru/db/v8std#content:444:hdoc)
41+
42+
## Сниппеты
43+
44+
<!-- Блоки ниже заполняются автоматически, не трогать -->
45+
### Экранирование кода
46+
47+
```bsl
48+
// BSLLS:IncorrectLineBreak-off
49+
// BSLLS:IncorrectLineBreak-on
50+
```
51+
52+
### Параметр конфигурационного файла
53+
54+
```json
55+
"IncorrectLineBreak": false
56+
```

docs/diagnostics/index.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,12 @@
88

99
## Список реализованных диагностик
1010

11-
Общее количество: **140**
11+
Общее количество: **141**
1212

1313
* Потенциальная уязвимость: **4**
1414
* Уязвимость: **3**
1515
* Ошибка: **44**
16-
* Дефект кода: **89**
16+
* Дефект кода: **90**
1717

1818

1919
| Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги |
@@ -76,6 +76,7 @@
7676
[IfElseDuplicatedCodeBlock](IfElseDuplicatedCodeBlock.md) | Повторяющиеся блоки кода в синтаксической конструкции Если...Тогда...ИначеЕсли... | Да | Незначительный | Дефект кода | `suspicious`
7777
[IfElseDuplicatedCondition](IfElseDuplicatedCondition.md) | Повторяющиеся условия в синтаксической конструкции Если...Тогда...ИначеЕсли... | Да | Важный | Дефект кода | `suspicious`
7878
[IfElseIfEndsWithElse](IfElseIfEndsWithElse.md) | Использование синтаксической конструкции Если...Тогда...ИначеЕсли... | Да | Важный | Дефект кода | `badpractice`
79+
[IncorrectLineBreak](IncorrectLineBreak.md) | Неправильный перенос выражения | Да | Информационный | Дефект кода | `standard`<br>`badpractice`
7980
[IncorrectUseLikeInQuery](IncorrectUseLikeInQuery.md) | Некорректное использование 'ПОДОБНО' | Да | Критичный | Ошибка | `standard`<br>`sql`<br>`unpredictable`
8081
[IncorrectUseOfStrTemplate](IncorrectUseOfStrTemplate.md) | Неверное использование "СтрШаблон" | Да | Блокирующий | Ошибка | `brainoverload`<br>`suspicious`<br>`unpredictable`
8182
[InvalidCharacterInFile](InvalidCharacterInFile.md) | Недопустимый символ | Да | Важный | Ошибка | `error`<br>`standard`<br>`unpredictable`
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Incorrect expression line break (IncorrectLineBreak)
2+
3+
Type | Scope | Severity | Activated<br>by default | Minutes<br>to fix | Tags
4+
:-: | :-: | :-: | :-: | :-: | :-:
5+
`Code smell` | `BSL`<br>`OS` | `Info` | `Yes` | `2` | `standard`<br>`badpractice`
6+
7+
<!-- Блоки выше заполняются автоматически, не трогать -->
8+
## Description
9+
10+
Long arithmetic expressions are carried as follows:
11+
one entry can contain more than one operand;
12+
when wrapping, operation characters are written at the beginning of the line (and not at the end of the previous line);
13+
operands on a new line are preceded by standard indentation, or they are aligned to the beginning of the first operand, regardless of the operation signs.
14+
15+
If necessary, parameters of procedures, functions and methods should be transferred as follows:
16+
17+
* parameters are either aligned to the beginning of the first parameter, or preceded by standard indentation;
18+
* closing parenthesis and operator separator ";" are written on the same line as the last parameter;
19+
* the formatting method that offers the auto-formatting function in the configurator is also acceptable
20+
21+
Complex logical conditions in If ... ElseIf ... EndIf should be carried as follows:
22+
23+
* The basis for the newline if the line length is limited to 120 characters;
24+
* logical operators AND, OR are placed at the beginning of a line, and not at the end of the previous line;
25+
* all conditions are preceded by the standard first indent, or they are aligned at the start of work without taking into account the logical operator (it is recommended to use spaces to align expressions relative to the first line).
26+
27+
## Examples
28+
<!-- В данном разделе приводятся примеры, на которые диагностика срабатывает, а также можно привести пример, как можно исправить ситуацию -->
29+
30+
```bsl
31+
AmountDocument = AmountWithoutDiscount +
32+
AmountManualDiscounts +
33+
AmountAutomaticDiscount;
34+
```
35+
36+
## Sources
37+
<!-- Необходимо указывать ссылки на все источники, из которых почерпнута информация для создания диагностики -->
38+
39+
* Источник: [Стандарт: Перенос выражений (RU)](https://its.1c.ru/db/v8std#content:444:hdoc)
40+
41+
## Snippets
42+
43+
<!-- Блоки ниже заполняются автоматически, не трогать -->
44+
### Diagnostic ignorance in code
45+
46+
```bsl
47+
// BSLLS:IncorrectLineBreak-off
48+
// BSLLS:IncorrectLineBreak-on
49+
```
50+
51+
### Parameter for config
52+
53+
```json
54+
"IncorrectLineBreak": false
55+
```

docs/en/diagnostics/index.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,12 @@ To escape individual sections of code or files from triggering diagnostics, you
88

99
## Implemented diagnostics
1010

11-
Total: **140**
11+
Total: **141**
1212

1313
* Security Hotspot: **4**
1414
* Vulnerability: **3**
1515
* Error: **44**
16-
* Code smell: **89**
16+
* Code smell: **90**
1717

1818

1919
| Key | Name| Enabled by default | Severity | Type | Tags |
@@ -76,6 +76,7 @@ Total: **140**
7676
[IfElseDuplicatedCodeBlock](IfElseDuplicatedCodeBlock.md) | Duplicated code blocks in If...Then...ElseIf... statements | Yes | Minor | Code smell | `suspicious`
7777
[IfElseDuplicatedCondition](IfElseDuplicatedCondition.md) | Duplicated conditions in If...Then...ElseIf... statements | Yes | Major | Code smell | `suspicious`
7878
[IfElseIfEndsWithElse](IfElseIfEndsWithElse.md) | Else...The...ElseIf... statement should end with Else branch | Yes | Major | Code smell | `badpractice`
79+
[IncorrectLineBreak](IncorrectLineBreak.md) | Incorrect expression line break | Yes | Info | Code smell | `standard`<br>`badpractice`
7980
[IncorrectUseLikeInQuery](IncorrectUseLikeInQuery.md) | Incorrect use of 'LIKE' | Yes | Critical | Error | `standard`<br>`sql`<br>`unpredictable`
8081
[IncorrectUseOfStrTemplate](IncorrectUseOfStrTemplate.md) | Incorrect use of "StrTemplate" | Yes | Blocker | Error | `brainoverload`<br>`suspicious`<br>`unpredictable`
8182
[InvalidCharacterInFile](InvalidCharacterInFile.md) | Invalid character | Yes | Major | Error | `error`<br>`standard`<br>`unpredictable`
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/*
2+
* This file is a part of BSL Language Server.
3+
*
4+
* Copyright © 2018-2021
5+
* Alexey Sosnoviy <labotamy@gmail.com>, Nikita Gryzlov <nixel2007@gmail.com> and contributors
6+
*
7+
* SPDX-License-Identifier: LGPL-3.0-or-later
8+
*
9+
* BSL Language Server is free software; you can redistribute it and/or
10+
* modify it under the terms of the GNU Lesser General Public
11+
* License as published by the Free Software Foundation; either
12+
* version 3.0 of the License, or (at your option) any later version.
13+
*
14+
* BSL Language Server is distributed in the hope that it will be useful,
15+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
16+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17+
* Lesser General Public License for more details.
18+
*
19+
* You should have received a copy of the GNU Lesser General Public
20+
* License along with BSL Language Server.
21+
*/
22+
package com.github._1c_syntax.bsl.languageserver.diagnostics;
23+
24+
import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata;
25+
import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity;
26+
import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag;
27+
import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType;
28+
import com.github._1c_syntax.utils.CaseInsensitivePattern;
29+
30+
import java.util.HashSet;
31+
import java.util.Set;
32+
import java.util.regex.Pattern;
33+
34+
@DiagnosticMetadata(
35+
type = DiagnosticType.CODE_SMELL,
36+
severity = DiagnosticSeverity.INFO,
37+
minutesToFix = 2,
38+
tags = {
39+
DiagnosticTag.STANDARD,
40+
DiagnosticTag.BADPRACTICE
41+
}
42+
)
43+
public class IncorrectLineBreakDiagnostic extends AbstractDiagnostic {
44+
45+
private static final Pattern INCORRECT_START_LINE_PATTERN = CaseInsensitivePattern.compile(
46+
"^\\s*(:?\\)|;|,|\\);)"
47+
);
48+
49+
private static final Pattern INCORRECT_END_LINE_PATTERN = CaseInsensitivePattern.compile(
50+
"\\s+(:?ИЛИ|И|OR|AND|\\+|-|/|%|\\*)\\s*(?://.*)?$"
51+
);
52+
53+
// +1 for next line and +1 for 1..n based line numbers.
54+
private static final int QUERY_START_LINE_OFFSET = 2;
55+
56+
private final Set<Integer> queryFirstLines = new HashSet<>();
57+
58+
@Override
59+
protected void check() {
60+
findQueryFirstLines();
61+
62+
checkContent(INCORRECT_START_LINE_PATTERN);
63+
checkContent(INCORRECT_END_LINE_PATTERN);
64+
}
65+
66+
private void findQueryFirstLines() {
67+
documentContext.getQueries().forEach(query -> queryFirstLines.add(query.getAst().getStart().getLine()));
68+
}
69+
70+
private void checkContent(Pattern pattern) {
71+
String[] contentList = documentContext.getContentList();
72+
String checkText;
73+
74+
for (var i = 0; i < contentList.length; i++) {
75+
checkText = contentList[i];
76+
77+
var matcher = pattern.matcher(checkText);
78+
79+
if (matcher.find() && !queryFirstLines.contains(i + QUERY_START_LINE_OFFSET)) {
80+
diagnosticStorage.addDiagnostic(i + 1, matcher.start(1), i + 1, matcher.end(1));
81+
}
82+
}
83+
}
84+
}

src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -682,6 +682,16 @@
682682
"title": "Else...The...ElseIf... statement should end with Else branch",
683683
"$id": "#/definitions/IfElseIfEndsWithElse"
684684
},
685+
"IncorrectLineBreak": {
686+
"description": "Incorrect expression line break",
687+
"default": true,
688+
"type": [
689+
"boolean",
690+
"object"
691+
],
692+
"title": "Incorrect expression line break",
693+
"$id": "#/definitions/IncorrectLineBreak"
694+
},
685695
"IncorrectUseLikeInQuery": {
686696
"description": "Incorrect use of 'LIKE'",
687697
"default": true,

src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,9 @@
197197
"IfElseIfEndsWithElse": {
198198
"$ref": "parameters-schema.json#/definitions/IfElseIfEndsWithElse"
199199
},
200+
"IncorrectLineBreak": {
201+
"$ref": "parameters-schema.json#/definitions/IncorrectLineBreak"
202+
},
200203
"IncorrectUseLikeInQuery": {
201204
"$ref": "parameters-schema.json#/definitions/IncorrectUseLikeInQuery"
202205
},
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
diagnosticMessage=Check for line break of operands, operators and parameters
2+
diagnosticName=Incorrect expression line break

0 commit comments

Comments
 (0)