### Function Naming Convention: Avoid 'Get' Prefix Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/FunctionNameStartsWithGet.md Demonstrates the incorrect and correct way to name functions according to the FunctionNameStartsWithGet rule. Functions should not start with 'Get' because their purpose is to return a value. ```bsl // Incorrect: Function GetNameByCode() // Correct: Function NameByCode() ``` -------------------------------- ### Example of Pre-checking Access Rights Before Privileged Mode Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/SetPrivilegedMode.md This example demonstrates how to safely use privileged mode by first verifying access rights with `VerifyAccessRights` before calling `SetPrivilegedMode(True)`. ```bsl Procedure ChangeData(...) Export VerifyAccessRights(...); // If the user has insufficient rights, an exception will be thrown SetPrivilegedMode(True); // Disable permission check // Change data in privileged mode ... EndProcedure ``` -------------------------------- ### Correct Spacing Example Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/MissingSpace.md Shows the corrected version of the previous example with proper spacing. ```bsl Procedure Sum(Param1, Param2) If Param1 = Param2 Then Sum = Price * Quantity; EndIf; EndProcedure ``` -------------------------------- ### Disable Safe Mode Examples Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/DisableSafeMode.md Examples demonstrating calls to `SetSafeMode` and `SetDisableSafeMode`. Calls with `False` for `SetSafeMode` and `True` for `SetDisableSafeMode` are flagged as errors, while the reverse are not. ```bsl SetSafeMode (False); // is error Value = False; SetSafeMode(Value); // is error SetSafeMode (True); // no error SetDisableSafeMode(True); // is error Value = True; SetDisableSafeMode(Value); // is error SetDisableSafeMode(False); // no error ``` -------------------------------- ### Example of Correct Data Change Procedure Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/SetPrivilegedMode.md This example shows a correct procedure for changing data without using privileged mode, relying on standard access rights checks. ```bsl Procedure ChangeData(...) Export // Changing data // (at the same time, if the user does not have enough rights to perform an operation on the data, an exception will be raised) ... EndProcedure ``` -------------------------------- ### Start BSL Language Server in Websocket Mode Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/index.md Initiate the BSL Language Server to communicate via websocket. This example specifies a custom port. ```sh java -jar bsl-language-server.jar --websocket --server.port=8080 ``` -------------------------------- ### Correct Region Structure Example Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/CodeOutOfRegion.md This example demonstrates a correctly structured module using nested regions according to standard naming conventions. Ensure your code is organized within these or similar valid regions. ```bsl #Region Private #Region Print // Methods code #EndRegion #Region Other // Methods code #EndRegion #EndRegion ``` -------------------------------- ### Correct Global Module Naming Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/CommonModuleNameGlobalClient.md This example demonstrates the correct naming convention for a global module, using only the 'Global' postfix. ```plaintext InfobaseUpdateGlobal ``` -------------------------------- ### Correct Method Call with All Parameters Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/MissedRequiredParameter.md This example shows a correct call to ChangeFormFieldColor where all required parameters are explicitly provided. ```bsl ChangeFormFieldColor(ThisObject, "Result", Color); // all required parameters are specified ``` -------------------------------- ### Run BSL Language Server Analysis Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/index.md Execute the BSL Language Server in analyzer mode to get diagnostic information. This example specifies the source directory and a JSON reporter. ```sh java -jar bsl-language-server.jar --analyze --srcDir ./src/cf --reporter json ``` -------------------------------- ### Run Gradle Tests Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/FastStart.md Execute the gradlew test command to verify your project setup and dependencies are correct. ```bash gradlew test ``` -------------------------------- ### Example of Incorrect Privileged Mode Usage Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/SetPrivilegedMode.md This example illustrates a potentially dangerous pattern where `SetPrivilegedMode(True)` is called before changing data, disabling permission checks. ```bsl Procedure ChangeData(...) Export SetPrivilegedMode(True); // Disable permission check // Change data in privileged mode ... EndProcedure ``` -------------------------------- ### Procedure Definition Example Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/MissedRequiredParameter.md This snippet shows the signature of a procedure with three parameters: Form, FiledName, and Color. ```bsl Procedure ChangeFormFieldColor(Form, FiledName, Color) ``` -------------------------------- ### Run BSL Language Server Formatting Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/index.md Example command to format BSL code in a specified directory using the bsl-language-server. Ensure the bsl-language-server.jar is in your current directory or provide its full path. ```sh java -jar bsl-language-server.jar --format --src ./src/cf ``` -------------------------------- ### Incorrect Metadata Naming Examples Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/SameMetadataObjectAndChildNames.md These examples demonstrate naming conventions that can lead to errors due to conflicts between parent metadata objects and their child elements. ```plaintext Catalog.Contractors.TabularSection.Contractors InformationRegister.SubordinateDocuments.Dimension.SubordinateDocuments Document.Container.TabularSection.Container. Attribute.Container ``` -------------------------------- ### Bad Method Example with Multiple Returns Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/TooManyReturns.md This example demonstrates a BSL function with multiple return statements, which the TooManyReturns diagnostic aims to identify. Such patterns can make code harder to understand and maintain. ```bsl Function Example(Condition) If Condition = 1 Then Return "Check passed"; ElsIf Condition = 2 Then ExecuteSomething(); Return "Check not passed"; ElsIf Condition > 7 Then Если Validate(Contidtion) Then Return "Check passed"; Else Return "Check not passed"; EndIf; EndIf; Return ""; EndFunction ``` -------------------------------- ### Correct Function Declaration with Grouped Parameters Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/NumberOfParams.md This example demonstrates grouping related parameters into a Structure to improve function declaration clarity and adhere to best practices. ```bsl // Create item in catalog "Goods" Procedure CreateNewGoods(Values, Check = True) EndProcedure ``` -------------------------------- ### Internet Resource Access Diagnostics Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/InternetAccess.md These code examples demonstrate the use of HTTPConnection and FTPConnection which may trigger diagnostics related to internet resource access and potential data transfer issues. ```bsl HTTPConnection = New HTTPConnection("zabbix.localhost", 80); // error FTPConnection = New FTPConnection(Server, Port, User, Pwd); // error ``` -------------------------------- ### NULL Comparison Examples in Joins Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/FieldsFromJoinsWithoutIsNull.md Demonstrates various methods of comparing values from a left-joined table, highlighting correct and incorrect ways to handle NULLs. Use IS NULL or ISNULL() for proper NULL checks. ```sdbl SELECT CASE WHEN LeftTable.Fld2 = 0 THEN "Equals 0 - does not work" WHEN LeftTable.Fld2 <> 0 THEN "NOT Equals 0 - does not work" WHEN LeftTable.Fld2 = NULL THEN "Equals NULL - does not work" WHEN LeftTable.Fld2 IS NULL THEN "IS NULL - it works" WHEN ISNULL(LeftTable.Fld2, 0) = 0 THEN "ISNULL() - and this works too" ELSE "else" END ИЗ First AS First LEFT JOIN LeftTable AS LeftTable ON FALSE ``` -------------------------------- ### Correct Variable Declarations with Descriptions Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/MissingVariablesDescription.md These examples demonstrate how to correctly declare variables with descriptive comments, satisfying the 'MissingVariablesDescription' diagnostic. ```bsl Var Context; // Detailed description that explains the purpose of the variable ``` ```bsl // Detailed description that explains the purpose of the variable Var Context; ``` -------------------------------- ### Implementing BSLDiagnostic Interface Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticStructure.md A basic example of a class implementing the BSLDiagnostic interface. ```java public class TemplateDiagnostic implements BSLDiagnostic ``` -------------------------------- ### Sentry Package Configuration Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/features/Monitoring.md Example configuration for including Sentry packages in a project. This is typically used for error tracking and reporting. ```json { "version": "6.2.1", "packages": [ { "name": "maven:io.sentry:sentry", "version": "6.2.1" }, { "name": "maven:io.sentry:sentry-spring-boot-starter", "version": "6.2.1" } ] } ``` -------------------------------- ### Incorrect Spacing Example Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/MissingSpace.md Demonstrates incorrect spacing around operators and punctuation in BSL code. ```bsl Procedure Sum(Param1,Param2) If Param1=Param2 Then Sum=Price*Quantity; EndIf; EndProcedure ``` -------------------------------- ### Corrected WriteLogEvent Calls with Exception Handling Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/UsageWriteLogEvent.md Examples demonstrating the correct way to use WriteLogEvent, especially within exception handling blocks, ensuring all necessary parameters are provided. ```bsl Try ServerCode(); Except ErrorText = DetailErrorDescription(ErrorInfo()); WriteLogEvent(NStr("en = 'Performing an operation'"), EventLogLevel.Error, , , ErrorText); EndTry; Try ServerCode(); Except ErrorText = DetailErrorDescription(ErrorInfo()); WriteLogEvent(NStr("en = 'Performing an operation'"), EventLogLevel.Error, , , ErrorText); Raise; EndTry; ``` -------------------------------- ### Incorrect Global Module Naming Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/CommonModuleNameGlobalClient.md This example shows an incorrect naming convention for a global module, where 'Client' is appended instead of 'Global'. ```plaintext InfobaseUpdateGlobalClient ``` -------------------------------- ### FormDataToValue Method Call Example Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/FormDataToValue.md This snippet demonstrates the usage of the FormDataToValue method. It is generally recommended to use FormAttributeToValue instead. ```bsl Procedure Test() Form=Doc.GetForm("DocumentForm"); FD = Form.FormDataToValue(Object, Type("ValueTable")); EndProcedure ``` -------------------------------- ### Implementing visitModuleVar for AbstractVisitorDiagnostic Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticStructure.md An example of implementing a visitor method for module variables. It checks for multiple compiler directives within the node and adds a diagnostic if found. ```java @Override public ParseTree visitModuleVar(BSLParser.ModuleVarContext ctx) { // Visitor for module variables if(Trees.findAllRuleNodes(ctx, BSLParser.RULE_compilerDirective).size() > 1) { // Finding child nodes diagnosticStorage.addDiagnostic(ctx); // Adding a error to the entire site } return ctx; } ``` -------------------------------- ### Enable Performance Measurement via Command Line Argument Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/Measures.md You can enable performance measurements by passing this parameter as a command-line argument when starting the application. This is useful for temporary activation or specific runs. ```bash java -jar your-app.jar --app.measures.enabled = true ``` -------------------------------- ### Client-Server Parameter Transfer Example Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/TransferringParametersBetweenClientAndServer.md Demonstrates passing parameters to a server procedure both with and without the 'Val' modifier. It shows how parameters modified without 'Val' on the server are reflected on the client, while those with 'Val' retain their original client values. ```bsl &AtServerNoContext Procedure TransferParametersToServer(Param1, Val ParamWithVal, Collection, Val CollectionWithVal) Param1 = "Changed1"; ParamWithVal = "Changed2"; Collection.Insert("Key1", "Changed1"); CollectionWithVal.Insert("Key2", "Changed2"); EndProcedure &AtClient Procedure PassingParameters(Command) Param1 = "Initial1"; ParamWithVal = "Initial2"; Collection = New Structure("Key1", "Source1"); CollectionWithVal = New Structure("Key2", "Source2"); PassingParametersToServer(Param1, ParamWithVal, Collection, CollectionWithVal); Template = "after server %1 = <%2>"; Message(StrTemplate(Template, "Param1", Param1)); Message(StrTemplate(Template, "ParamWithVal", ParamWithVal)); Message(StrTemplate(Template, "Collection.Key1", Collection.Key1)); Message(StrTemplate(Template, "CollectionWithVal.Key2", CollectionWithVal.Key2)); EndProcedure ``` -------------------------------- ### Example Performance Measurement Results Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/Measures.md This log fragment shows typical output from the performance measurement module after the 'analyze' command has finished. It details the time taken for various components and diagnostics. ```log c.g._.b.l.aop.measures.MeasureCollector : diagnostic: NestedStatements - 4139 c.g._.b.l.aop.measures.MeasureCollector : diagnostic: UnreachableCode - 4555 c.g._.b.l.aop.measures.MeasureCollector : computer: DiagnosticIgnoranceComputer - 4704 c.g._.b.l.aop.measures.MeasureCollector : context: diagnosticIgnorance - 4750 c.g._.b.l.aop.measures.MeasureCollector : diagnostic: ParseError - 6383 c.g._.b.l.aop.measures.MeasureCollector : diagnostic: DeprecatedMethodCall - 6828 c.g._.b.l.aop.measures.MeasureCollector : diagnostic: LatinAndCyrillicSymbolInWord - 8164 c.g._.b.l.aop.measures.MeasureCollector : computer: QueryComputer - 8680 c.g._.b.l.aop.measures.MeasureCollector : computer: MethodSymbolComputer - 8829 c.g._.b.l.aop.measures.MeasureCollector : context: queries - 8933 c.g._.b.l.aop.measures.MeasureCollector : context: metrics - 9864 c.g._.b.l.aop.measures.MeasureCollector : diagnostic: UsingHardcodeNetworkAddress - 11995 ``` -------------------------------- ### Correct Use of For Each Loop Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/UseLessForEach.md This example demonstrates the correct usage of a 'For Each' loop where the iterator is properly used to process each element of the collection. ```bsl For Each Iterator From Collection Loop ProcessElement(Iterator); EndLoop; ``` -------------------------------- ### Console Reporter Output Example Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/reporters/console.md This snippet shows the typical output format of the console reporter, including analysis date, file information, and diagnostic details. ```log Analysis date: 2019-01-28T15:32:06.856 [FileInfo(path=C:\src\cf\Catalogs\MyCatalog\Ext\ManagerModule.bsl, diagnostics=[]), FileInfo(path=C:\src\cf\Catalogs\Goods\Ext\ObjectModule.bsl, diagnostics=[Diagnostic [ range = Range [ start = Position [ line = 55 character = 0 ] end = Position [ line = 55 character = 140 ] ] severity = Information code = "LineLengthDiagnostic" source = "bsl-language-server" message = "Line length exceeded" relatedInformation = null ]])] ``` -------------------------------- ### Get help for newDiagnostic task Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticDevWorkFlow.md Displays detailed help information for the newDiagnostic Gradle task, including available parameters. ```bash gradlew -q help --task newDiagnostic ``` -------------------------------- ### Incorrect Method Calls with Missing Parameters Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/MissedRequiredParameter.md These examples demonstrate incorrect calls to ChangeFormFieldColor where required parameters are omitted, leading to 'Undefined' being passed. ```bsl ChangeFormFieldColor(,"Result", StyleColors.ArthursShirtColor); // missing first parameter Form ChangeFormFieldColor(,,); // missing all required parameters ``` -------------------------------- ### SELECT TOP with UNION and WHERE clauses Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/SelectTopWithoutOrderBy.md This example demonstrates a complex query involving UNION ALL and WHERE clauses. The diagnostic flags 'TOP 10' without sorting in the subquery and the second 'UNION ALL' block due to missing sorting. ```bsl SELECT TOP 1 // < - No error, there is a condition Reference.Link OF Directory.Contractors AS Directory WHERE Reference.Ref. IN ( SELECT TOP 10 // < - Error, no sorting Link OF Reference, Contractors) UNION ALL SELECT TOP 10 // < - Error, no sorting (and cannot be) Reference.Link OF Directory.Contractors AS Directory UNION ALL SELECT TOP 1 // < - Always error, even 1 Reference.Link OF Directory.Contractors AS Directory SORT BY Link ``` -------------------------------- ### Empty Region Example Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/EmptyRegion.md This snippet demonstrates an empty region that will trigger the EmptyRegion diagnostic. Ensure regions contain code to avoid this. ```bsl #Region EmptyRegion #EndRegion ``` -------------------------------- ### Correct Structure Initialization using Insert Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/NumberOfValuesInStructureConstructor.md Shows the recommended method for initializing a Structure by creating an empty Structure and then using the Insert method for each property. This improves code clarity and adheres to best practices. ```bsl Parameters = New Structure; Parameters.Insert("UseParam1", True); Parameters.Insert("UseParam2", True); Parameters.Insert("UseParam3", True); Parameters.Insert("UseParam4", True); Parameters.Insert("UseParam5", True); Parameters.Insert("DataAddress", Current.DataAddress); Parameters.Insert("SettingsAddress", ?(Current.DataAddress <> Undefined, Current.DataAddress, EmptyAddress)); Parameters.Insert("UUID ", UUID); Parameters.Insert("Description", Description); ``` -------------------------------- ### GitLab CI Cache Configuration Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/Typo.md Example configuration for caching the BSL LS Typo directory in GitLab CI using the 'cache' section in .gitlab-ci.yml. ```yaml variables: APP_CACHE_FULLPATH: ".bsl-ls-cache" cache: key: "bsl-ls-typo-cache" paths: - .bsl-ls-cache/ policy: pull-push ``` -------------------------------- ### 1C BSL Code Examples for External Application Launch Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/ExternalAppStarting.md This snippet demonstrates various methods for launching external applications and opening files/URLs in 1C BSL. It includes calls to functions like КомандаСистемы, ЗапуститьПриложение, НачатьЗапускПриложения, ПерейтиПоНавигационнойСсылке, ФайловаяСистемаКлиент.ОткрытьНавигационнуюСсылку, ФайловаяСистемаКлиент.ЗапуститьПрограмму, ФайловаяСистема.ЗапуститьПрограмму, ФайловаяСистемаКлиент.ОткрытьПроводник, and ФайловаяСистемаКлиент.ОткрытьФайл. ```bsl Процедура Метод() СтрокаКоманды = ""; ТекущийКаталог = ""; ДождатьсяЗавершения = Истина; ОписаниеОповещения = Неопределено; ПараметрыКоманды = Новый Структура; КомандаСистемы(СтрокаКоманды, ТекущийКаталог); // есть замечание ЗапуститьПриложение(СтрокаКоманды, ТекущийКаталог); // есть замечание ЗапуститьПриложение(СтрокаКоманды, ТекущийКаталог, Истина); // есть замечание НачатьЗапускПриложения(ОписаниеОповещения, СтрокаКоманды, ТекущийКаталог, ДождатьсяЗавершения); // есть замечание ПерейтиПоНавигационнойСсылке(СтрокаКоманды); // есть замечание ФайловаяСистемаКлиент.ОткрытьНавигационнуюСсылку(СтрокаКоманды); // есть замечание ФайловаяСистемаКлиент.ОткрытьНавигационнуюСсылку(СтрокаКоманды, ОписаниеОповещения); // есть замечание ФайловаяСистемаКлиент.ЗапуститьПрограмму("ping 127.0.0.1 -n 5", ПараметрыКоманды); // есть замечание ФайловаяСистемаКлиент.ЗапуститьПрограмму(СтрокаКоманды, ПараметрыКоманды); // есть замечание ФайловаяСистема.ЗапуститьПрограмму(СтрокаКоманды); // есть замечание ФайловаяСистема.ЗапуститьПрограмму(СтрокаКоманды, ПараметрыКоманды); // есть замечание ФайловаяСистемаКлиент.ОткрытьПроводник("C:\\Users"); // есть замечание ФайловаяСистемаКлиент.ОткрытьФайл(СтрокаКоманды); // есть замечание ФайловаяСистемаКлиент.ОткрытьФайл(СтрокаКоманды, ОписаниеОповещения); // есть замечание КонецПроцедуры &НаКлиенте Асинх Процедура Подключить() СтрокаКоманды = ""; ТекущийКаталог = ""; ДождатьсяЗавершения = Истина; Ждать ЗапуститьПриложениеАсинх(СтрокаКоманды, ТекущийКаталог, ДождатьсяЗавершения); // есть замечание КонецПроцедуры &НаКлиенте Процедура ПроверкаЗапуститьСистему(ДополнительныеПараметрыКоманднойСтроки, КодВозврата) ДождатьсяЗавершения = Истина; ЗапуститьСистему(); // есть замечание ЗапуститьСистему(ДополнительныеПараметрыКоманднойСтроки); // есть замечание ЗапуститьСистему(ДополнительныеПараметрыКоманднойСтроки, ДождатьсяЗавершения); // есть замечание ЗапуститьСистему(ДополнительныеПараметрыКоманднойСтроки, ДождатьсяЗавершения, КодВозврата); // есть замечание КонецПроцедуры ``` -------------------------------- ### Implement QuickFixProvider with AbstractSDBLListenerDiagnostic Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticStructure.md Extend `AbstractSDBLListenerDiagnostic` and implement `QuickFixProvider` for SDBL-specific diagnostics using a listener pattern and supporting quick fixes. ```java public class TemplateDiagnostic extends AbstractSDBLListenerDiagnostic implements QuickFixProvider ``` -------------------------------- ### Unacceptable Commented Code Example 1 Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/CommentedCode.md This example shows commented-out code that should be removed after debugging. It includes a commented 'If' block with a message. ```bsl Procedure BeforeDelete(Failure) //If True Then // Message("For debugging"); //EndIf; EndProcedure ``` -------------------------------- ### Implement QuickFixProvider with AbstractSDBLVisitorDiagnostic Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticStructure.md Extend `AbstractSDBLVisitorDiagnostic` and implement `QuickFixProvider` for SDBL-specific diagnostics using a visitor pattern with quick fix capabilities. ```java public class TemplateDiagnostic extends AbstractSDBLVisitorDiagnostic implements QuickFixProvider ``` -------------------------------- ### Refactored Function (Good Example) Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/FunctionReturnsSamePrimitive.md This snippet shows the refactored version of the previous function, where the redundant 'Return True' statements have been removed, assuming the function's return value was not essential. ```bsl Function CheckString(Val RowTable) If ItsGoodString(RowTable) Then ActionGood(); ElsIf ItsNodBadString(RowTable) Then ActionNoBad(); Else ActionElse(); EndIf; EndFunction ``` -------------------------------- ### Unacceptable Commented Code Example 2 Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/CommentedCode.md This example illustrates another form of unacceptable commented code, featuring a developer's note within a conditional block. ```bsl Procedure BeforeDelete(Failure) If True Then // Ivanov: need fix EndIf; EndProcedure ``` -------------------------------- ### Implement QuickFixProvider with AbstractVisitorDiagnostic Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticStructure.md Extend `AbstractVisitorDiagnostic` and implement `QuickFixProvider` for diagnostics utilizing a visitor pattern and supporting quick fixes. ```java public class TemplateDiagnostic extends AbstractVisitorDiagnostic implements QuickFixProvider ``` -------------------------------- ### Display Help for BSL Language Server Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/index.md Run this command to see all available options and commands for the BSL Language Server. ```sh java -jar bsl-language-server.jar --help ``` -------------------------------- ### Diagnostic Metadata Annotation Example Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticStructure.md This snippet shows an example of the @DiagnosticMetadata annotation used to define properties for a diagnostic, including type, severity, time to fix, and compatibility settings. ```java @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, severity = DiagnosticSeverity.MINOR, minutesToFix = 1, activatedByDefault = false, scope = DiagnosticScope.BSL, compatibilityMode = DiagnosticCompatibilityMode.COMPATIBILITY_MODE_8_3_3, tags = { DiagnosticTag.STANDARD }, modules = { ModuleType.CommonModule }, canLocateOnProject = false, extraMinForComplexity = 1, // For each additional note position (`DiagnosticRelatedInformation`) one minute will be added lspSeverity = "Warning" // Explicit LSP severity level (Error, Warning, Information, Hint) ) ``` -------------------------------- ### Basic Cognitive Complexity Increases in BSL Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/CognitiveComplexity.md Demonstrates how common BSL control flow structures and operators increase cognitive complexity by 1 or more. Use these examples to understand the base complexity added by each construct. ```bsl // Loop `For each` For Each Element in Collection Do // +1 EndDo; // Loop `For` For i = StartValue To EndValue Do // +1 EndDo; // Loop `While` While Condition Do // +1 EndDo; // Condition If Condition1 Then // +1 // Alternative condition branch ElseIf Condition2 Then // +1 // default branch Else EndIf; // ternary operator Value = ?(Condition, ValueTrue, ValueFalse); // +1 Try // Exception handling Except // +1 EndTry; // Go to label Goto ~Label; // +1 // Binary logical operations While Condition1 Or Condition2 Do // +2 EndDo; If Condition1 And Condition2 Then // +2 ElseIf Condition2 // +1 Or Condition3 And Condition4 Then // +2 EndIf; Value = ?(Condition1 Or Condition2 Or Not Condition3,// +3 ValueTrue, ValueFalse); Value = First Or Second; // +1 Value = A <> B; // +1 ``` -------------------------------- ### Example Error Event Message Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/features/Monitoring.md This JSON object represents an example of an error event message sent by the BSL Language Server. It includes details about the project, release, platform, error message, and contextual information. ```json { "event_id": "746e2e82f4c1499abcdd935bc4c26644", "project": 5790531, "release": "ae081de9d3c3496ddac1d176259365191966b0cd", "dist": null, "platform": "java", "message": "Internal error: java.lang.RuntimeException: psss", "datetime": "2022-07-14T11:07:57.875000Z", "tags": [ [ "environment", "production" ], [ "level", "error" ], [ "logger", "org.eclipse.lsp4j.jsonrpc.RemoteEndpoint" ], [ "runtime", "AdoptOpenJDK 15.0.2" ], [ "runtime.name", "AdoptOpenJDK" ], [ "release", "ae081de9d3c3496ddac1d176259365191966b0cd" ], [ "user", "id:49516eb9-2a0d-4a15-bd96-978b68d8d0df" ], [ "server.version", "feature-sentry-ae081de-DIRTY" ] ], "_metrics": { "bytes.ingested.event": 3289, "bytes.stored.event": 9875 }, "contexts": { "runtime": { "name": "AdoptOpenJDK", "version": "15.0.2", "type": "runtime" } }, "culprit": "java.util.concurrent.CompletableFuture in encodeThrowable", "environment": "production", "exception": { "values": [ { "type": "RuntimeException", "value": "psss", "module": "java.lang", "stacktrace": { "frames": [ { "function": "run", "module": "java.util.concurrent.ForkJoinWorkerThread", "in_app": false }, { "function": "runWorker", "module": "java.util.concurrent.ForkJoinPool", "in_app": false }, { "function": "scan", "module": "java.util.concurrent.ForkJoinPool", "in_app": false }, { "function": "topLevelExec", "module": "java.util.concurrent.ForkJoinPool$WorkQueue", "in_app": false }, { "function": "doExec", "module": "java.util.concurrent.ForkJoinTask", "in_app": false }, { "function": "exec", "module": "java.util.concurrent.CompletableFuture$AsyncSupply", "in_app": false }, { "function": "run", "module": "java.util.concurrent.CompletableFuture$AsyncSupply", "in_app": false } ] } } ] } } ``` -------------------------------- ### Implement QuickFixProvider with BSLDiagnostic Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticStructure.md Implement the `QuickFixProvider` interface along with `BSLDiagnostic` for diagnostics that support quick fixes. ```java public class TemplateDiagnostic implements BSLDiagnostic, QuickFixProvider ``` -------------------------------- ### Incorrectly Storing a Password Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/UsingHardcodeSecretInformation.md This snippet shows an example of hardcoding a password directly in the code, which is prohibited. ```bsl Password = "12345"; ``` -------------------------------- ### Dereference in Cast Function Result Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/QueryNestedFieldsByDot.md Example of dereferencing fields from the result of a CAST function in a 1C query. ```1c ВЫРАЗИТЬ(ВТ_ПланОтгрузок.ДокументПлан КАК Документ.ЗаказКлиента).Валюта.Наценка ``` -------------------------------- ### Implement QuickFixProvider with AbstractDiagnostic Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticStructure.md Extend `AbstractDiagnostic` and implement `QuickFixProvider` for diagnostics requiring a base abstract implementation and quick fix support. ```java public class TemplateDiagnostic extends AbstractDiagnostic implements QuickFixProvider ``` -------------------------------- ### Configure Diagnostic Settings Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticStructure.md This snippet demonstrates how to retrieve default diagnostic settings, modify a specific parameter ('templateParem'), and then apply these new settings using the `configure` method. It also shows how to fetch and assert the resulting diagnostics. ```java @Test void testConfigure() { // getting default diagnostic settings Map configuration = diagnosticInstance.getInfo().getDefaultDiagnosticConfiguration(); configuration.put("templateParem", "newValue"); // setting "templateParem" to "newValue" diagnosticInstance.configure(configuration); // applying settings List diagnostics = getDiagnostics(); // getting a list of diagnostics assertThat(diagnostics).hasSize(2); // checking the number of detected // special case check assertThat(diagnostics, true) .hasRange(27, 4, 27, 29) .hasRange(40, 4, 40, 29); } ``` -------------------------------- ### Multiple Assignments Example Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/OneStatementPerLine.md Multiple statements of the same type, specifically assignment operators, can be placed on a single line. ```bsl StartIndex = 0; Index = 0; Result = 0; ``` -------------------------------- ### Extending AbstractSDBLVisitorDiagnostic Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticStructure.md Example of a diagnostic class extending AbstractSDBLVisitorDiagnostic for analyzing 1C queries based on AST. ```java public class TemplateDiagnostic extends AbstractSDBLVisitorDiagnostic ``` -------------------------------- ### Crazy Multiline String Initialization Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/CrazyMultilineString.md This snippet demonstrates the 'crazy' method of initializing multiline strings where lines are separated by whitespace, which can be difficult to understand and prone to errors. ```bsl String = "BBB" "CC" "F"; ``` -------------------------------- ### Extending AbstractVisitorDiagnostic Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticStructure.md Example of a diagnostic class extending AbstractVisitorDiagnostic for analyzing 1C code based on AST. ```java public class TemplateDiagnostic extends AbstractVisitorDiagnostic ``` -------------------------------- ### Implement QuickFixProvider with AbstractListenerDiagnostic Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticStructure.md Extend `AbstractListenerDiagnostic` and implement `QuickFixProvider` for diagnostics using a listener pattern and offering quick fixes. ```java public class TemplateDiagnostic extends AbstractListenerDiagnostic implements QuickFixProvider ``` -------------------------------- ### Correct HTTPConnection Initialization with Timeout Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/TimeoutsInExternalResources.md This snippet shows the correct way to initialize an HTTPConnection by specifying a timeout value, preventing potential operational issues. ```bsl HTTPConnection = New HTTPConnection("zabbix.localhost", 80,,,, 1); ``` -------------------------------- ### Base Dereference Through Dot Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/QueryNestedFieldsByDot.md Example of dereferencing nested fields using dot notation in a temporary table or select query. ```1c ЗаказКлиентаТовары.Ссылка.Организация КАК Организация ``` -------------------------------- ### Instantiating COMObject on Unix Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/UsingObjectNotAvailableUnix.md Avoid instantiating COMObject on Linux as it is not supported. Use alternative integration methods. ```bsl Component = New COMObject("System.Text.UTF8Encoding"); ``` -------------------------------- ### Extending AbstractSDBLListenerDiagnostic Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticStructure.md Example of a diagnostic class extending AbstractSDBLListenerDiagnostic for analyzing 1C queries using the listener strategy. ```java public class TemplateDiagnostic extends AbstractSDBLListenerDiagnostic ``` -------------------------------- ### Extending AbstractListenerDiagnostic Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticStructure.md Example of a diagnostic class extending AbstractListenerDiagnostic for implementing the listener strategy for AST node analysis. ```java public class TemplateDiagnostic extends AbstractListenerDiagnostic ``` -------------------------------- ### Create a new diagnostic with Gradle Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticDevWorkFlow.md Generates the necessary files for a new diagnostic using the gradlew command. Replace 'KeyDiagnostic' with your diagnostic's key and provide Russian and English descriptions. ```bash gradlew newDiagnostic --key="KeyDiagnostic" --nameRu="Russian description" --nameEn="English description" ``` -------------------------------- ### Extending AbstractDiagnostic Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticStructure.md Example of a diagnostic class extending the AbstractDiagnostic base class for simple module context checking. ```java public class TemplateDiagnostic extends AbstractDiagnostic ``` -------------------------------- ### Incorrect Variable Declaration Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/MissingVariablesDescription.md This snippet shows an example of a variable declaration without a description, which will trigger the 'MissingVariablesDescription' diagnostic. ```bsl Var Context; ``` -------------------------------- ### Correct: Using a Function for Network Address Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/UsingHardcodeNetworkAddress.md This snippet demonstrates the correct way to handle network addresses by calling a function that retrieves the address. This is a recommended practice for managing network configurations. ```bsl NetworkAddress = MyModuleReUse.ServerNetworkAddress(); ``` -------------------------------- ### Invalid WriteLogEvent Calls Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/UsageWriteLogEvent.md Examples of incorrect usage of the WriteLogEvent method, including missing parameters and improper exception logging. ```bsl WriteLogEvent("Event");// error WriteLogEvent("Event", EventLogLevel.Error);// error WriteLogEvent("Event", EventLogLevel.Error, , );// error WriteLogEvent("Event", , , , DetailErrorDescription(ErrorInfo())); WriteLogEvent("Event", EventLogLevel.Error, , , );// error Try ServerCode(); Except WriteLogEvent("Event", EventLogLevel.Error, , , ErrorDescription()); // error WriteLogEvent("Event", EventLogLevel.Error, , , "Commentary 1"); // error EndTry; ``` -------------------------------- ### Default Cache Configuration Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/Typo.md Shows the default configuration properties for the cache base path and full path. ```properties app.cache.basePath=${user.home} app.cache.fullPath= ``` -------------------------------- ### Correct Transaction Pairing in BSL Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/PairingBrokenTransaction.md Demonstrates the correct way to pair StartTransaction() with CommitTransaction() or RollbackTransaction() within a single procedure. Ensure all transaction operations are contained within the same method. ```bsl Procedure WriteDataToIB() StartTransaction(); Try ... // read or write data DocumentObject.Write() CommitTransaction(); Raise RollbackTransaction(); ... // additional steps to handle the exception EndTry; EndProcedure ``` -------------------------------- ### Correct HTTPConnection Initialization with Variable Timeout Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/TimeoutsInExternalResources.md This snippet illustrates initializing an HTTPConnection with a timeout value stored in a variable, offering flexibility in setting the time limit. ```bsl ConnectiomTimeout = 180; HTTPConnection = New HTTPConnection("zabbix.localhost", 80,,,, ConnectiomTimeout); ``` -------------------------------- ### Implement Parameter Configuration Method Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnostcAddSettings.md Implement the 'configure' method to handle setting parameter values, especially for 'hard' types like regular expression patterns or complex data structures. This method processes a map of configurations. ```java @Override public void configure(Map configuration) { // to set "simple properties" including "commentAsCode" super.configure(configuration); // setting the "hard" property "excludeMethods" String excludeMethodsString = (String) configuration.getOrDefault("excludeMethods", EXCLUDE_METHODS_DEFAULT); this.excludeMethods = new ArrayList<>(Arrays.asList(excludeMethodsString.split(","))); } ``` -------------------------------- ### Classic Multiline String Initialization Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/CrazyMultilineString.md This snippet shows the 'classic' method for initializing multiline strings using explicit string concatenation with '+', which is generally easier to read and maintain. ```bsl String = "BBB" + "CC" + "F"; ``` -------------------------------- ### Test Class Structure Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/DiagnosticStructure.md Example of a basic test class structure extending AbstractDiagnosticTest. This sets up the test environment for a specific diagnostic. ```java package com.github._1c_syntax.bsl.languageserver.diagnostics; import org.eclipse.lsp4j.Diagnostic; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import org.junit.jupiter.api.Test; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; class TemplateDiagnosticTest extends AbstractDiagnosticTest { TemplateDiagnosticTest() { super(TemplateDiagnostic.class); } } ``` -------------------------------- ### Correct Structure Initialization in BSL Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/NestedConstructorsInStructureDeclaration.md Shows the recommended method for initializing a structure with nested structures in BSL. It involves creating a separate structure and inserting properties, then passing it to the constructor. ```bsl Parameters = New Structure; Parameters.Вставить("CharacteristicsUsed", New Structure("Good", "CharacteristicsUsed")); Parameters.Вставить("Type", New Structure("Good", "Type")); Parameters.Вставить("Variant", New Structure("Good", "Variant")); GoodsServer.MakeGoods(Object.Products, Parameters); ``` -------------------------------- ### Example Forbidden Words List Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/BadWords.md A sample regular expression defining a list of forbidden words. This can be used to enforce naming conventions. ```regex "singularity|avada kedavra|Donald" ``` -------------------------------- ### Client-side: Correct use of SessionDate Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/DeprecatedCurrentDate.md Use GeneralPurposeClient.SessionDate() on the client to get the date and time in the user's session time zone. ```bsl OperationDate = GeneralPurposeClient.SessionDate(); ``` -------------------------------- ### Correct StrTemplate Usage with Immediate Digit Formatting Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/IncorrectUseOfStrTemplate.md Illustrates the correct syntax for passing a digit immediately after a template value placeholder using parentheses, like %(1)2, to achieve specific formatting. ```1c StrTemplate("Name %(1)2"), Name); // if pass the value "MyString", then the result will be "MyString2" ``` -------------------------------- ### GitHub Actions Cache Configuration Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/Typo.md Example configuration for caching the BSL LS Typo directory in GitHub Actions using the 'actions/cache' action. ```yaml - name: Cache BSL LS Typo uses: actions/cache@v3 with: path: .bsl-ls-cache key: ${{ runner.os }}-bsl-typo-${{ hashFiles('**/*.bsl') }} restore-keys: | ${{ runner.os }}-bsl-typo- ``` -------------------------------- ### Allowed LIKE Operator Usage Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/IncorrectUseLikeInQuery.md Demonstrates the correct way to use the LIKE operator with a constant string literal. ```bsl Field LIKE "123%" ``` -------------------------------- ### Incorrect Query Text Formatting Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/QueryParseError.md This snippet shows an example of query text that violates the formatting rules and would trigger the QueryParseError diagnostic. ```bsl Text = "SELECT | Goods.Name AS Name , | Goods. " + FieldNameCode + " AS Code |From | Catalog.Goods КАК Goods"; ``` -------------------------------- ### BSL Function with Optional Parameter Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/OrderOfParams.md Example of a BSL function definition where the optional 'Date' parameter correctly follows the mandatory 'Currency' parameter. ```bsl Function CurrencyRateOnDate(Currency, Date = Notdefined) Export ``` -------------------------------- ### Run Type Service Benchmark Test Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/contributing/TypeSystem.md Execute the TypeServiceBenchmarkTest using Gradle. This command is used to capture performance metrics for the type inferencer on a specific machine. ```bash ./gradlew test --tests "*TypeServiceBenchmarkTest" --info ``` -------------------------------- ### Correct Procedure/Function Parameter Formatting Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/IncorrectLineBreak.md Illustrates the correct way to format parameters in procedure or function calls, including the placement of the closing parenthesis and operator separator. ```bsl Names = New ValueList; Names.Add(Name, Synonym); ``` -------------------------------- ### Incorrect Double Negative Condition Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/DoubleNegatives.md This snippet shows an example of a double negative condition that makes the code harder to understand. It is recommended to refactor such conditions. ```bsl If Not ValueTable.Find(SearchValue, "Column") <> Undefined Then // Do the action EndIf; ``` -------------------------------- ### Instantiating Mail Object on Unix Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/UsingObjectNotAvailableUnix.md Avoid instantiating the Mail object directly on Linux. Consider using StartApplication() or checking platform type before instantiation. ```bsl Mail = New Mail; ``` -------------------------------- ### Correct Handler Method Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/WrongWebServiceHandler.md This snippet demonstrates a correctly implemented web service handler method. It includes a method body and the correct set of parameters, ensuring proper operation handling. ```bsl Function FillCatalogs(MobileDeviceID, MessageExchange) Return MobileOrders.FillCatalogs(MobileDeviceID, MessageExchange); EndFunction ``` -------------------------------- ### Incorrect: Hardcoded IP Address Source: https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/en/diagnostics/UsingHardcodeNetworkAddress.md This snippet shows an example of a hardcoded IP address that will trigger the diagnostic. Avoid storing network addresses directly in the code. ```bsl NetworkAddress = "192.168.0.1"; ```