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

Add useless ternary operator diagnostic #1820

Open
wants to merge 8 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
47 changes: 47 additions & 0 deletions docs/diagnostics/UselessTernaryOperator.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Бесполезный тернарный оператор (UselessTernaryOperator)

| Тип | Поддерживаются<br>языки | Важность | Включена<br>по умолчанию | Время на<br>исправление (мин) | Теги |
|:-------------:|:-----------------------------:|:----------------:|:------------------------------:|:-----------------------------------:|:-----------------------------------:|
| `Дефект кода` | `BSL` | `Информационный` | `Да` | `1` | `badpractice`<br>`suspicious` |

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

## Примеры
Бессмысленные операторы

```Bsl
А = ?(Истина, 1, 0);
```
```Bsl
А = ?(Б = 1, Истина, Ложь);
```
```Bsl
А = ?(Б = 0, False, True);
```

Подозрительные операторы

```Bsl
А = ?(Б = 1, True, Истина);
```
```Bsl
А = ?(Б = 0, 0, False);
```

## Сниппеты

<!-- Блоки ниже заполняются автоматически, не трогать -->
### Экранирование кода

```bsl
// BSLLS:UselessTernaryOperator-off
// BSLLS:UselessTernaryOperator-on
```

### Параметр конфигурационного файла

```json
"UselessTernaryOperator": false
```
5 changes: 3 additions & 2 deletions docs/diagnostics/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@

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

Общее количество: **145**
Общее количество: **146**

* Потенциальная уязвимость: **4**
* Уязвимость: **4**
* Ошибка: **44**
* Дефект кода: **93**
* Дефект кода: **94**


| Ключ | Название | Включена по умолчанию | Важность | Тип | Тэги |
Expand Down Expand Up @@ -146,6 +146,7 @@
[UnusedParameters](UnusedParameters.md) | Неиспользуемый параметр | Да | Важный | Дефект кода | `design`<br>`unused`
[UsageWriteLogEvent](UsageWriteLogEvent.md) | Неверное использование метода "ЗаписьЖурналаРегистрации" | Да | Информационный | Дефект кода | `standard`<br>`badpractice`
[UseLessForEach](UseLessForEach.md) | Бесполезный перебор коллекции | Да | Критичный | Ошибка | `clumsy`
[UselessTernaryOperator](UselessTernaryOperator.md) | Бесполезный тернарный оператор | Да | Информационный | Дефект кода | `badpractice`<br>`suspicious`
[UsingCancelParameter](UsingCancelParameter.md) | Работа с параметром "Отказ" | Да | Важный | Дефект кода | `standard`<br>`badpractice`
[UsingExternalCodeTools](UsingExternalCodeTools.md) | Использование возможностей выполнения внешнего кода | Да | Критичный | Потенциальная уязвимость | `standard`<br>`design`
[UsingFindElementByString](UsingFindElementByString.md) | Использование методов "НайтиПоНаименованию" и "НайтиПоКоду" | Да | Важный | Дефект кода | `standard`<br>`badpractice`<br>`performance`
Expand Down
47 changes: 47 additions & 0 deletions docs/en/diagnostics/UselessTernaryOperator.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Useless ternary operator (UselessTernaryOperator)

| Type | Scope | Severity | Activated<br>by default | Minutes<br>to fix | Tags |
|:------------:|:-----:|:--------:|:-----------------------------:|:-----------------------:|:-----------------------------------:|
| `Code smell` | `BSL` | `Info` | `Yes` | `1` | `badpractice`<br>`suspicious` |

<!-- Блоки выше заполняются автоматически, не трогать -->
## Description
The placement of Boolean constants "True" or "False" in the ternary operator indicates poor code thoughtfulness.

## Examples
Useless operators

```Bsl
A = ?(True, 1, 0);
```
```Bsl
A = ?(B = 1, True, False);
```
```Bsl
A = ?(B = 0, False, True);
```

Suspicious operators

```Bsl
A = ?(B = 1, True, True);
```
```Bsl
A = ?(B = 0, 0, False);
```

## Snippets

<!-- Блоки ниже заполняются автоматически, не трогать -->
### Diagnostic ignorance in code

```bsl
// BSLLS:UselessTernaryOperator-off
// BSLLS:UselessTernaryOperator-on
```

### Parameter for config

```json
"UselessTernaryOperator": false
```
5 changes: 3 additions & 2 deletions docs/en/diagnostics/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ To escape individual sections of code or files from triggering diagnostics, you

## Implemented diagnostics

Total: **145**
Total: **146**

* Security Hotspot: **4**
* Vulnerability: **4**
* Error: **44**
* Code smell: **93**
* Code smell: **94**


| Key | Name| Enabled by default | Severity | Type | Tags |
Expand Down Expand Up @@ -146,6 +146,7 @@ Total: **145**
[UnusedParameters](UnusedParameters.md) | Unused parameter | Yes | Major | Code smell | `design`<br>`unused`
[UsageWriteLogEvent](UsageWriteLogEvent.md) | Incorrect use of the method | Yes | Info | Code smell | `standard`<br>`badpractice`
[UseLessForEach](UseLessForEach.md) | Useless collection iteration | Yes | Critical | Error | `clumsy`
[UselessTernaryOperator](UselessTernaryOperator.md) | Useless ternary operator | Yes | Info | Code smell | `badpractice`<br>`suspicious`
[UsingCancelParameter](UsingCancelParameter.md) | Using parameter "Cancel" | Yes | Major | Code smell | `standard`<br>`badpractice`
[UsingExternalCodeTools](UsingExternalCodeTools.md) | Using external code tools | Yes | Critical | Security Hotspot | `standard`<br>`design`
[UsingFindElementByString](UsingFindElementByString.md) | Using FindByName and FindByCode | Yes | Major | Code smell | `standard`<br>`badpractice`<br>`performance`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

Expand All @@ -56,150 +57,155 @@ public void clearDiagnostics() {
diagnosticList.clear();
}

protected void addDiagnostic(BSLParserRuleContext node) {
protected Optional<Diagnostic> addDiagnostic(BSLParserRuleContext node) {
if (node.exception != null) {
return;
return Optional.empty();
}

addDiagnostic(
return addDiagnostic(
Ranges.create(node)
);
}

protected void addDiagnostic(BSLParserRuleContext node, String diagnosticMessage) {
protected Optional<Diagnostic> addDiagnostic(BSLParserRuleContext node, String diagnosticMessage) {
if (node.exception != null) {
return;
return Optional.empty();
}

addDiagnostic(
return addDiagnostic(
Ranges.create(node),
diagnosticMessage
);
}

protected void addDiagnostic(int startLine, int startChar, int endLine, int endChar) {
addDiagnostic(
protected Optional<Diagnostic> addDiagnostic(int startLine, int startChar, int endLine, int endChar) {
return addDiagnostic(
Ranges.create(startLine, startChar, endLine, endChar)
);
}

protected void addDiagnostic(Range range) {
addDiagnostic(
protected Optional<Diagnostic> addDiagnostic(Range range) {
return addDiagnostic(
range,
diagnostic.getInfo().getMessage()
);
}

protected void addDiagnostic(Range range, String diagnosticMessage) {
addDiagnostic(
protected Optional<Diagnostic> addDiagnostic(Range range, String diagnosticMessage) {
return addDiagnostic(
range,
diagnosticMessage,
null
);
}

protected void addDiagnostic(Token token) {
addDiagnostic(
protected Optional<Diagnostic> addDiagnostic(Token token) {
return addDiagnostic(
Ranges.create(token)
);
}

protected void addDiagnostic(Token startToken, Token endToken) {
addDiagnostic(
protected Optional<Diagnostic> addDiagnostic(Token startToken, Token endToken) {
return addDiagnostic(
Ranges.create(startToken, endToken)
);
}

protected void addDiagnostic(Token token, String diagnosticMessage) {
addDiagnostic(
protected Optional<Diagnostic> addDiagnostic(Token token, String diagnosticMessage) {
return addDiagnostic(
Ranges.create(token),
diagnosticMessage
);
}

protected void addDiagnostic(TerminalNode terminalNode) {
addDiagnostic(terminalNode.getSymbol());
protected Optional<Diagnostic> addDiagnostic(TerminalNode terminalNode) {
return addDiagnostic(terminalNode.getSymbol());
}

protected void addDiagnostic(TerminalNode terminalNode, String diagnosticMessage) {
addDiagnostic(terminalNode.getSymbol(), diagnosticMessage);
protected Optional<Diagnostic> addDiagnostic(TerminalNode terminalNode, String diagnosticMessage) {
return addDiagnostic(terminalNode.getSymbol(), diagnosticMessage);
}

protected void addDiagnostic(TerminalNode startTerminalNode, TerminalNode stopTerminalNode) {
addDiagnostic(startTerminalNode.getSymbol(), stopTerminalNode.getSymbol());
protected Optional<Diagnostic> addDiagnostic(TerminalNode startTerminalNode, TerminalNode stopTerminalNode) {
return addDiagnostic(startTerminalNode.getSymbol(), stopTerminalNode.getSymbol());
}

protected void addDiagnostic(BSLParserRuleContext node, List<DiagnosticRelatedInformation> relatedInformation) {
protected Optional<Diagnostic> addDiagnostic(BSLParserRuleContext node, List<DiagnosticRelatedInformation> relatedInformation) {
if (node.exception != null) {
return;
return Optional.empty();
}

addDiagnostic(
return addDiagnostic(
node,
diagnostic.getInfo().getMessage(),
relatedInformation
);
}

public void addDiagnostic(Token token, List<DiagnosticRelatedInformation> relatedInformation) {
addDiagnostic(
public Optional<Diagnostic> addDiagnostic(Token token, List<DiagnosticRelatedInformation> relatedInformation) {
return addDiagnostic(
token,
diagnostic.getInfo().getMessage(),
relatedInformation
);
}

public void addDiagnostic(
public Optional<Diagnostic> addDiagnostic(
BSLParserRuleContext node,
String diagnosticMessage,
List<DiagnosticRelatedInformation> relatedInformation
) {

if (node.exception != null) {
return;
return Optional.empty();
}

addDiagnostic(
return addDiagnostic(
Ranges.create(node),
diagnosticMessage,
relatedInformation
);
}

public void addDiagnostic(
public Optional<Diagnostic> addDiagnostic(
Token token,
String diagnosticMessage,
List<DiagnosticRelatedInformation> relatedInformation
) {
addDiagnostic(
return addDiagnostic(
Ranges.create(token),
diagnosticMessage,
relatedInformation
);
}

public void addDiagnostic(
public Optional<Diagnostic> addDiagnostic(
Range range,
List<DiagnosticRelatedInformation> relatedInformation
) {
addDiagnostic(
return addDiagnostic(
range,
diagnostic.getInfo().getMessage(),
relatedInformation
);
}

public void addDiagnostic(
public Optional<Diagnostic> addDiagnostic(
Range range,
String diagnosticMessage,
@Nullable List<DiagnosticRelatedInformation> relatedInformation
) {
diagnosticList.add(createDiagnostic(

var dgs = createDiagnostic(
nixel2007 marked this conversation as resolved.
Show resolved Hide resolved
diagnostic,
range,
diagnosticMessage,
relatedInformation
));
);

diagnosticList.add(dgs);
nixel2007 marked this conversation as resolved.
Show resolved Hide resolved

return Optional.of(dgs);
nixel2007 marked this conversation as resolved.
Show resolved Hide resolved
}

public void addDiagnostic(ParseTree tree) {
Expand Down
Loading