-
Notifications
You must be signed in to change notification settings - Fork 117
Fix ClassCastException in MagicNumberDiagnostic with soft error handling #3486
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
base: develop
Are you sure you want to change the base?
Changes from 18 commits
337d432
80a646b
50e7a28
240c0fe
503081e
d60200f
ad3410a
1681c41
d21e17d
ea69b6e
7346b69
df49d65
dae5993
0443adb
7bdfb53
dafc798
7a4c86d
d69d92d
7276b9d
6e38274
631c220
291d79b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -25,6 +25,8 @@ | |
| 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.symbol.MethodSymbol; | ||
| import org.springframework.beans.factory.config.BeanDefinition; | ||
| import org.springframework.context.annotation.Role; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import java.util.Map; | ||
|
|
@@ -33,6 +35,7 @@ | |
| * Сапплаер линз, показывающий когнитивную сложность методов. | ||
| */ | ||
| @Component | ||
| @Role(BeanDefinition.ROLE_INFRASTRUCTURE) | ||
|
||
| public class CyclomaticComplexityCodeLensSupplier extends AbstractMethodComplexityCodeLensSupplier { | ||
|
|
||
| public CyclomaticComplexityCodeLensSupplier( | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -32,6 +32,8 @@ | |
| import org.eclipse.lsp4j.Command; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.context.annotation.Lazy; | ||
| import org.springframework.beans.factory.config.BeanDefinition; | ||
| import org.springframework.context.annotation.Role; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import java.nio.file.Paths; | ||
|
|
@@ -43,6 +45,7 @@ | |
| * Поставщик линзы для запуска всех тестов в текущем файле. | ||
| */ | ||
| @Component | ||
| @Role(BeanDefinition.ROLE_INFRASTRUCTURE) | ||
|
||
| @Slf4j | ||
| public class RunAllTestsCodeLensSupplier | ||
| extends AbstractRunTestsCodeLensSupplier<DefaultCodeLensData> { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -36,6 +36,8 @@ | |
| import org.eclipse.lsp4j.Command; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.context.annotation.Lazy; | ||
| import org.springframework.beans.factory.config.BeanDefinition; | ||
| import org.springframework.context.annotation.Role; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import java.beans.ConstructorProperties; | ||
|
|
@@ -50,6 +52,7 @@ | |
| * Поставщик линз для запуска теста по конкретному тестовому методу. | ||
| */ | ||
| @Component | ||
| @Role(BeanDefinition.ROLE_INFRASTRUCTURE) | ||
|
||
| @Slf4j | ||
| public class RunTestCodeLensSupplier | ||
| extends AbstractRunTestsCodeLensSupplier<RunTestCodeLensSupplier.RunTestCodeLensData> { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -39,6 +39,8 @@ | |
| import org.springframework.cache.annotation.CacheEvict; | ||
| import org.springframework.cache.annotation.Cacheable; | ||
| import org.springframework.context.event.EventListener; | ||
| import org.springframework.beans.factory.config.BeanDefinition; | ||
| import org.springframework.context.annotation.Role; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import java.io.IOException; | ||
|
|
@@ -56,6 +58,7 @@ | |
| * Физически выполняет команды по получению идентификаторов тестов на основании конфигурации. | ||
| */ | ||
| @Component | ||
| @Role(BeanDefinition.ROLE_INFRASTRUCTURE) | ||
|
||
| @RequiredArgsConstructor | ||
| @Slf4j | ||
| @CacheConfig(cacheNames = "testIds") | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -23,12 +23,15 @@ | |
|
|
||
| import com.github._1c_syntax.bsl.languageserver.commands.complexity.AbstractToggleComplexityInlayHintsCommandSupplier; | ||
| import com.github._1c_syntax.bsl.languageserver.inlayhints.CognitiveComplexityInlayHintSupplier; | ||
| import org.springframework.beans.factory.config.BeanDefinition; | ||
| import org.springframework.context.annotation.Role; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| /** | ||
| * Поставщик команды переключения подсказок когнитивной сложности. | ||
| */ | ||
| @Component | ||
| @Role(BeanDefinition.ROLE_INFRASTRUCTURE) | ||
|
||
| public class ToggleCognitiveComplexityInlayHintsCommandSupplier | ||
| extends AbstractToggleComplexityInlayHintsCommandSupplier { | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -23,12 +23,15 @@ | |
|
|
||
| import com.github._1c_syntax.bsl.languageserver.commands.complexity.AbstractToggleComplexityInlayHintsCommandSupplier; | ||
| import com.github._1c_syntax.bsl.languageserver.inlayhints.CyclomaticComplexityInlayHintSupplier; | ||
| import org.springframework.beans.factory.config.BeanDefinition; | ||
| import org.springframework.context.annotation.Role; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| /** | ||
| * Поставщик команды переключения подсказок цикломатической сложности. | ||
| */ | ||
| @Component | ||
| @Role(BeanDefinition.ROLE_INFRASTRUCTURE) | ||
|
||
| public class ToggleCyclomaticComplexityInlayHintsCommandSupplier | ||
| extends AbstractToggleComplexityInlayHintsCommandSupplier { | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -28,17 +28,23 @@ | |
| import com.github._1c_syntax.bsl.languageserver.codelenses.CodeLensSupplier; | ||
| import com.github._1c_syntax.bsl.languageserver.commands.CommandArguments; | ||
| import com.github._1c_syntax.bsl.languageserver.commands.CommandSupplier; | ||
| import org.springframework.beans.factory.config.BeanDefinition; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.context.annotation.Lazy; | ||
| import org.springframework.context.annotation.Role; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Collection; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| @Configuration | ||
| @Role(BeanDefinition.ROLE_INFRASTRUCTURE) | ||
| public class ObjectMapperConfiguration { | ||
|
|
||
| @Bean | ||
| @Role(BeanDefinition.ROLE_INFRASTRUCTURE) | ||
| @Lazy | ||
|
||
| public ObjectMapper objectMapper( | ||
| Collection<CodeLensSupplier<? extends CodeLensData>> codeLensResolvers, | ||
| Collection<CommandSupplier<? extends CommandArguments>> commandSuppliers | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -24,19 +24,30 @@ | |
| import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; | ||
| import com.github._1c_syntax.bsl.languageserver.diagnostics.BSLDiagnostic; | ||
| import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; | ||
| import com.github._1c_syntax.bsl.languageserver.utils.Resources; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.eclipse.lsp4j.jsonrpc.messages.Either; | ||
| import org.springframework.beans.factory.config.BeanDefinition; | ||
| import org.springframework.beans.factory.config.BeanPostProcessor; | ||
| import org.springframework.context.annotation.Lazy; | ||
| import org.springframework.context.annotation.Role; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import java.util.Map; | ||
|
|
||
| @RequiredArgsConstructor | ||
| @Component | ||
| @Role(BeanDefinition.ROLE_INFRASTRUCTURE) | ||
|
||
| @Slf4j | ||
| public class DiagnosticBeanPostProcessor implements BeanPostProcessor { | ||
|
|
||
| private final LanguageServerConfiguration configuration; | ||
| private final Map<Class<? extends BSLDiagnostic>, DiagnosticInfo> diagnosticInfos; | ||
| @Lazy | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. а вот это точно лишнее
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
| private final Resources resources; | ||
| @Lazy | ||
|
||
| private final DiagnosticParameterValidator diagnosticParameterValidator; | ||
|
|
||
| @Override | ||
| public Object postProcessBeforeInitialization(Object bean, String beanName) { | ||
|
|
@@ -65,7 +76,17 @@ public Object postProcessAfterInitialization(Object bean, String beanName) { | |
| configuration.getDiagnosticsOptions().getParameters().get(diagnostic.getInfo().getCode().getStringValue()); | ||
|
|
||
| if (diagnosticConfiguration != null && diagnosticConfiguration.isRight()) { | ||
| diagnostic.configure(diagnosticConfiguration.getRight()); | ||
| try { | ||
| // Validate configuration against JSON schema if available | ||
| var diagnosticCode = diagnostic.getInfo().getCode().getStringValue(); | ||
| diagnosticParameterValidator.validateDiagnosticConfiguration(diagnosticCode, diagnosticConfiguration.getRight()); | ||
|
|
||
| diagnostic.configure(diagnosticConfiguration.getRight()); | ||
nixel2007 marked this conversation as resolved.
Show resolved
Hide resolved
nixel2007 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } catch (Exception e) { | ||
| var errorMessage = resources.getResourceString(getClass(), "diagnosticConfigurationError", | ||
| diagnostic.getInfo().getCode().getStringValue(), e.getMessage()); | ||
| LOGGER.warn(errorMessage, e); | ||
| } | ||
| } | ||
|
|
||
| return diagnostic; | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,159 @@ | ||
| /* | ||
| * This file is a part of BSL Language Server. | ||
| * | ||
| * Copyright (c) 2018-2025 | ||
| * 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.infrastructure; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import com.github._1c_syntax.bsl.languageserver.configuration.events.LanguageServerConfigurationChangedEvent; | ||
| import com.github._1c_syntax.bsl.languageserver.utils.Resources; | ||
| import com.networknt.schema.JsonSchema; | ||
| import com.networknt.schema.JsonSchemaFactory; | ||
| import com.networknt.schema.SpecVersion; | ||
| import com.networknt.schema.ValidationMessage; | ||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.beans.factory.config.BeanDefinition; | ||
| import org.springframework.cache.annotation.CacheConfig; | ||
| import org.springframework.cache.annotation.CacheEvict; | ||
| import org.springframework.cache.annotation.Cacheable; | ||
| import org.springframework.context.annotation.Lazy; | ||
| import org.springframework.context.annotation.Role; | ||
| import org.springframework.context.event.EventListener; | ||
| import org.springframework.core.io.ClassPathResource; | ||
| import org.springframework.lang.Nullable; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import java.io.IOException; | ||
| import java.util.Map; | ||
| import java.util.Set; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
|
|
||
| /** | ||
| * Валидатор параметров диагностик с кешированием результатов проверки. | ||
| * <p> | ||
| * Выполняет валидацию конфигурации диагностик против JSON-схемы для обеспечения | ||
| * корректности параметров. Результаты валидации кешируются по классу диагностики | ||
| * и конфигурации для повышения производительности при работе с prototype-бинами. | ||
| * <p> | ||
| * Кеш автоматически сбрасывается при получении события {@link LanguageServerConfigurationChangedEvent}. | ||
| * Ошибки валидации логируются как предупреждения, но не препятствуют созданию диагностик. | ||
| * | ||
| * @see LanguageServerConfigurationChangedEvent | ||
| * @see DiagnosticBeanPostProcessor | ||
| */ | ||
| @RequiredArgsConstructor | ||
| @Component | ||
| @Role(BeanDefinition.ROLE_INFRASTRUCTURE) | ||
| @Slf4j | ||
| @CacheConfig(cacheNames = "diagnosticSchemaValidation") | ||
| public class DiagnosticParameterValidator { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. нужен javadoc на класс
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added comprehensive Javadoc documentation to the DiagnosticParameterValidator class explaining its purpose, caching functionality, and key features. Commit: 7bdfb53 |
||
|
|
||
| private final Resources resources; | ||
| @Lazy | ||
| private final ObjectMapper objectMapper; | ||
|
|
||
| @Getter(lazy = true) | ||
| @Nullable | ||
| private final JsonSchema parametersSchema = loadParametersSchema(); | ||
| private final Map<String, JsonSchema> diagnosticSchemas = new ConcurrentHashMap<>(); | ||
|
|
||
| /** | ||
| * Обработчик события {@link LanguageServerConfigurationChangedEvent}. | ||
| * <p> | ||
| * Сбрасывает кеш валидации схем при изменении конфигурации. | ||
| * | ||
| * @param event Событие | ||
| */ | ||
| @EventListener | ||
| @CacheEvict(allEntries = true) | ||
| public void handleLanguageServerConfigurationChange(LanguageServerConfigurationChangedEvent event) { | ||
| // No-op. Служит для сброса кеша при изменении конфигурации | ||
| } | ||
|
|
||
| /** | ||
| * Cached validation of diagnostic configuration against JSON schema. | ||
| * Results are cached per diagnostic class and configuration to improve performance for prototype beans. | ||
| * | ||
| * @param diagnosticCode Diagnostic code | ||
| * @param configuration Configuration map to validate | ||
| */ | ||
| @Cacheable | ||
| public void validateDiagnosticConfiguration(String diagnosticCode, Map<String, Object> configuration) { | ||
| try { | ||
| var schema = getDiagnosticSchema(diagnosticCode); | ||
| if (schema != null) { | ||
| var configNode = objectMapper.valueToTree(configuration); | ||
| Set<ValidationMessage> errors = schema.validate(configNode); | ||
|
|
||
| if (!errors.isEmpty()) { | ||
| var errorMessages = errors.stream() | ||
| .map(ValidationMessage::getMessage) | ||
| .reduce((msg1, msg2) -> msg1 + "; " + msg2) | ||
| .orElse("Unknown validation error"); | ||
|
|
||
| var localizedMessage = resources.getResourceString(DiagnosticBeanPostProcessor.class, "diagnosticSchemaValidationError", | ||
| diagnosticCode, errorMessages); | ||
| LOGGER.warn(localizedMessage); | ||
| } | ||
| } | ||
| } catch (Exception e) { | ||
| // Schema validation failed, but don't prevent diagnostic configuration | ||
| LOGGER.debug("Schema validation failed for diagnostic '{}': {}", diagnosticCode, e.getMessage()); | ||
| } | ||
| } | ||
|
|
||
| private JsonSchema getDiagnosticSchema(String diagnosticCode) { | ||
| return diagnosticSchemas.computeIfAbsent(diagnosticCode, this::loadDiagnosticSchema); | ||
| } | ||
|
|
||
| private JsonSchema loadDiagnosticSchema(String diagnosticCode) { | ||
| try { | ||
| var schema = getParametersSchema(); | ||
| if (schema != null) { | ||
| // Extract the specific diagnostic schema from the main schema | ||
| var schemaNode = schema.getSchemaNode(); | ||
| var definitionsNode = schemaNode.get("definitions"); | ||
| if (definitionsNode != null && definitionsNode.has(diagnosticCode)) { | ||
| var diagnosticSchemaNode = definitionsNode.get(diagnosticCode); | ||
| var factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V7); | ||
| return factory.getSchema(diagnosticSchemaNode); | ||
| } | ||
| } | ||
| } catch (Exception e) { | ||
| LOGGER.debug("Failed to load schema for diagnostic '{}': {}", diagnosticCode, e.getMessage()); | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| private JsonSchema loadParametersSchema() { | ||
| try { | ||
| var schemaResource = new ClassPathResource("com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json"); | ||
| if (schemaResource.exists()) { | ||
| var factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V7); | ||
| return factory.getSchema(schemaResource.getInputStream()); | ||
| } | ||
| } catch (IOException e) { | ||
| LOGGER.warn("Failed to load parameters schema: {}", e.getMessage()); | ||
| } | ||
| return null; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -25,6 +25,8 @@ | |
| import com.github._1c_syntax.bsl.languageserver.context.computer.ComplexitySecondaryLocation; | ||
| import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.beans.factory.config.BeanDefinition; | ||
| import org.springframework.context.annotation.Role; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import java.util.List; | ||
|
|
@@ -34,6 +36,7 @@ | |
| * Поставщик подсказок о когнитивной сложности методов. | ||
| */ | ||
| @Component | ||
| @Role(BeanDefinition.ROLE_INFRASTRUCTURE) | ||
|
||
| @RequiredArgsConstructor | ||
| public class CognitiveComplexityInlayHintSupplier extends AbstractComplexityInlayHintSupplier { | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -25,6 +25,8 @@ | |
| import com.github._1c_syntax.bsl.languageserver.context.computer.ComplexitySecondaryLocation; | ||
| import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.beans.factory.config.BeanDefinition; | ||
| import org.springframework.context.annotation.Role; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import java.util.List; | ||
|
|
@@ -34,6 +36,7 @@ | |
| * Поставщик подсказок о цикломатической сложности методов. | ||
| */ | ||
| @Component | ||
| @Role(BeanDefinition.ROLE_INFRASTRUCTURE) | ||
|
||
| @RequiredArgsConstructor | ||
| public class CyclomaticComplexityInlayHintSupplier extends AbstractComplexityInlayHintSupplier { | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Это обычный бин, не инфраструктурный.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Removed ROLE_INFRASTRUCTURE annotation from CognitiveComplexityCodeLensSupplier as it's a regular bean. Commit: 7276b9d