diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 00000000000..d06d6c669ee --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,41 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/java +{ + "name": "Java", + // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile + "image": "mcr.microsoft.com/devcontainers/java:1-17-bookworm", + + "features": { + "ghcr.io/devcontainers/features/java:1": { + "version": "none", + "installMaven": "false", + "installGradle": "true" + }, + "ghcr.io/devcontainers/features/python:1": {} + }, + "customizations": { + "vscode": { + "extensions": [ + "vscjava.vscode-gradle", + "GitHub.vscode-github-actions", + "astrizhachuk.1c-extension-pack", + "zhuangtongfa.Material-theme", + "GitHub.copilot", + "GitHub.copilot-chat", + "github.vscode-github-actions" + ] + } + } + + // Use 'forwardPorts' to make a list of ports inside the container available locally. + // "forwardPorts": [], + + // Use 'postCreateCommand' to run commands after the container is created. + // "postCreateCommand": "java -version", + + // Configure tool-specific properties. + // "customizations": {}, + + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + // "remoteUser": "root" +} diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 00000000000..d766802d8f5 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,5 @@ +# happy new year 2025 +e84a3f81035a6e76c042b406d5ad6e986a91d8e1 +# happy new year 2024 +654c64ee05d943de550defda931b10ad6067171d + diff --git a/.github/ISSUE_TEMPLATE/NewDiagnostic.md b/.github/ISSUE_TEMPLATE/NewDiagnostic.md index fdad78fe1e1..88df6f476ab 100644 --- a/.github/ISSUE_TEMPLATE/NewDiagnostic.md +++ b/.github/ISSUE_TEMPLATE/NewDiagnostic.md @@ -50,7 +50,7 @@ assignees: '' * [ ] `LOCALIZE` - "Проблемы локализации" ### Время на исправление (минут) - + ## Дополнительная информация diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 7687c759aff..cd99e05a5b4 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -9,7 +9,15 @@ updates: directory: "/" # Location of package manifests schedule: interval: "daily" + groups: + freefair: + patterns: + - "io.freefair.*" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" + - package-ecosystem: "devcontainers" + directory: "/" + schedule: + interval: weekly \ No newline at end of file diff --git a/.github/scripts/benchmark.py b/.github/scripts/benchmark.py index 3bb69bac0de..04e561792c7 100644 --- a/.github/scripts/benchmark.py +++ b/.github/scripts/benchmark.py @@ -20,6 +20,8 @@ def some_func(arg): cmdArgs.append('-a') cmdArgs.append('-s') cmdArgs.append('ssl') + cmdArgs.append('-r') + cmdArgs.append('sarif') cmdArgs.append('-c') cmdArgs.append(pathToConfig) cmd = ' '.join(cmdArgs) diff --git a/.github/scripts/build-jpackage.py b/.github/scripts/build-jpackage.py new file mode 100644 index 00000000000..c1a63d8c04c --- /dev/null +++ b/.github/scripts/build-jpackage.py @@ -0,0 +1,73 @@ +import ntpath +import os +import platform +import re +import shutil +import sys + + +def build_image(base_dir, image_prefix, executable_file): + path_to_jar = get_bsl_ls_jar(base_dir) + if path_to_jar is None: + exit() + + cmd_args = [ + 'jpackage', + '--name', 'bsl-language-server', + '--input', 'build/libs', + '--main-jar', path_to_jar] + + if is_windows(): + cmd_args.append('--win-console') + + cmd_args.append('--type') + cmd_args.append('app-image') + cmd_args.append('--java-options') + cmd_args.append('-Xmx3g') + + cmd = ' '.join(cmd_args) + os.system(cmd) + + shutil.make_archive( + "bsl-language-server_" + image_prefix, + 'zip', + './', + executable_file) + + +def is_windows(): + return platform.system() == 'Windows' + + +def get_base_dir(): + if is_windows(): + base_dir = os.getcwd() + "\\build\\libs" + else: + base_dir = os.getcwd() + "/build/libs" + return base_dir + + +def get_bsl_ls_jar(dir_name): + pattern = r"bsl.+\.jar" + names = os.listdir(dir_name) + for name in names: + fullname = os.path.join(dir_name, name) + if os.path.isfile(fullname) and re.search(pattern, fullname) and fullname.find('exec.jar') != -1: + return ntpath.basename(fullname) + + return None + + +if __name__ == "__main__": + # directory with build project + arg_base_dir = get_base_dir() + + # image prefix: `win`, `nic` or `mac` + arg_image_prefix = sys.argv[1] + + # executable file: `bsl-language-server` or `bsl-language-server.app` + arg_executable_file = sys.argv[2] + + build_image(base_dir=get_base_dir(), + image_prefix=sys.argv[1], + executable_file=sys.argv[2]) diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index a151fc26bd9..5d73464866b 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -29,16 +29,17 @@ jobs: uses: actions/checkout@v3 - name: Setup JDK - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: 17 distribution: 'temurin' + cache: gradle - name: Build with Gradle run: ./gradlew bootJar - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: "3.7" @@ -51,6 +52,12 @@ jobs: - name: Analyze ssl run: pytest .github/scripts/benchmark.py --benchmark-min-rounds=3 --benchmark-timer=time.time --benchmark-json=output.json --benchmark-verbose + - name: Archive results in SARIF + uses: actions/upload-artifact@v4 + with: + name: "SARIF report" + path: bsl-ls.sarif + - name: Generation badge benchmark if: github.event_name == 'push' run: python .github/scripts/gen-bandge.py diff --git a/.github/workflows/check-package.yml b/.github/workflows/check-package.yml new file mode 100644 index 00000000000..ffe39ce37bd --- /dev/null +++ b/.github/workflows/check-package.yml @@ -0,0 +1,51 @@ +name: Check making image + +on: + push: + branches: + - develop + - feature/check-package + + +jobs: + build: + strategy: + fail-fast: true + matrix: + os: [windows-latest, ubuntu-latest, macOS-latest] + include: + - os: windows-latest + displayName: Windows + prefix: win + app-image: bsl-language-server + - os: ubuntu-latest + displayName: Linux + prefix: nix + app-image: bsl-language-server + - os: macOS-latest + displayName: MacOS + prefix: mac + app-image: bsl-language-server.app + runs-on: ${{ matrix.os }} + name: (${{ matrix.displayName }}) create image app version + + steps: + - name: Checkout source + uses: actions/checkout@v4 + + - name: Set up JDK + uses: actions/setup-java@v4 + with: + java-version: 23 + distribution: 'temurin' + cache: gradle + + - name: Build bootJar with Gradle + run: ./gradlew check build + + - name: Build jpackage application image + run: python .github/scripts/build-jpackage.py ${{ matrix.prefix }} ${{ matrix.app-image }} + + + + diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 4a201535b01..eede133d6de 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -23,21 +23,22 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: # We must fetch at least the immediate parents so that if this is # a pull request then we can checkout the head. fetch-depth: 2 - - name: Set up JDK 11 - uses: actions/setup-java@v3 + - name: Set up JDK 17 + uses: actions/setup-java@v4 with: java-version: 17 distribution: 'temurin' + cache: gradle # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@v2 + uses: github/codeql-action/init@v3 # Override language selection by uncommenting this and choosing your languages with: languages: java @@ -52,4 +53,4 @@ jobs: - run: ./gradlew jar - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 + uses: github/codeql-action/analyze@v3 diff --git a/.github/workflows/codesee-arch-diagram.yml b/.github/workflows/codesee-arch-diagram.yml new file mode 100644 index 00000000000..9a3aa1cdf7d --- /dev/null +++ b/.github/workflows/codesee-arch-diagram.yml @@ -0,0 +1,22 @@ +# This workflow was added by CodeSee. Learn more at https://codesee.io/ +# This is v2.0 of this workflow file +on: + push: + branches: + - develop + pull_request_target: + types: [opened, synchronize, reopened] + +name: CodeSee + +permissions: read-all + +jobs: + codesee: + runs-on: ubuntu-latest + continue-on-error: true + name: Analyze the repo with CodeSee + steps: + - uses: Codesee-io/codesee-action@v2 + with: + codesee-token: ${{ secrets.CODESEE_ARCH_DIAG_API_TOKEN }} diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index dfd41afb90b..80a4ae6d698 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -17,21 +17,22 @@ jobs: build-deploy: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Setup JDK - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: 17 distribution: 'temurin' + cache: gradle - name: Build javadoc run: ./gradlew --no-daemon javadoc - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: - python-version: '3.6' + python-version: '3.12' architecture: 'x64' - name: Install dependencies @@ -145,7 +146,7 @@ jobs: cp -R temp/site/. public/dev/en - name: Deploy - uses: peaceiris/actions-gh-pages@v3.9.0 + uses: peaceiris/actions-gh-pages@v4.0.0 with: deploy_key: ${{ secrets.ACTIONS_DEPLOY_KEY }} publish_branch: gh-pages diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index d791c53625b..c3900a79e7f 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -18,20 +18,21 @@ jobs: strategy: fail-fast: false matrix: - java_version: ['11', '17'] + java_version: ['17', '21', '23'] os: [ubuntu-latest, windows-latest, macOS-latest] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up JDK ${{ matrix.java_version }} - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: ${{ matrix.java_version }} distribution: 'temurin' + cache: gradle - name: Build with Gradle run: ./gradlew check --stacktrace - name: Archive test results if: failure() - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: junit_report_${{ matrix.os }}_${{ matrix.java_version }} path: build/reports/tests/test diff --git a/.github/workflows/javadoc.yml b/.github/workflows/javadoc.yml index 6c28e6b491d..391052f8d68 100644 --- a/.github/workflows/javadoc.yml +++ b/.github/workflows/javadoc.yml @@ -17,11 +17,12 @@ jobs: needs: gatekeeper runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up JDK - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: 17 distribution: 'temurin' + cache: gradle - name: Check javadoc build run: ./gradlew javadoc --stacktrace diff --git a/.github/workflows/pre-qa.yml b/.github/workflows/pre-qa.yml index bc9564dc609..5c9485192e5 100644 --- a/.github/workflows/pre-qa.yml +++ b/.github/workflows/pre-qa.yml @@ -21,7 +21,7 @@ jobs: run: echo ${{ github.event.number }} > PR_NUMBER.txt - name: Archive PR number if: github.event_name == 'pull_request' - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: PR_NUMBER path: PR_NUMBER.txt diff --git a/.github/workflows/publish-to-sonatype.yml b/.github/workflows/publish-to-sonatype.yml index 8db838b6f4e..8dd8c892fa0 100644 --- a/.github/workflows/publish-to-sonatype.yml +++ b/.github/workflows/publish-to-sonatype.yml @@ -12,12 +12,13 @@ jobs: publish: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up JDK - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: 17 distribution: 'temurin' + cache: gradle - name: Publish to Sonatype run: ./gradlew publishMavenPublicationToSonatypeRepository -PsimplifyVersion env: diff --git a/.github/workflows/qa.yml b/.github/workflows/qa.yml index 43d2422400e..7c8703fc5af 100644 --- a/.github/workflows/qa.yml +++ b/.github/workflows/qa.yml @@ -13,7 +13,7 @@ jobs: steps: - name: Download PR number artifact if: github.event.workflow_run.event == 'pull_request' - uses: dawidd6/action-download-artifact@v2 + uses: dawidd6/action-download-artifact@v9 with: workflow: ${{ github.event.workflow_run.name }} run_id: ${{ github.event.workflow_run.id }} @@ -34,7 +34,7 @@ jobs: full_name: ${{ github.event.repository.full_name }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: repository: ${{ github.event.workflow_run.head_repository.full_name }} ref: ${{ github.event.workflow_run.head_branch }} @@ -47,20 +47,21 @@ jobs: git checkout -B ${{ fromJson(steps.get_pr_data.outputs.data).base.ref }} upstream/${{ fromJson(steps.get_pr_data.outputs.data).base.ref }} git checkout ${{ github.event.workflow_run.head_branch }} git clean -ffdx && git reset --hard HEAD - - name: Set up JDK 11 - uses: actions/setup-java@v3 + - name: Set up JDK 17 + uses: actions/setup-java@v4 with: - java-version: 11 + java-version: 17 distribution: 'temurin' + cache: gradle - name: SonarCloud Scan on PR if: github.event.workflow_run.event == 'pull_request' - run: ./gradlew check sonarqube -Dsonar.scm.revision=${{ github.event.workflow_run.head_sha }} -Dsonar.pullrequest.key=${{ fromJson(steps.get_pr_data.outputs.data).number }} -Dsonar.pullrequest.branch=${{ fromJson(steps.get_pr_data.outputs.data).head.ref }} -Dsonar.pullrequest.base=${{ fromJson(steps.get_pr_data.outputs.data).base.ref }} + run: ./gradlew check sonar -Dsonar.scm.revision=${{ github.event.workflow_run.head_sha }} -Dsonar.pullrequest.key=${{ fromJson(steps.get_pr_data.outputs.data).number }} -Dsonar.pullrequest.branch=${{ fromJson(steps.get_pr_data.outputs.data).head.ref }} -Dsonar.pullrequest.base=${{ fromJson(steps.get_pr_data.outputs.data).base.ref }} env: SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: SonarCloud Scan on push if: github.event.workflow_run.event == 'push' && github.event.workflow_run.head_repository.full_name == github.event.repository.full_name - run: ./gradlew check sonarqube -Dsonar.scm.revision=${{ github.event.workflow_run.head_sha }} -Dsonar.branch.name=${{ github.event.workflow_run.head_branch }} + run: ./gradlew check sonar -Dsonar.scm.revision=${{ github.event.workflow_run.head_sha }} -Dsonar.branch.name=${{ github.event.workflow_run.head_branch }} env: SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/qodana.yml b/.github/workflows/qodana.yml deleted file mode 100644 index 52134cffbb0..00000000000 --- a/.github/workflows/qodana.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: Qodana -on: - workflow_dispatch: - pull_request: - push: - branches: - - develop - - feature/qodana - -jobs: - gatekeeper: - runs-on: ubuntu-latest - if: github.event_name == 'pull_request' && startsWith(github.head_ref, 'translations_') == false || github.event_name == 'push' - steps: - - run: echo 'Open the Golden Gate' - - qodana: - needs: gatekeeper - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - name: 'Qodana Scan' - uses: JetBrains/qodana-action@v2022.2.4 - with: - linter: jetbrains/qodana-jvm-community - - uses: github/codeql-action/upload-sarif@v2 - with: - sarif_file: ${{ runner.temp }}/qodana/results/qodana.sarif.json - - name: Deploy to GitHub Pages - if: github.event_name == 'push' - uses: peaceiris/actions-gh-pages@v3.9.0 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - publish_dir: ${{ runner.temp }}/qodana/results/report - destination_dir: ./qodana diff --git a/.github/workflows/rebase.yml b/.github/workflows/rebase.yml index af3f5a54c79..c06a1bcdf2e 100644 --- a/.github/workflows/rebase.yml +++ b/.github/workflows/rebase.yml @@ -9,11 +9,11 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout the latest code - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: token: ${{ secrets.GITHUB_TOKEN }} fetch-depth: 0 # otherwise, you will fail to push refs to dest repo - name: Automatic Rebase - uses: cirrus-actions/rebase@1.7 + uses: cirrus-actions/rebase@1.8 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5eb2030f5d1..6a2192ca624 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -28,83 +28,40 @@ jobs: steps: - name: Checkout source - uses: actions/checkout@v3 + uses: actions/checkout@v4 + - name: Set up JDK - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: - java-version: 17 + java-version: 23 distribution: 'temurin' + cache: gradle + - name: Build bootJar with Gradle run: ./gradlew check bootJar - - name: Build jpackage app-image - run: | - import os - import platform - import re - import ntpath - import shutil - - pattern = r"bsl.+\.jar" - thisPlatform = platform.system(); - isWindows = False - if thisPlatform == 'Windows': - isWindows = True - - if isWindows: - dirName = os.getcwd() + "\\build\\libs" - else: - dirName = os.getcwd() + "/build/libs" - - def start(): - fullname = get_bslls_jar(dirName) - if (fullname == None): - exit - - cmdArgs = ['jpackage'] - cmdArgs.append('--name') - cmdArgs.append('bsl-language-server') - cmdArgs.append('--input') - cmdArgs.append('build/libs') - cmdArgs.append('--main-jar') - cmdArgs.append(fullname) - if isWindows: - cmdArgs.append('--win-console') - cmdArgs.append('--type') - cmdArgs.append('app-image') - cmdArgs.append('--java-options') - cmdArgs.append('-Xmx2g') - cmd = ' '.join(cmdArgs) - os.system(cmd) - - shutil.make_archive("bsl-language-server_" + "${{ matrix.prefix }}", 'zip', './',"${{ matrix.app-image }}") + - name: Build jpackage application image + run: python .github/scripts/build-jpackage.py ${{ matrix.prefix }} ${{ matrix.app-image }} - def get_bslls_jar(dir): - names = os.listdir(dir) - for name in names: - fullname = os.path.join(dir, name) - if os.path.isfile(fullname) and re.search(pattern, fullname) and fullname.find('exec.jar') != -1: - return ntpath.basename(fullname) - return None - - start() - shell: python - name: Upload artifact - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: bsl-language-server_${{ matrix.prefix }}.zip path: ./${{ matrix.app-image }} + - name: Upload assets to release - uses: AButler/upload-release-assets@v2.0 + uses: AButler/upload-release-assets@v3.0 with: files: './bsl-language-server_${{ matrix.prefix }}.zip' repo-token: ${{ secrets.GITHUB_TOKEN }} + - name: Build with Gradle if: matrix.prefix == 'nix' - run: ./gradlew build + run: ./gradlew build -x test + - name: Upload jar to release if: matrix.prefix == 'nix' - uses: AButler/upload-release-assets@v2.0 + uses: AButler/upload-release-assets@v3.0 with: files: './build/libs/*.jar' repo-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/sentry.yml b/.github/workflows/sentry.yml index c435c5b8af7..0e311643c2b 100644 --- a/.github/workflows/sentry.yml +++ b/.github/workflows/sentry.yml @@ -1,20 +1,36 @@ -name: Sentry -on: - push: - branches-ignore: - - "translations_*" -jobs: - - sentry: - name: Sentry - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - name: Create Sentry release - uses: getsentry/action-release@v1 - env: - SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} - SENTRY_ORG: ${{ secrets.SENTRY_ORG }} - SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }} - with: - environment: production +name: Sentry +on: + push: + branches-ignore: + - "translations_**" + - "dependabot/**" + tags: + - 'v*' +jobs: + + sentry: + name: Sentry + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + fetch-tags: true + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: 21 + distribution: 'temurin' + cache: gradle + - name: Get version from Gradle + id: get_version + run: echo "RELEASE_VERSION=$(./gradlew version -q)" >> $GITHUB_ENV + - name: Create Sentry release + uses: getsentry/action-release@v3 + env: + SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} + SENTRY_ORG: ${{ secrets.SENTRY_ORG }} + SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }} + with: + environment: production + version: ${{ env.RELEASE_VERSION }} diff --git a/.github/workflows/update-gradle.yml b/.github/workflows/update-gradle.yml new file mode 100644 index 00000000000..661243c279a --- /dev/null +++ b/.github/workflows/update-gradle.yml @@ -0,0 +1,26 @@ +name: Update Gradle Wrapper + +on: + workflow_dispatch: + schedule: + - cron: "0 0 * * 0" + +jobs: + update-gradle-wrapper: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: 17 + distribution: 'temurin' + cache: gradle + + - name: Update Gradle Wrapper + uses: gradle-update/update-gradle-wrapper-action@v2 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + set-distribution-checksum: false diff --git a/.gitignore b/.gitignore index 33ff50fa4de..09ec85e6fc1 100644 --- a/.gitignore +++ b/.gitignore @@ -54,6 +54,7 @@ fabric.properties *.ps1 target/ build/ +bin/ # Scala compiler user settings .idea/hydra.xml @@ -67,6 +68,7 @@ gen/ .idea/sonarlint-state.xml .idea/sonarlint.xml .idea/checkstyle-idea.xml +.idea/jpa-buddy.xml *.bak *.orig @@ -78,3 +80,6 @@ public/ bsl-language-server/ bsl-language-server_*.zip /.idea/misc.xml +*.log +*.hprof +/.idea/material_theme_project_new.xml diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml index e58ee21b50e..05a3cea0e75 100644 --- a/.idea/codeStyles/Project.xml +++ b/.idea/codeStyles/Project.xml @@ -31,6 +31,9 @@ + + - + \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000000..d53ecaf3d72 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "java.compile.nullAnalysis.mode": "automatic", + "java.configuration.updateBuildConfiguration": "automatic" +} \ No newline at end of file diff --git a/README.md b/README.md index 518fddf7323..50b10e59ded 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,6 @@ [![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=alert_status)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) [![Maintainability](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=coverage)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) -[![Crowdin](https://badges.crowdin.net/bsl-language-server/localized.svg)](https://crowdin.com/project/bsl-language-server) [![Benchmark](https://1c-syntax.github.io/bsl-language-server/dev/bench/benchmark.svg)](https://1c-syntax.github.io/bsl-language-server/dev/bench/index.html) [![telegram](https://img.shields.io/badge/telegram-chat-green.svg)](https://t.me/bsl_language_server) diff --git a/build.gradle.kts b/build.gradle.kts index 8d0748c34ef..ec4d64a000a 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,6 +1,7 @@ import me.qoomon.gitversioning.commons.GitRefType import org.apache.tools.ant.filters.EscapeUnicode import java.util.* +import java.text.SimpleDateFormat plugins { `java-library` @@ -8,27 +9,29 @@ plugins { jacoco signing id("org.cadixdev.licenser") version "0.6.1" - id("org.sonarqube") version "3.5.0.2730" - id("io.freefair.lombok") version "6.6" - id("io.freefair.javadoc-links") version "6.6" - id("io.freefair.javadoc-utf-8") version "6.6" - id("io.freefair.aspectj.post-compile-weaving") version "6.6" - id("io.freefair.maven-central.validate-poms") version "6.6" - id("me.qoomon.git-versioning") version "6.3.7" - id("com.github.ben-manes.versions") version "0.44.0" - id("org.springframework.boot") version "2.7.5" - id("io.spring.dependency-management") version "1.1.0" - id("io.github.1c-syntax.bslls-dev-tools") version "0.7.1" - id("ru.vyarus.pom") version "2.2.2" - id("com.gorylenko.gradle-git-properties") version "2.4.1" + id("org.sonarqube") version "6.0.1.5171" + id("io.freefair.lombok") version "8.12.2.1" + id("io.freefair.javadoc-links") version "8.12.2.1" + id("io.freefair.javadoc-utf-8") version "8.12.2.1" + id("io.freefair.aspectj.post-compile-weaving") version "8.12.2.1" + id("io.freefair.maven-central.validate-poms") version "8.12.2.1" + id("me.qoomon.git-versioning") version "6.4.4" + id("com.github.ben-manes.versions") version "0.52.0" + id("org.springframework.boot") version "3.4.3" + id("io.spring.dependency-management") version "1.1.7" + id("io.sentry.jvm.gradle") version "5.3.0" + id("io.github.1c-syntax.bslls-dev-tools") version "0.8.1" + id("ru.vyarus.pom") version "3.0.0" + id("com.gorylenko.gradle-git-properties") version "2.4.2" id("io.codearte.nexus-staging") version "0.30.0" - id("me.champeau.jmh") version "0.6.8" + id("me.champeau.jmh") version "0.7.3" } repositories { mavenLocal() mavenCentral() - maven(url = "https://jitpack.io") + maven(url = "https://projectlombok.org/edge-releases") + maven(url = "https://s01.oss.sonatype.org/content/repositories/snapshots") } group = "io.github.1c-syntax" @@ -49,15 +52,13 @@ gitVersioning.apply { } } -val isSnapshot = gitVersioning.gitVersionDetails.refType != GitRefType.TAG +gitProperties { + customProperty("git.build.time", buildTime()) +} -val languageToolVersion = "5.6" +val isSnapshot = gitVersioning.gitVersionDetails.refType != GitRefType.TAG -dependencyManagement { - imports { - mavenBom("io.sentry:sentry-bom:6.9.2") - } -} +val languageToolVersion = "6.5" dependencies { @@ -66,61 +67,68 @@ dependencies { // spring api("org.springframework.boot:spring-boot-starter") api("org.springframework.boot:spring-boot-starter-websocket") - api("info.picocli:picocli-spring-boot-starter:4.7.0") + api("org.springframework.boot:spring-boot-starter-cache") + api("info.picocli:picocli-spring-boot-starter:4.7.6") // lsp4j core - api("org.eclipse.lsp4j", "org.eclipse.lsp4j", "0.17.0") - api("org.eclipse.lsp4j", "org.eclipse.lsp4j.websocket", "0.17.0") + api("org.eclipse.lsp4j", "org.eclipse.lsp4j", "0.24.0") + api("org.eclipse.lsp4j", "org.eclipse.lsp4j.websocket.jakarta", "0.24.0") // 1c-syntax - api("com.github.1c-syntax", "bsl-parser", "167aaad827322e09ccde4658a71152dad234de4b") { - exclude("com.tunnelvisionlabs", "antlr4-annotations") + api("io.github.1c-syntax", "bsl-parser", "0.26.0") { exclude("com.ibm.icu", "*") exclude("org.antlr", "ST4") exclude("org.abego.treelayout", "org.abego.treelayout.core") exclude("org.antlr", "antlr-runtime") - exclude("org.glassfish", "javax.json") } - api("com.github.1c-syntax", "utils", "f1694d9c") - api("com.github.1c-syntax", "mdclasses", "0.10.3") - api("io.github.1c-syntax", "bsl-common-library", "0.3.0") - api("io.github.1c-syntax", "supportconf", "0.1.1") + api("io.github.1c-syntax", "utils", "0.6.2") + api("io.github.1c-syntax", "mdclasses", "0.15.0") + api("io.github.1c-syntax", "bsl-common-library", "0.8.0") + api("io.github.1c-syntax", "supportconf", "0.14.2") + api("io.github.1c-syntax", "bsl-parser-core", "0.3.0") // JLanguageTool - implementation("org.languagetool", "languagetool-core", languageToolVersion) + implementation("org.languagetool", "languagetool-core", languageToolVersion){ + exclude("commons-logging", "commons-logging") + } implementation("org.languagetool", "language-en", languageToolVersion) implementation("org.languagetool", "language-ru", languageToolVersion) // AOP - implementation("org.aspectj", "aspectjrt", "1.9.7") + implementation("org.aspectj", "aspectjrt", "1.9.22.1") // commons utils - implementation("commons-io", "commons-io", "2.11.0") - implementation("org.apache.commons", "commons-lang3", "3.12.0") - implementation("commons-beanutils", "commons-beanutils", "1.9.4") + implementation("commons-io", "commons-io", "2.18.0") + implementation("commons-beanutils", "commons-beanutils", "1.10.1"){ + exclude("commons-logging", "commons-logging") + } + implementation("commons-codec", "commons-codec", "1.16.0") + implementation("org.apache.commons", "commons-lang3", "3.17.0") implementation("org.apache.commons", "commons-collections4", "4.4") + implementation("org.apache.commons", "commons-exec", "1.4.0") // progress bar - implementation("me.tongfei", "progressbar", "0.9.2") + implementation("me.tongfei", "progressbar", "0.10.1") // (de)serialization implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310") implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-xml") // graphs - implementation("org.jgrapht", "jgrapht-core", "1.5.1") + implementation("org.jgrapht", "jgrapht-core", "1.5.2") // SARIF serialization implementation("com.contrastsecurity", "java-sarif", "2.0") - // Sentry - implementation("io.sentry:sentry-spring-boot-starter") - implementation("io.sentry:sentry-logback") - + // CONSTRAINTS + implementation("com.google.guava:guava") { + version { + strictly("33.4.0-jre") + } + } + // COMPILE - - // stat analysis - compileOnly("com.google.code.findbugs", "jsr305", "3.0.2") + compileOnly("com.github.spotbugs:spotbugs-annotations:4.9.2") // TEST @@ -130,13 +138,13 @@ dependencies { } // test utils - testImplementation("com.ginsberg", "junit5-system-exit", "1.1.2") - testImplementation("org.awaitility", "awaitility", "4.1.1") + testImplementation("org.jmockit", "jmockit", "1.49") + testImplementation("org.awaitility", "awaitility", "4.3.0") } java { - sourceCompatibility = JavaVersion.VERSION_11 - targetCompatibility = JavaVersion.VERSION_11 + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 withSourcesJar() withJavadocJar() } @@ -163,6 +171,11 @@ tasks.bootJar { archiveClassifier.set("exec") } +tasks.named("sourcesJar") { + dependsOn(tasks.generateSentryDebugMetaPropertiesjava) + dependsOn(tasks.collectExternalDependenciesForSentry) +} + tasks.build { dependsOn(tasks.bootJar) } @@ -177,6 +190,9 @@ tasks.test { reports { html.required.set(true) } + + val jmockitPath = classpath.find { it.name.contains("jmockit") }!!.absolutePath + jvmArgs("-javaagent:${jmockitPath}") } tasks.check { @@ -184,13 +200,27 @@ tasks.check { mustRunAfter(tasks.generateDiagnosticDocs) } +tasks.checkLicenseMain { + dependsOn(tasks.generateSentryDebugMetaPropertiesjava) + dependsOn(tasks.collectExternalDependenciesForSentry) +} + +tasks.updateLicenseMain { + dependsOn(tasks.generateSentryDebugMetaPropertiesjava) + dependsOn(tasks.collectExternalDependenciesForSentry) +} + tasks.jacocoTestReport { reports { xml.required.set(true) - xml.outputLocation.set(File("$buildDir/reports/jacoco/test/jacoco.xml")) + xml.outputLocation.set(File("${layout.buildDirectory.get()}/reports/jacoco/test/jacoco.xml")) } } +jmh { + jmhVersion = "1.37" +} + tasks.processResources { filteringCharset = "UTF-8" // native2ascii gradle replacement @@ -207,12 +237,12 @@ tasks.generateDiagnosticDocs { doLast { val resourcePath = tasks["processResources"].outputs.files.singleFile copy { - from("$buildDir/docs/diagnostics") + from("${layout.buildDirectory.get()}/docs/diagnostics") into("$resourcePath/com/github/_1c_syntax/bsl/languageserver/diagnostics/ru") } copy { - from("$buildDir/docs/en/diagnostics") + from("${layout.buildDirectory.get()}/docs/en/diagnostics") into("$resourcePath/com/github/_1c_syntax/bsl/languageserver/diagnostics/en") } } @@ -254,7 +284,7 @@ sonarqube { property("sonar.projectKey", "1c-syntax_bsl-language-server") property("sonar.projectName", "BSL Language Server") property("sonar.exclusions", "**/gen/**/*.*") - property("sonar.coverage.jacoco.xmlReportPaths", "$buildDir/reports/jacoco/test/jacoco.xml") + property("sonar.coverage.jacoco.xmlReportPaths", "${layout.buildDirectory.get()}/reports/jacoco/test/jacoco.xml") } } @@ -363,3 +393,9 @@ nexusStaging { tasks.withType { enabled = false } + +fun buildTime(): String { + val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") + formatter.timeZone = TimeZone.getTimeZone("UTC") + return formatter.format(Date()) +} diff --git a/docs/contributing/DiagnosticStructure.md b/docs/contributing/DiagnosticStructure.md index a312a01d2a2..f98512c41f9 100644 --- a/docs/contributing/DiagnosticStructure.md +++ b/docs/contributing/DiagnosticStructure.md @@ -45,11 +45,13 @@ - Тип диагностики `type` и ее важность `severity`, для каждой диагностики обязательно их определение. Для того, чтобы правильно выбрать тип и важность диагностики, можно обратиться к [статье](DiagnosticTypeAndSeverity.md). - Время на исправление замечания `minutesToFix` (по умолчанию 0). Данное значение используется при расчете общего техдолга проекта в трудозатрах на исправление всех замечаний (сумма времени на исправление по всем обнаруженным замечаниям). Стоит указывать время, максимально реалистичное, которое разработчик должен потратить на исправление. +- С помощью параметра `extraMinForComplexity` можно динамически увеличивать время на исправление замечания для диагностик, в которых учитывается несколько нарушающих правило мест, например при расчете сложности метода. - Набор тэгов `tag` диагностики, указывающих группы, к котором она относится. Подробнее о тэга в [статье](DiagnosticTag.md). - Границы применимости `scope` (по умолчанию `ALL`, т.е. без ограничения). BSL LS поддерживает несколько языков (oscript и bsl) и диагностики могут применяться как к одному конкретному языку, так и ко всем сразу. - Активность правила по-умолчанию `activatedByDefault` (по умолчанию `Истина`). При разработке экспериментальных, спорных либо не применимых в большинстве проектов, стоит по умолчанию отключать диагностику, активацию выполнит конечный пользователь решения. - Режим совместимости `compatibilityMode`, по которому фильтруются диагностики при использовании метаданных. По умолчанию `UNDEFINED`. - +- Список типов модулей `modules` для возможности ограничить анализируемую диагностикой область +- Признак возможности установить замечания на весь проект `canLocateOnProject`. Используется для диагностик не связанных с модулем исходного кода. На данный момент опция воспринимается только SonarQube, остальные инструменты игнорируют. Последние два могут быть опущены. Пример аннотации @@ -64,8 +66,14 @@ compatibilityMode = DiagnosticCompatibilityMode.COMPATIBILITY_MODE_8_3_3, // Режим проверки совместимости с 8.3.3 tags = { DiagnosticTag.STANDARD // Относится к диагностикам нарушения стандарта 1С - } + }, + modules = { + ModuleType.CommonModule // Анализируются только общие модули + }, + canLocateOnProject = false, // Замечание будет размещено только в привязке к модулю + extraMinForComplexity = 1 // За каждую дополнительную позицию замечания (`DiagnosticRelatedInformation`) будет добавлено по одной минуте ) + ``` Класс должен реализовывать интерфейс `BSLDiagnostic`. Если диагностика основывается на AST дереве, то класс реализации должен быть унаследован от одного из классов ниже, реализующих `BSLDiagnostic`: diff --git a/docs/contributing/EnvironmentSetting.md b/docs/contributing/EnvironmentSetting.md index 9830b52b862..f2ce34b531e 100644 --- a/docs/contributing/EnvironmentSetting.md +++ b/docs/contributing/EnvironmentSetting.md @@ -4,7 +4,7 @@ ## Необходимое ПО -* Java Development Kit 11 +* Java Development Kit 17 * [IntelliJ IDEA Community Edition](https://www.jetbrains.com/idea/download/) * Плагины IntelliJ IDEA * Lombok Plugin @@ -14,7 +14,7 @@ ### Настройки IntelliJ IDEA -* Настроить [Java SDK на JDK11](https://www.jetbrains.com/help/idea/sdk.html#manage_sdks) +* Настроить [Java SDK на JDK17](https://www.jetbrains.com/help/idea/sdk.html#manage_sdks) * Включить обработку аннотаций: `File -> Settings -> Build, Execution, Deployment -> Compiler -> Annotation Processors -> Enable annotation processing` * Выполнить настройки автоимпорта, подробно описано в [статье](https://www.jetbrains.com/help/idea/creating-and-optimizing-imports.html). Отдельно стоит обратить внимание на оптимизацию импорта. * Не надо запускать оптимизацию импортов всего проекта, за этим следят мейнтейнеры. Если после оптимизации импортов появились измененные файлы, которые не менялись в процессе разработки, стоит уведомить мейнтейнеров и откатить эти изменения. diff --git a/docs/contributing/StyleGuide.md b/docs/contributing/StyleGuide.md index b11c76c6939..0d9053a2a72 100644 --- a/docs/contributing/StyleGuide.md +++ b/docs/contributing/StyleGuide.md @@ -4,10 +4,29 @@ Постарайтесь придерживаться их, и процесс ревью Вашего кода будет гладким и шелковистым (с). -## Общие рекомендации +## Обработка null Если метод на законных основаниях может возвращать `null`, рекомендуется вместо явного возврата `null` возвращать `Optional`. Исключения (например, высокочастотные или перфомансные функции) обговариваются отдельно. +В описании пакета `package-info.java` необходимо указать, что в пакете по умолчанию используется NonNull API. +Для этого над именем пакета добавляется аннотация `@DefaultAnnotation(NonNull.class)` + +Пример: +```java +// ...Лицензия... +@DefaultAnnotation(NonNull.class) +package com.github._1c_syntax.bsl.languageserver; + +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; +``` + +Для явного указания того, что метод может принимать или возвращать `null`, используется аннотация `@edu.umd.cs.findbugs.annotations.Nullable`. + +В общем случае это позволяет не использовать аннотации `@edu.umd.cs.findbugs.annotations.NonNull` вообще. + +Аннотации по контролю за `null` из пакета `javax.annotations` или `jetbrains.annotations` использоваться не должны. + ## Форматирование 1. Весь код в модулях должен быть автоматически отформатирован. @@ -56,6 +75,6 @@ 1. Подключение новых библиотек в implementation scope стоит производить аккуратно, с контролем увеличения размера итогового jar-файла. По возможности "лишние" и незадействованные суб-зависимости стоит исключать через `exclude`. 1. Явное подключение библиотеки `com.google.guava`, `Google Collections` или прочих частей библиотек семейства Guava запрещено. В случае **крайней** необходимости допустимо копирование реализации из `Guava` внутрь BSL Language Server с выполнением условий лицензии Guava. Для всего остального есть Apache Commons. 1. Прямой импорт классов `*.google.*`, а так же прочих частей библиотек Guava запрещено. Без исключений. - +1. Пакет `jsr305` и его аннотации не должны использоваться в коде. См. раздел "Обработка null". > В процессе наполнения... diff --git a/docs/diagnostics/AllFunctionPathMustHaveReturn.md b/docs/diagnostics/AllFunctionPathMustHaveReturn.md index 7a9ff8975d8..2a44bc0bff6 100644 --- a/docs/diagnostics/AllFunctionPathMustHaveReturn.md +++ b/docs/diagnostics/AllFunctionPathMustHaveReturn.md @@ -13,7 +13,7 @@ ### Неправильно ```bsl -// если ставка заполнена, но не НДС10 и не НДС10 - вернется Неопределено +// если ставка заполнена, но не равна НДС20 и не равна НДС10 - вернется Неопределено // это может быть, как запланированное поведение, // так и ошибка проверки прочих вариантов. Функция ОпределитьСтавкуНДС(Знач Ставка) diff --git a/docs/diagnostics/CanonicalSpellingKeywords.md b/docs/diagnostics/CanonicalSpellingKeywords.md index dd96d369be8..11307483692 100644 --- a/docs/diagnostics/CanonicalSpellingKeywords.md +++ b/docs/diagnostics/CanonicalSpellingKeywords.md @@ -32,7 +32,7 @@ | Неопределено | Undefined | | Перейти | Goto | | Перем | Var | -| По | For | +| По | To | | Пока | WHile | | Попытка | Try | | Процедура | Procedure | diff --git a/docs/diagnostics/CognitiveComplexity.md b/docs/diagnostics/CognitiveComplexity.md index 0ffca8e0984..8604ddeff30 100644 --- a/docs/diagnostics/CognitiveComplexity.md +++ b/docs/diagnostics/CognitiveComplexity.md @@ -123,7 +123,7 @@ И НЕ Символы.Экспортный() Тогда // +1, логическая операция, вложенность не учитывается Если МожноПереопределить(Символ) Тогда // +3, вложенное условие, вложенность 2 - Переопредялемость = ПроверитьПереопределяемость(Символ, ТипКласса); + Переопределяемость = ПроверитьПереопределяемость(Символ, ТипКласса); Если Переопределяемость = Неопределено Тогда // +4, вложенное условие, вложенность 3 Если НЕ НеизвестностьНайдена Тогда // +5, вложенное условие, вложенность 4 НеизвестностьНайдена = Истина; diff --git a/docs/diagnostics/DenyIncompleteValues.md b/docs/diagnostics/DenyIncompleteValues.md new file mode 100644 index 00000000000..9c2a9bc3864 --- /dev/null +++ b/docs/diagnostics/DenyIncompleteValues.md @@ -0,0 +1,35 @@ +# Запрет незаполненных значений у измерений регистров (DenyIncompleteValues) + + +## Описание диагностики + +Довольно часто при проектировании структуры метаданных соблюдается правило - измерения регистра всегда должны быть заполнены конкретными значениями и не должны быть пустыми. + +Проверку на заполненность измерений удобно выполнять с помощью простых встроенных средств платформы, а именно, флага "Запрет незаполненных значений" для измерения регистра. В этом случае платформа самостоятельно будет проверять заполненность измерений и не нужно дополнительно контролировать заполнение измерения ни при программной обработке регистров, ни при интерактивной обработке. +Фактически записи с незаполненным измерением не имеют смысла в информационной базе, каким бы образом они в нее ни попали: в результате интерактивного ввода или в результате выполнения программного кода. + +Без установки указанного флага могут возникать различные ситуации, которые приводят к проблемам или усложняют сопровождение систем 1С. Например, +- пользователи смогут интерактивно указать пустые значения +- или разработчики могут при разработке ошибаться, не указывая значения измерения при подготовке записей регистра. + +Текущее правило может выдавать ложные срабатывания для измерений, которые могут быть не заполнены. + +Правило применяется для следующих регистров: +- сведений +- накопления +- бухгалтерских +- расчетных + +## Примеры + + +## Источники + + +- [Книга "Разработка интерфейса прикладных решений на платформе "1С:Предприятие 8" - глава "Проверка заполнения и проверка при записи"](https://its.1c.ru/db/pubv8devui#content:225:1) +- [Документация разработчика 1С 8.3 - Свойства измерения (ресурса, реквизита) регистра сведений](https://its.1c.ru/db/v8323doc#bookmark:dev:TI000000349) +- [Документация разработчика 1С 8.3 - Свойства измерения (ресурса, реквизита) регистра накопления](https://its.1c.ru/db/v8323doc#bookmark:dev:TI000000363) diff --git a/docs/diagnostics/DeprecatedCurrentDate.md b/docs/diagnostics/DeprecatedCurrentDate.md index b2f13115ff8..32a548fe1a4 100644 --- a/docs/diagnostics/DeprecatedCurrentDate.md +++ b/docs/diagnostics/DeprecatedCurrentDate.md @@ -3,15 +3,36 @@ ## Описание диагностики -Функция "ТекущаяДата" является устаревшей. Рекомендуется использовать функцию "ТекущаяДатаСеанса". +Конфигурации должны быть рассчитаны на работу в условиях, когда часовой пояс на серверном компьютере не совпадает с реальным часовым поясом пользователей информационной базы. Например, с сервером, расположенным в Москве, работают сотрудники компании из Владивостока, и при этом все операции в системе должны выполняться по местному времени (Владивостока). + +Такой сценарий работы часто востребован в клиент-серверных информационных базах и в прикладных решениях в модели сервиса (SaaS). + +Во всех серверных процедурах и функциях вместо функции ТекущаяДата, которая возвращает дату и время серверного компьютера, следует использовать функцию ТекущаяДатаСеанса, которая приводит время сервера к часовому поясу пользовательского сеанса. + +В клиентском коде использование функции ТекущаяДата также недопустимо. Это требование обусловлено тем, что текущее время, вычисленное в клиентском и серверном коде, не должно различаться. + +При использовании Библиотеки стандартных подсистем рекомендуется использовать функцию ДатаСеанса общего модуля ОбщегоНазначенияКлиент. ## Примеры + +### На клиенте Неправильно: ```bsl ДатаОперации = ТекущаяДата(); ``` +Правильно: + +```bsl +ДатаОперации = ОбщегоНазначенияКлиент.ДатаСеанса(); +``` + +### На сервере + +```bsl +ДатаОперации = ТекущаяДата(); +``` Правильно: diff --git a/docs/diagnostics/DisableSafeMode.md b/docs/diagnostics/DisableSafeMode.md new file mode 100644 index 00000000000..31a74a35a8e --- /dev/null +++ b/docs/diagnostics/DisableSafeMode.md @@ -0,0 +1,45 @@ +# Отключение безопасного режима (DisableSafeMode) + + +## Описание диагностики + +Помимо программного кода конфигурации, в прикладном решении может исполняться сторонний программный код, который может быть подключен с помощью внешних отчетов, внешних обработок, расширений конфигурации, внешних компонент или другими способами, например, с помощью стороннего (по отношению к конфигурации) программного кода, надежность которого разработчик гарантировать не может (далее – внешний код). При этом злоумышленник может предусмотреть в нем различные деструктивные действия (как в самом внешнем коде, так и опосредовано, через запуск внешних приложений, внешних компонент, COM-объектов), которые могут нанести вред компьютерам пользователей, серверным компьютерам, а также данным в программе. + +Перечисленные проблемы безопасности особенно критичны при работе конфигураций в модели сервиса. Например, получив доступ к сервису, вредоносный код может получить доступ сразу ко всем приложениям всех пользователей сервиса. + +Поэтому важно контролировать выполнение подобного внешнего кода в безопасном режиме, в исключительных случаях точечно разрешая выполнять код в небезопасном режиме после верификации кода. + +Правило диагностирует вызовы методов ` УстановитьБезопасныйРежим` и `УстановитьОтключениеБезопасногоРежима` в режиме отключения контроля безопасного режима +- вызов `УстановитьБезопасныйРежим (Истина)` игнорируется +- вызов `УстановитьОтключениеБезопасногоРежима(Ложь)` игнорируется + +## Примеры + +``` + УстановитьБезопасныйРежим (Ложь); // есть замечание + + Значение = Ложь; + УстановитьБезопасныйРежим (Значение); // есть замечание + + УстановитьБезопасныйРежим (Истина); // нет замечания + + УстановитьОтключениеБезопасногоРежима(Истина); // есть замечание + + Значение = Истина; + УстановитьОтключениеБезопасногоРежима(Значение); // есть замечание + + УстановитьОтключениеБезопасногоРежима(Ложь); // нет замечания +``` + +## Источники + + +- [Статья "Безопасный режим работы" - руководство разработчика 1С 8.3.22](https://its.1c.ru/db/v8322doc#bookmark:dev:TI000000186@ee788d9) +- [Стандарт "Ограничение на выполнение «внешнего» кода"](https://its.1c.ru/db/v8std/content/669/hdoc) +- [Стандарт "Безопасность прикладного программного интерфейса сервера"](https://its.1c.ru/db/v8std/content/678/hdoc) +- [Стандарт "Ограничения на использование Выполнить и Вычислить на сервере"](https://its.1c.ru/db/v8std#content:770:hdoc) +- [Стандарт Использование привилегированного режима](https://its.1c.ru/db/v8std/content/485/hdoc) diff --git a/docs/diagnostics/DoubleNegatives.md b/docs/diagnostics/DoubleNegatives.md new file mode 100644 index 00000000000..fda21235024 --- /dev/null +++ b/docs/diagnostics/DoubleNegatives.md @@ -0,0 +1,30 @@ +# Двойные отрицания (DoubleNegatives) + + +## Описание диагностики + +Использование двойных отрицаний усложняет понимание кода и может приводить к ошибкам, когда вместо истины разработчик "в уме" вычислил Ложь, или наоборот. +Двойные отрицания рекомендуется заменять на выражения условий, которые прямо выражают намерения автора. + +## Примеры + +### Неправильно + +```bsl +Если Не ТаблицаЗначений.Найти(ИскомоеЗначение, "Колонка") <> Неопределено Тогда + // Сделать действие +КонецЕсли; +``` + +### Правильно + +```bsl +Если ТаблицаЗначений.Найти(ИскомоеЗначение, "Колонка") = Неопределено Тогда + // Сделать действие +КонецЕсли; +``` + +## Источники + + +* Источник: [Remove double negative](https://www.refactoring.com/catalog/removeDoubleNegative.html) diff --git a/docs/diagnostics/DuplicatedInsertionIntoCollection.md b/docs/diagnostics/DuplicatedInsertionIntoCollection.md new file mode 100644 index 00000000000..2d2b18cdef9 --- /dev/null +++ b/docs/diagnostics/DuplicatedInsertionIntoCollection.md @@ -0,0 +1,16 @@ +# Повторное добавление/вставка значений в коллекцию (DuplicatedInsertionIntoCollection) + + +## Описание диагностики + + +## Примеры + + +## Источники + + diff --git a/docs/diagnostics/ExternalAppStarting.md b/docs/diagnostics/ExternalAppStarting.md new file mode 100644 index 00000000000..711d1403a18 --- /dev/null +++ b/docs/diagnostics/ExternalAppStarting.md @@ -0,0 +1,78 @@ +# Запуск внешних приложений (ExternalAppStarting) + + +## Описание диагностики + +Для повышения качества и безопасности решения на 1С необходимо контролировать запуск внешних приложений из кода 1С. + +Данное правило распространяется на все способы запуска внешних программ, в том числе: +- КомандаСистемы +- ЗапуститьСистему +- ЗапуститьПриложение +- НачатьЗапускПриложения +- ЗапуститьПриложениеАсинх +- ПерейтиПоНавигационнойСсылке или ФайловаяСистемаКлиент.ОткрытьНавигационнуюСсылку +- ФайловаяСистемаКлиент.ЗапуститьПрограмму (в клиентском коде) и ФайловаяСистема.ЗапуститьПрограмму (в серверном коде) +- ФайловаяСистемаКлиент.ОткрытьПроводник +- ФайловаяСистемаКлиент.ОткрытьФайл + +## Примеры + +```bsl +Процедура Метод() + СтрокаКоманды = ""; + ТекущийКаталог = ""; + ДождатьсяЗавершения = Истина; + ОписаниеОповещения = Неопределено; + ПараметрыКоманды = Новый Структура; + + КомандаСистемы(СтрокаКоманды, ТекущийКаталог); // есть замечание + ЗапуститьПриложение(СтрокаКоманды, ТекущийКаталог); // есть замечание + ЗапуститьПриложение(СтрокаКоманды, ТекущийКаталог, Истина); // есть замечание + + НачатьЗапускПриложения(ОписаниеОповещения, СтрокаКоманды, ТекущийКаталог, ДождатьсяЗавершения); // есть замечание + + ПерейтиПоНавигационнойСсылке(СтрокаКоманды); // есть замечание + ФайловаяСистемаКлиент.ОткрытьНавигационнуюСсылку(СтрокаКоманды); // есть замечание + ФайловаяСистемаКлиент.ОткрытьНавигационнуюСсылку(СтрокаКоманды, ОписаниеОповещения); // есть замечание + + ФайловаяСистемаКлиент.ЗапуститьПрограмму("ping 127.0.0.1 -n 5", ПараметрыКоманды); // есть замечание + ФайловаяСистемаКлиент.ЗапуститьПрограмму(СтрокаКоманды, ПараметрыКоманды); // есть замечание + ФайловаяСистема.ЗапуститьПрограмму(СтрокаКоманды); // есть замечание + ФайловаяСистема.ЗапуститьПрограмму(СтрокаКоманды, ПараметрыКоманды); // есть замечание + + ФайловаяСистемаКлиент.ОткрытьПроводник("C:\Users"); // есть замечание + ФайловаяСистемаКлиент.ОткрытьФайл(СтрокаКоманды); // есть замечание + ФайловаяСистемаКлиент.ОткрытьФайл(СтрокаКоманды, ОписаниеОповещения); // есть замечание + +КонецПроцедуры + +&НаКлиенте +Асинх Процедура Подключить() + СтрокаКоманды = ""; + ТекущийКаталог = ""; + ДождатьсяЗавершения = Истина; + + Ждать ЗапуститьПриложениеАсинх(СтрокаКоманды, ТекущийКаталог, ДождатьсяЗавершения); // есть замечание +КонецПроцедуры + +&НаКлиенте +Процедура ПроверкаЗапуститьСистему(ДополнительныеПараметрыКоманднойСтроки, КодВозврата) + ДождатьсяЗавершения = Истина; + + ЗапуститьСистему(); // есть замечание + ЗапуститьСистему(ДополнительныеПараметрыКоманднойСтроки); // есть замечание + ЗапуститьСистему(ДополнительныеПараметрыКоманднойСтроки, ДождатьсяЗавершения); // есть замечание + ЗапуститьСистему(ДополнительныеПараметрыКоманднойСтроки, ДождатьсяЗавершения, КодВозврата); // есть замечание +КонецПроцедуры +``` + +## Источники + + +- [стандарт Безопасность запуска приложений](https://its.1c.ru/db/v8std/content/774/hdoc) +- [стандарт Ограничение на выполнение «внешнего» кода](https://its.1c.ru/db/v8std/content/669/hdoc ) diff --git a/docs/diagnostics/FileSystemAccess.md b/docs/diagnostics/FileSystemAccess.md new file mode 100644 index 00000000000..ea11adf570b --- /dev/null +++ b/docs/diagnostics/FileSystemAccess.md @@ -0,0 +1,39 @@ +# Доступ к файловой системе (FileSystemAccess) + + +## Описание диагностики + +При код-ревью или аудите кода необходимо проверять обращения к файлам, каталогам и набор действий, выполняемых с ними, для исключения передачи конфиденциальной или защищенной информации, а также для исключения деструктивных действий с файловой системой. +Важно проверять код от сторонних разработчиков, подрядчиков, из различных интернет-сервисов, каталогов и т.п. + +По найденным замечаниям рекомендуется выполнить ручной аудит кода на предмет его правильности и безопасности. + +## Примеры + +```bsl + Текст = Новый ЧтениеТекста(ПутьФайла, КодировкаТекста.ANSI); // есть замечание + Текст = Новый ЗаписьТекста(ПутьФайла, КодировкаТекста.ANSI); // есть замечание + + ЗначениеВФайл(ПутьФайла, ЛичныеДанные); // есть замечание + КопироватьФайл(ПутьФайла, ДругойПутьФайла); // есть замечание + + МассивИмен = Новый Массив(); + МассивИмен.Добавить(ПутьФайла); + ОбъединитьФайлы(МассивИмен, ДругойПутьФайла); // есть замечание + + ПереместитьФайл(ПутьФайла, ДругойПутьФайла); // есть замечание + РазделитьФайл(ПутьФайла, 1024 * 1024 ); // есть замечание + СоздатьКаталог(ИмяКаталога); // есть замечание + УдалитьФайлы(ПутьФайла); // есть замечание +``` + +## Источники + + +* [Стандарт Доступ к файловой системе из кода конфигурации](https://its.1c.ru/db/v8std#content:542:hdoc) +* [Стандарт Безопасность запуска приложений](https://its.1c.ru/db/v8std#content:774:hdoc) +* [Безопасный режим работы - руководство разработчика](https://its.1c.ru/db/v8323doc#bookmark:dev:TI000000186) diff --git a/docs/diagnostics/GlobalContextMethodCollision8312.md b/docs/diagnostics/GlobalContextMethodCollision8312.md index 9532b1c3100..b782e38028f 100644 --- a/docs/diagnostics/GlobalContextMethodCollision8312.md +++ b/docs/diagnostics/GlobalContextMethodCollision8312.md @@ -19,7 +19,7 @@ ПобитовыйСдвигВлево|BitwiseShiftLeft ПобитовыйСдвигВправо|BitwiseShiftRight -Необходимо существующие функции конфигурации прикладного решения необходимо либо переименовать, либо удалить, заменив обращение к ним на методы глобального контекста. +Необходимо существующие функции конфигурации прикладного решения переименовать или удалить, заменив обращение к ним на методы глобального контекста. ## Примеры diff --git a/docs/diagnostics/InternetAccess.md b/docs/diagnostics/InternetAccess.md new file mode 100644 index 00000000000..974639618c7 --- /dev/null +++ b/docs/diagnostics/InternetAccess.md @@ -0,0 +1,21 @@ +# Обращение к Интернет-ресурсам (InternetAccess) + + +## Описание диагностики + +Проверьте обращение к Интернет-ресурсам и набор передаваемых данных для исключения передачи конфиденциальной или защищенной информации. + +## Примеры + +```bsl +HTTPСоединение = Новый HTTPСоединение("zabbix.localhost", 80); // замечание +FTPСоединение = Новый FTPСоединение(Сервер, Порт, Пользователь, Пароль); // замечание +``` + +## Источники + + diff --git a/docs/diagnostics/MagicDate.md b/docs/diagnostics/MagicDate.md index 9f76aaa598b..986489a1b5c 100644 --- a/docs/diagnostics/MagicDate.md +++ b/docs/diagnostics/MagicDate.md @@ -22,3 +22,16 @@ ХоверБордБудетИзобретен = Неопределено; КонецЕсли; ``` + +Также хорошим решением является использование специального метода с говорящим названием, который возвращает +дату-константу + +```bsl +Функция ДатаИзобретенияХовера() + Возврат '20151021'; +КонецФункции + +Если текДата < ДатаИзобретенияХовера() Тогда + ХоверБордБудетИзобретен = Неопределено; +КонецЕсли; +``` diff --git a/docs/diagnostics/MissedRequiredParameter.md b/docs/diagnostics/MissedRequiredParameter.md new file mode 100644 index 00000000000..8454bae0df7 --- /dev/null +++ b/docs/diagnostics/MissedRequiredParameter.md @@ -0,0 +1,33 @@ +# Пропущен обязательный параметр метода (MissedRequiredParameter) + + +## Описание диагностики + +При вызове функций не следует пропускать обязательные параметры. В противном случае в параметр будет передано значение `Неопределено`, на которое функция может быть не рассчитана. +Если же значение `Неопределено` является допустимым, то нужно +- или его передавать в функцию явно +- или сделать этот параметр необязательным со значением по умолчанию `Неопределено`. +## Примеры + +Например, для вызова процедуры + +```bsl +Процедура ПоменятьЦветПоляФормы(Форма, ИмяПоля, Цвет) +``` + +неправильно: + +```bsl +ПоменятьЦветПоляФормы(,"РезультатПроверки", ЦветаСтиля.ПоясняющийОшибкуТекст); // пропущен первый параметр Форма +ПоменятьЦветПоляФормы(,,); // пропущены все обязательные параметры +``` + +правильно: + +```bsl +ПоменятьЦветПоляФормы(ЭтотОбъект, "РезультатПроверки", Цвет); // указаны все обязательные параметры +``` + +## Источники + +[Параметры процедур и функций](https://its.1c.ru/db/v8std#content:640:hdoc) diff --git a/docs/diagnostics/MissingCommonModuleMethod.md b/docs/diagnostics/MissingCommonModuleMethod.md new file mode 100644 index 00000000000..7745c3825eb --- /dev/null +++ b/docs/diagnostics/MissingCommonModuleMethod.md @@ -0,0 +1,23 @@ +# Обращение к отсутствующему методу общего модуля (MissingCommonModuleMethod) + + +## Описание диагностики + +Правило регистрирует ошибочные обращения к методам общих модулей. +Находятся проблемные варианты +- когда метода нет в указанном общем модуле +- когда метод есть в общем модуле, но метод не является экспортным +- когда у общего модуля отсутствуют исходники, все обращения к любым его методам помечаются как ошибочные + +Исключаются варианты +- когда имя переменной совпадает с именем общего модуля +## Примеры + + +## Источники + + diff --git a/docs/diagnostics/PrivilegedModuleMethodCall.md b/docs/diagnostics/PrivilegedModuleMethodCall.md new file mode 100644 index 00000000000..5fe2ea880ef --- /dev/null +++ b/docs/diagnostics/PrivilegedModuleMethodCall.md @@ -0,0 +1,26 @@ +# Обращение к методам привилегированных модулей (PrivilegedModuleMethodCall) + + +## Описание диагностики + +При обращении к публичным процедурам и функциям привилегированных общих модулей могут нарушаться ограничения конфигурации по правам и ролям конфигурации, решения 1С. +Необходимо провалидировать подобные обращения для исключения обхода ограничений. + +## Примеры + +Например, в конфигурации существует привилегированный модуль выполнения заданий с именем `Задания`. +В этом модуле есть публичная функция `Функция ДобавитьЗадание(Знач ИмяМетода, Знач Параметры) Экспорт`. +Какой-то код конфигурации или расширения обращается к этому методу `Задания.ДобавитьЗадание("МетодДляВыполнения", Параметры);` + +Необходимо проанализировать код и убедиться в том, что: +- указан правильный метод для выполнения задания - `МетодДляВыполнения` +- метод `МетодДляВыполнения` для выполнения задания не выполняет деструктивных действий +- и не выдает пользователям данные, запрещенные ограничениями конфигурации + +## Источники + + diff --git a/docs/diagnostics/ProtectedModule.md b/docs/diagnostics/ProtectedModule.md new file mode 100644 index 00000000000..403ef3c6a4b --- /dev/null +++ b/docs/diagnostics/ProtectedModule.md @@ -0,0 +1,18 @@ +# Защищенные модули (ProtectedModule) + + +## Описание диагностики + +Отсутствие исходников модуля в конфигурации не рекомендуется. +В случае закрытого, запароленного модуля понижается качество кода, нельзя сделать ревью кода, версионирование изменений не ведется. + +## Примеры + + +## Источники + + diff --git a/docs/diagnostics/QueryToMissingMetadata.md b/docs/diagnostics/QueryToMissingMetadata.md index 76184ac9838..6ecf3bac48c 100644 --- a/docs/diagnostics/QueryToMissingMetadata.md +++ b/docs/diagnostics/QueryToMissingMetadata.md @@ -3,8 +3,8 @@ ## Описание диагностики -При активной разработке и изменения модели метаданных могут появляться запросы, в которых идет обращение к переименованным или удалили метаданным. -Также ошибочные имена таблиц могут возникать при ручном изменения запросов, без проверки с помощью конструктора запросов. +При активной разработке и изменении модели метаданных могут появляться запросы, в которых идет обращение к переименованным или удаленным метаданным. +Также ошибочные имена таблиц могут возникать при ручном изменении запросов, без проверки с помощью конструктора запросов. При выполнении запросов к несуществующим метаданным будет возникать ошибка исполнения. diff --git a/docs/diagnostics/ReservedParameterNames.md b/docs/diagnostics/ReservedParameterNames.md new file mode 100644 index 00000000000..51960a86f0a --- /dev/null +++ b/docs/diagnostics/ReservedParameterNames.md @@ -0,0 +1,18 @@ +# Зарезервированные имена параметров (ReservedParameterNames) + + +## Описание диагностики +Если имя параметра совпадает с именем системного перечисления, то невозможно будет обратиться к значениям этого системного перечисления, потому что параметр его скроет. +Синтаксическая проверка кода модуля не выявит такую ошибку. Чтобы предотвратить эту ситуацию имя параметра не должно совпадать с именами системных перечислений. +Список зарезервированных слов задается регулярным выражением. +Поиск производится без учета регистра символов. + +**Примеры настройки:** + +"ВидГруппыФормы|ВидПоляФормы" + +## Источники + + +* Источник: [Стандарт: Параметры процедур и функций](https://its.1c.ru/db/v8std/content/640/hdoc) +* Источник: [Стандарт: Правила образования имен переменных](https://its.1c.ru/db/v8std#content:454:hdoc) diff --git a/docs/diagnostics/ServerSideExportFormMethod.md b/docs/diagnostics/ServerSideExportFormMethod.md index 65e25bf1e72..192641e72ca 100644 --- a/docs/diagnostics/ServerSideExportFormMethod.md +++ b/docs/diagnostics/ServerSideExportFormMethod.md @@ -5,7 +5,7 @@ В модуле формы можно объявлять экспортные методы, доступные в клиентском контексте (обычно это методы-обработчики событий оповещения формы). -У экспортных методов формы может быть указана только директива компиляции `НаКлиенте`, так как для остальных практического смысла нет: обращение к методам формы из вне доступно только после вызова метода `ПолучитьФорму`, который доступен только на клиенте. +У экспортных методов формы может быть указана только директива компиляции `НаКлиенте`, так как для остальных практического смысла нет: обращение к методам формы извне доступно только после вызова метода `ПолучитьФорму`, который доступен только на клиенте. Указание экспортному методу формы иной директивы компиляции либо ее опускание считается ошибкой. diff --git a/docs/diagnostics/SetPrivilegedMode.md b/docs/diagnostics/SetPrivilegedMode.md new file mode 100644 index 00000000000..6733c4e1f68 --- /dev/null +++ b/docs/diagnostics/SetPrivilegedMode.md @@ -0,0 +1,69 @@ +# Использование привилегированного режима (SetPrivilegedMode) + + +## Описание диагностики + +Текущее правило находит код установки привилегированного режима. +Для внешнего кода, например, кода из внешних отчетов\обработок, это действие может быть небезопасным. + +По найденным замечаниям необходимо выполнить ручной аудит кода на предмет его правильности и безопасности. + +Правило находит вызовы метода `УстановитьПривилегированныйРежим` + вызов `УстановитьПривилегированныйРежим(Ложь)` игнорируется + +Потенциально опасны любые экспортные процедуры и функции, которые выполняют на сервере какие-либо действия с предварительной безусловной установкой привилегированного режима, так как это отключает проверку прав доступа текущего пользователя. Особого внимания требуют экспортные процедуры и функции клиентского прикладного программного интерфейса сервера 1С:Предприятия. + +Например, неправильно: +```bsl +Процедура ИзменитьИлиУдалитьДанные(...) Экспорт + +УстановитьПривилегированныйРежим(Истина); // Отключаем проверку прав доступа +// Изменяем данные в привилегированном режиме +... +КонецПроцедуры +``` +Правильно: +```bsl +Процедура ИзменитьИлиУдалитьДанные(...) Экспорт + +// Изменяем данные +// (при этом если у пользователя недостаточно прав для выполнения операции над данными, то будет вызвано исключение) +... + +КонецПроцедуры +``` +Исключение составляют случаи, когда действие, выполняемое процедурой, должно быть разрешено (или возвращаемое значение функции должно быть доступно) абсолютно всем категориям пользователей. + +Если все-таки необходимо использовать привилегированный режим внутри метода, следует использовать проверку прав доступа вручную, следует использовать метод `ВыполнитьПроверкуПравДоступа`. + +Пример предварительной проверки перед выполнением действий в привилегированном режиме: +```bsl +Процедура ИзменитьИлиУдалитьДанные(...) Экспорт + +ВыполнитьПроверкуПравДоступа(...); // Если у пользователя недостаточно прав, то будет вызвано исключение +УстановитьПривилегированныйРежим(Истина); // Отключаем проверку прав доступа + +// Изменяем данные в привилегированном режиме +... +КонецПроцедуры +``` +## Примеры + +```bsl + УстановитьПривилегированныйРежим(Истина); // есть замечание + + Значение = Истина; + УстановитьПривилегированныйРежим(Значение); // есть замечание + + УстановитьПривилегированныйРежим(Ложь); // нет замечания +``` +## Источники + + +* Источник: [Стандарт: Использование привилегированного режима](https://its.1c.ru/db/v8std/content/485/hdoc) +* Источник: [Стандарт: Безопасность прикладного программного интерфейса сервера](https://its.1c.ru/db/v8std#content:678:hdoc) +* Источник: [Стандарт: Ограничение на выполнение «внешнего» кода](https://its.1c.ru/db/v8std/content/669/hdoc) diff --git a/docs/diagnostics/TransferringParametersBetweenClientAndServer.md b/docs/diagnostics/TransferringParametersBetweenClientAndServer.md new file mode 100644 index 00000000000..dd78c94a9e0 --- /dev/null +++ b/docs/diagnostics/TransferringParametersBetweenClientAndServer.md @@ -0,0 +1,104 @@ +# Передача параметров между клиентом и сервером (TransferringParametersBetweenClientAndServer) + + +## Описание диагностики + +При передаче управления с клиента на сервер (и обратно) всегда передаются копии параметров. + +- При вызове серверной процедуры или функции с клиента происходит создание копии фактического параметра и передача этой копии на сторону сервера. +- При возврате управления с сервера на клиента также происходит создание копии формального параметра (с которым происходила работы в вызванной процедуре или функции) для передачи обратно на клиента. + +Если формальный параметр указан с модификатором Знач, то значение параметра будет передаваться только при вызове процедуры или функции и не будет передаваться обратно при возврате управления на клиента. + +Возможные сценарии: + +- Если из клиентского метода в серверный метод без модификатора Знач передается структура со вложенными структурами, и параметр не меняется внутри серверного метода, в этом случае при возврате управления от сервера будет передана копия этой структуры со всеми ее вложениями. +- В случае передачи плоской коллекции, которая не изменяется, например, массив, копия этой коллекции также зря будет возвращаться с сервера на клиент. + +В итоге отсутствие модификатора Знач при клиент-серверном взаимодействии может привести к ухудшению производительности и выполнению лишней\ненужной нагрузки как клиентом, так и сервером. + +Текущее правило находит серверные методы, выполняемые из клиентских методов, и выдает замечания на параметры без модификатора Знач, для которых не выполняется установка значения. + +## Примеры + +1. Пример с передачей параметров с клиента на сервер без "Знач" и со "Знач" +```bsl +&НаСервереБезКонтекста +Процедура ПередачаПараметровНаСервер(Парам1, Знач ПарамСоЗнач, Коллекция, Знач КоллекцияСоЗнач) + Парам1 = "Изменено1"; + ПарамСоЗнач = "Изменено2"; + Коллекция.Вставить("Ключ1", "Изменено1"); + КоллекцияСоЗнач.Вставить("Ключ2", "Изменено2"); +КонецПроцедуры + +&НаКлиенте +Процедура ПередачаПараметров(Команда) + Парам1 = "Исходное1"; + ПарамСоЗнач = "Исходное2"; + Коллекция = Новый Структура("Ключ1", "Исходное1"); + КоллекцияСоЗнач = Новый Структура("Ключ2", "Исходное2"); + + ПередачаПараметровНаСервер(Парам1, ПарамСоЗнач, Коллекция, КоллекцияСоЗнач); + + Шаблон = "после сервера %1 = <%2>"; + Сообщить(СтрШаблон(Шаблон, "Парам1", Парам1)); + Сообщить(СтрШаблон(Шаблон, "ПарамСоЗнач", ПарамСоЗнач)); + Сообщить(СтрШаблон(Шаблон, "Коллекция.Ключ1", Коллекция.Ключ1)); + Сообщить(СтрШаблон(Шаблон, "КоллекцияСоЗнач.Ключ2", КоллекцияСоЗнач.Ключ2)); +КонецПроцедуры +``` +Этот код при выполнении покажет следующий результат +``` +после сервера Парам1 = <Изменено1> +после сервера ПарамСоЗнач = <Исходное2> +после сервера Коллекция.Ключ1 = <Изменено1> +после сервера КоллекцияСоЗнач.Ключ2 = <Исходное2> +``` +Видно, что все параметры, передаваемые через Знач, после выполнения не меняют свои значения, в т.ч. и значения внутри коллекций. + +2. Пример неточной передачи параметров +```bsl +&НаКлиенте +Процедура ГруппыПользователейПеретаскиваниеЗавершение(Ответ, ДополнительныеПараметры) Экспорт + + Если Ответ = КодВозвратаДиалога.Нет Тогда + Возврат; + КонецЕсли; + + СообщениеПользователю = ПеремещениеПользователяВНовуюГруппу( + ДополнительныеПараметры.ПараметрыПеретаскивания, + ДополнительныеПараметры.Строка, + ДополнительныеПараметры.Перемещение); + +КонецПроцедуры + +// входные параметры МассивПользователей и остальные параметры не меняются +// и поэтому нет смысла дополнительно возвращать их с сервера +&НаСервере +Функция ПеремещениеПользователяВНовуюГруппу(МассивПользователей, НоваяГруппаВладелец, Перемещение) + + Если НоваяГруппаВладелец = Неопределено Тогда + Возврат Неопределено; + КонецЕсли; + + ТекущаяГруппаВладелец = Элементы.ГруппыПользователей.ТекущаяСтрока; + СообщениеПользователю = ПользователиСлужебный.ПеремещениеПользователяВНовуюГруппу( + МассивПользователей, ТекущаяГруппаВладелец, НоваяГруппаВладелец, Перемещение); + + Элементы.ПользователиСписок.Обновить(); + Элементы.ГруппыПользователей.Обновить(); + + Возврат СообщениеПользователю; + +КонецФункции +``` + +## Источники + + + +- [Статья на 1С:ИТС - Вызов с передачей управления с клиента на сервер](https://its.1c.ru/db/v8318doc#bookmark:dev:TI000000153) diff --git a/docs/diagnostics/UsageWriteLogEvent.md b/docs/diagnostics/UsageWriteLogEvent.md index 33a392f0721..ed54fefae36 100644 --- a/docs/diagnostics/UsageWriteLogEvent.md +++ b/docs/diagnostics/UsageWriteLogEvent.md @@ -57,7 +57,27 @@ ВызватьИсключение; КонецПопытки; ``` +В то же время, если во внешней попытке делается запись в ЖР, то во вложенной делать её повторно уже не нужно: +```bsl +Процедура ЗагрузитьДанные() Экспорт + Попытка + ВыполнитьЗаписьДанных(); + Исключение + ЗаписьЖурналаРегистрации(); // <- исключение подавляется с записью в ЖР + КонецПопытки; +КонецПроцедуры +Процедура ВыполнитьЗаписьДанных() + НачатьТранзакцию(); + Попытка + // ... + ЗафиксироватьТранзакцию(); + Исключение + ОтменитьТранзакцию(); + ВызватьИсключение; // <- вложенная попытка, запись в ЖР не требуется + КонецПопытки; +КонецПроцедуры +``` ## Источники +## Описание диагностики + +Объект `СистемнаяИнформация` предоставляет данные о компьютере и конфигурации в 1С, которая может быть использована в злонамеренных целях. + +## Примеры + + +## Источники + diff --git a/docs/diagnostics/UsingFindElementByString.md b/docs/diagnostics/UsingFindElementByString.md index 4acff08d202..52de8359277 100644 --- a/docs/diagnostics/UsingFindElementByString.md +++ b/docs/diagnostics/UsingFindElementByString.md @@ -1,20 +1,30 @@ -# Использование методов "НайтиПоНаименованию" и "НайтиПоКоду" (UsingFindElementByString) +# Использование методов "НайтиПоНаименованию", "НайтиПоКоду" и "НайтиПоНомеру" (UsingFindElementByString) ## Описание диагностики -Запрещено использовать методы поиска элементов "НайтиПоНаименованию" или "НайтиПоКоду". +Правило находит использование методов `НайтиПоНаименованию`, `НайтиПоКоду` или `НайтиПоНомеру` с указанием конкретных и +уникальных номеров, кодов и названий элементов или документов. +Скорее всего, подобный код не будет работать в других ИБ, что приведет к ошибкам выполнения. +Возможно, в финальный код попал тестовый код, что также не рекомендовано. + +Константные значения данных из ИБ рекомендуется указывать в константах ИБ, предопределенных элементах метаданных. ## Примеры +Неправильно: ```bsl Должность = Справочники.Должности.НайтиПоНаименованию("Ведущий бухгалтер"); ``` +или +```bsl +Должность = Справочники.Должности.НайтиПоКоду("00-0000001"); +``` или ```bsl -Должность = Справочники.Должности.НайтиПоКоду("00-0000001"); +ОбъектНазначения = Документы.ПередачаТоваровМеждуОрганизациями.НайтиПоНомеру("0000-000001", ТекущаяДата()); ``` Допустимо использование: @@ -24,3 +34,7 @@ ```bsl Справочники.КлассификаторБанков.НайтиПоКоду(СведенияОБанке.БИК); ``` + +```bsl +Документы.Реализация.НайтиПоНомеру(НомерДокумента); +``` diff --git a/docs/diagnostics/WrongWebServiceHandler.md b/docs/diagnostics/WrongWebServiceHandler.md index 0e152ea591f..d2b059933ce 100644 --- a/docs/diagnostics/WrongWebServiceHandler.md +++ b/docs/diagnostics/WrongWebServiceHandler.md @@ -5,7 +5,7 @@ При отсутствии обработчика операции web-сервиса обращение к данной операции не выдаст ни самих данных, ни ошибки на стороне клиента сервиса, ни ошибки на стороне самого сервиса. -Также важно помнить, что количество параметров операции web-сервиса должно совпадать с количество параметров, указанных в настройках операции web-сервиса. +Также важно помнить, что количество параметров операции web-сервиса должно совпадать с количеством параметров, указанных в настройках операции web-сервиса. Конфигуратор замечает нарушения указанных ограничений только при включенном флаге "Проверка существования назначенных обработчиков". diff --git a/docs/diagnostics/YoLetterUsage.md b/docs/diagnostics/YoLetterUsage.md index 47db746ee16..d2a546d80d6 100644 --- a/docs/diagnostics/YoLetterUsage.md +++ b/docs/diagnostics/YoLetterUsage.md @@ -3,7 +3,7 @@ ## Описание диагностики -В текстах модулях не допускается использовать букву "ё". +В текстах модулей не допускается использование буквы "ё". Исключения составляют интерфейсные тексты, выводимые пользователю в сообщениях, формах и справке, где употребление буквы «ё» в ряде случаев допустимо. ## Источники diff --git a/docs/en/contributing/DiagnosticStructure.md b/docs/en/contributing/DiagnosticStructure.md index b08d50035b8..fc4669a1b0b 100644 --- a/docs/en/contributing/DiagnosticStructure.md +++ b/docs/en/contributing/DiagnosticStructure.md @@ -45,26 +45,33 @@ At the time of this writing, the following properties are available: - The type of diagnostics is `type` and its importance is `severity`, for each diagnostics it is necessary to define them. In order to choose the correct type and importance of diagnostics, you can refer to [article](DiagnosticTypeAndSeverity.md). - Time to fix issue `minutesToFix` (default 0). This value is used when calculating the total technical debt of the project in labor costs to correct all comments (the sum of time to correct for all detected comments). It is worth indicating the time, as realistic as possible, that the developer should spend on fixing. +- Using the `extraMinForComplexity` parameter, you can dynamically increase the time to correct a comment for diagnostics that take into account several places that violate the rule, for example, when calculating the complexity of a method. - A set of diagnostics tags `tag` that indicate the group to which it belongs. Read more about tags in the [article](DiagnosticTag.md). - Applicability limit `scope` (by default `ALL`, i.e. no limit). BSL LS supports multiple languages (oscript and bsl) and diagnostics can be applied to one specific language or to all at once. - Default diagnostic active `activatedByDefault` (default `True`). When developing experimental, controversial, or not applicable in most projects, it is worth turning off diagnostics by default, the activation will be performed by the end user of the solution. - Compatibility mode `compatibilityMode`, by which diagnostics are filtered when using metadata. The default is `UNDEFINED`. - +- List of module types `modules` for the ability to limit the area analyzed by diagnostics +- Sign of the ability to set issues on the entire project `canLocateOnProject`. Used for diagnostics not related to the source code module. At the moment, the option is accepted only by SonarQube, other tools ignore it. The last two can be omitted. Annotation example ```java @DiagnosticMetadata( - type = DiagnosticType.CODE_SMELL, - severity = DiagnosticSeverity.MINOR, - minutesToFix = 1, - activatedByDefault = false, // Deactivated by default - scope = DiagnosticScope.BSL, // Applicable only for BSL - compatibilityMode = DiagnosticCompatibilityMode.COMPATIBILITY_MODE_8_3_3, // 8.3.3 compatibility mode + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.MINOR, + minutesToFix = 1, + activatedByDefault = false, + scope = DiagnosticScope.BSL, + compatibilityMode = DiagnosticCompatibilityMode.COMPATIBILITY_MODE_8_3_3, tags = { - DiagnosticTag.STANDARD // This is a diagnosis for violation of the 1C standard - } + DiagnosticTag.STANDARD + }, + modules = { + ModuleType.CommonModule + }, + canLocateOnProject = false, + extraMinForComplexity = 1 // For each additional note position (`DiagnosticRelatedInformation`) one minute will be added ) ``` @@ -217,7 +224,7 @@ Examples: ### Diagnostics class, inherits from AbstractSDBLVisitorDiagnostic -The diagnostic class implements the necessary `AST visitors`, according to the grammar of the query language (see [BSLParser](https://github.com/1c-syntax/bsl-parser/blob/master/src/main/antlr/SDBLParser. g4)). The complete list of visitor methods is in the `SDBLParserBaseVisitor` class. +The diagnostic class implements the necessary `AST visitors`, according to the grammar of the query language (see [BSLParser](https://github.com/1c-syntax/bsl-parser/blob/master/src/main/antlr/SDBLParser.g4)). The complete list of visitor methods is in the `SDBLParserBaseVisitor` class. The rest of the rules are identical to `AbstractVisitorDiagnostic`. @@ -355,7 +362,7 @@ The fixtures are the contents of the test resource file located in the `src/test It is necessary to add both erroneous and correct code, **marking the places of errors with comments**. It is best if the test cases are `real`, from practice, and not synthetic, invented `for diagnostics`. -## Diagnostics description +## Description The diagnostic description is created in the [Markdown](https://ru.wikipedia.org/wiki/Markdown) format in two versions - for Russian and English. The files are located in the `docs/diagnostics` directory for Russian, for English in `docs/en/diagnostics`. The file has the structure diff --git a/docs/en/contributing/EnvironmentSetting.md b/docs/en/contributing/EnvironmentSetting.md index ee86d2feb8a..f631ae0cf62 100644 --- a/docs/en/contributing/EnvironmentSetting.md +++ b/docs/en/contributing/EnvironmentSetting.md @@ -4,7 +4,7 @@ Development is underway using [IntelliJ IDEA Community Edition](https://www.jetb ## Required Software -* Java Development Kit 11 +* Java Development Kit 17 * [IntelliJ IDEA Community Edition](https://www.jetbrains.com/idea/download/) * Plugins IntelliJ IDEA * Lombok Plugin @@ -14,7 +14,7 @@ Please note that plugins do not have to be installed - if you have Internet acce ### IntelliJ IDEA Settings -* Configure [Java SDK на JDK11](https://www.jetbrains.com/help/idea/sdk.html#manage_sdks) +* Set [Java SDK to JDK17](https://www.jetbrains.com/help/idea/sdk.html#manage_sdks) * Enable annotation processing: `File -> Settings -> Build, Execution, Deployment -> Compiler -> Annotation Processors -> Enable annotation processing` * Configure auto import settings, details in the [article](https://www.jetbrains.com/help/idea/creating-and-optimizing-imports.html). Pay special attention to import optimization. * There is no need to start optimization of imports of the entire project, this is followed by maintainers. If, after optimizing imports, changed files appeared that did not change during the development process, you should notify the maintainers and roll back these changes. diff --git a/docs/en/contributing/StyleGuide.md b/docs/en/contributing/StyleGuide.md index 1049966f03a..43ec4c4143b 100644 --- a/docs/en/contributing/StyleGuide.md +++ b/docs/en/contributing/StyleGuide.md @@ -4,10 +4,29 @@ This document contains general guidelines for writing code in the BSL Language S Try to stick to them and the code review process will be simple. -## General recommendations +## Null values If a method can legally return `null`, it is recommended that you return `Optional` instead of explicitly returning `null`. Exceptions (eg. high frequency or performance functions) are negotiated separately. +The description of the `package-info.java` package must indicate that the NonNull API is used by default in the package. +To do this, the annotation `@DefaultAnnotation(NonNull.class)` is added above the package name + +Example: +```java +// ...license... +@DefaultAnnotation(NonNull.class) +package com.github._1c_syntax.bsl.languageserver; + +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; +``` + +To explicitly indicate that a method can accept or return `null`, use the annotation `@edu.umd.cs.findbugs.annotations.Nullable`. + +This avoids using the `@edu.umd.cs.findbugs.annotations.NonNull` annotation. + +The `null` control annotations from the `javax.annotations` or `jetbrains.annotations` packages are not allowed. + ## Formatting 1. All code in the modules should be automatically formatted. @@ -56,6 +75,6 @@ To simplify the creation of a logger instance, it is recommended to use the `@lo 1. Connecting new libraries to the implementation scope should be done carefully, with control over the increase in the size of the resulting jar file. If possible, "unnecessary" and unused sub-dependencies should be excluded through `exclude`. 1. Explicit linking of the `com.google.guava`, `Google Collections` library or other parts of the Guava family of libraries is prohibited. **If absolutely necessary**, it is permissible to copy the implementation from `Guava` inside the BSL Language Server, subject to the terms of the Guava license. For everything else, there is Apache Commons. 1. Import of `*.google.*` classes, as well as other parts of Guava libraries, is prohibited. With no exceptions. - +1. The `jsr305` package and its annotations should not be used in code. See section "Null values". > In the process... diff --git a/docs/en/diagnostics/CanonicalSpellingKeywords.md b/docs/en/diagnostics/CanonicalSpellingKeywords.md index 72511e8f523..6b77e38575f 100644 --- a/docs/en/diagnostics/CanonicalSpellingKeywords.md +++ b/docs/en/diagnostics/CanonicalSpellingKeywords.md @@ -32,7 +32,7 @@ A built-in language constructs, keywords must be written canonically. | Неопределено | Undefined | | Перейти | Goto | | Перем | Var | -| По | For | +| По | To | | Пока | While | | Попытка | Try | | Процедура | Procedure | diff --git a/docs/en/diagnostics/DenyIncompleteValues.md b/docs/en/diagnostics/DenyIncompleteValues.md new file mode 100644 index 00000000000..477e71da299 --- /dev/null +++ b/docs/en/diagnostics/DenyIncompleteValues.md @@ -0,0 +1,32 @@ +# Deny incomplete values for dimensions (DenyIncompleteValues) + + +## Description + +Often when designing a metadata structure, it is required that the dimensions of a register must always be filled with values (should not be empty). + +Checking for completeness of the dimension value should be done using the "Deny Incomplete Values" flag for the register dimension; additional software control of measurement filling is not required. +It is assumed that records with an empty dimension value do not make sense in the infobase. +The absence of a set flag can lead to potential problems if the application developers have not provided a value validation algorithm. + +The current rule may give a lot of false positives, use at your own risk. + +The rule applies to the following registers: +- information register +- accumulation register +- accounting register +- calculation register + +## Examples + + +## Sources + + +- [Development of the interface for applied solutions on the "1C:Enterprise" platform (RU). Ch "Fill check and check on write"](https://its.1c.ru/db/pubv8devui#content:225:1) +- [Developer's Guide - Properties of a dimension (resource, attribute) of the information register (RU)](https://its.1c.ru/db/v8323doc#bookmark:dev:TI000000349) +- [Developer's Guide - Properties of a dimension (resource, attribute) of the accumulation register (RU)](https://its.1c.ru/db/v8323doc#bookmark:dev:TI000000363) diff --git a/docs/en/diagnostics/DeprecatedCurrentDate.md b/docs/en/diagnostics/DeprecatedCurrentDate.md index c905097b880..4673c51026b 100644 --- a/docs/en/diagnostics/DeprecatedCurrentDate.md +++ b/docs/en/diagnostics/DeprecatedCurrentDate.md @@ -3,24 +3,46 @@ ## Description -The "CurrentDate" function has been deprecated. It is recommended to use the "CurrentSessionDate" function. +The configurations must be designed to work in conditions where the time zone on the server computer does not match the real time zone of the infobase users. For example, employees of a company from Vladivostok work with a server located in Moscow, and all operations in the system must be performed in local time (Vladivostok). + +Such a work scenario is often in demand in client-server infobases and in applied solutions in the service model (SaaS). + +In all server procedures and functions, instead of the CurrentDate function, which returns the server computer's date and time, you should use the CurrentSessionDate function, which converts the server's time to the user's session time zone. + +In client code, using the CurrentDate function is also not allowed. This requirement is due to the fact that the current time calculated in the client and server code must not differ. + +When using the Library of Standard Subsystems, it is recommended to use the DateSession function of the general module GeneralPurposeClient. ## Examples -Incorrect: + +### On the client +Wrong: ```bsl OperationDate = CurrentDate(); ``` +Right: + +```bsl +OperationDate = GeneralPurposeClient.SessionDate(); +``` + +### On server -Correct: +```bsl +OperationDate = CurrentDate(); +``` + +Right: ```bsl OperationDate = CurrentSessionDate(); ``` ## Sources - + + * Reference: [Metadata creation and change. Work in different timezones (RU)](https://its.1c.ru/db/v8std/content/643/hdoc) diff --git a/docs/en/diagnostics/DisableSafeMode.md b/docs/en/diagnostics/DisableSafeMode.md new file mode 100644 index 00000000000..da4c2057737 --- /dev/null +++ b/docs/en/diagnostics/DisableSafeMode.md @@ -0,0 +1,45 @@ +# Disable safe mode (DisableSafeMode) + + +## Description + +In addition to configuration code, the application solution can execute third-party program code, which can be connected in various ways (external reports and data processing, extensions, external components, etc.). The developer cannot guarantee the reliability of this code. An attacker can include various destructive actions in it that can harm user computers, servers, and data in the program. + +The listed security problems are especially critical when operating configurations in the service model, because Having gained access to the service, malicious code can immediately gain access to all applications of all users of the service. + +It is important to control the execution of such external code in safe mode, in exceptional cases (after verification) allowing code to be executed in unsafe mode. + +The rule diagnoses calls to the methods `SetSafeMode` and `SetDisableSafeMode` in the mode of disabling safe mode control +- Method call `SetDisableSafeMode(true)` is ignored +- Method call `SetDisableSafeMode(false)` is ignored + +## Examples + +``` + 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 +``` + +## Sources + + +- [Developer's Guide 8.3.22: Safe operation (RU)](https://its.1c.ru/db/v8322doc#bookmark:dev:TI000000186) +- [Standard: Restriction on the execution of "external" code (RU)](https://its.1c.ru/db/v8std/content/669/hdoc) +- [Standard: Server API Security (RU)](https://its.1c.ru/db/v8std/content/678/hdoc) +- [Standard: Restrictions on the use of Execute and Eval on the server (RU)](https://its.1c.ru/db/v8std#content:770:hdoc) +- [Standard: Using Privileged Mode (RU)](https://its.1c.ru/db/v8std/content/485/hdoc) diff --git a/docs/en/diagnostics/DoubleNegatives.md b/docs/en/diagnostics/DoubleNegatives.md new file mode 100644 index 00000000000..12e7c77500a --- /dev/null +++ b/docs/en/diagnostics/DoubleNegatives.md @@ -0,0 +1,30 @@ +# Double negatives (DoubleNegatives) + + +## Description + +Using double negatives makes the code harder to understand and can lead to errors when the developer mentally computes False instead of True, or vice versa. +It is recommended to replace double negatives with conditional expressions that directly express the author's intentions. + +## Examples + +### Incorrect + +```bsl +If Not ValueTable.Find(SearchValue, "Column") <> Undefined Then + // Do the action +EndIf; +``` + +### Correct + +```bsl +If ValueTable.Find(LookupValue, "Column") = Undefined Then + // Perform action +EndIf; +``` + +## Sources + + +* Source: [Remove double negative](https://www.refactoring.com/catalog/removeDoubleNegative.html) diff --git a/docs/en/diagnostics/DuplicatedInsertionIntoCollection.md b/docs/en/diagnostics/DuplicatedInsertionIntoCollection.md new file mode 100644 index 00000000000..aff2ea4e18a --- /dev/null +++ b/docs/en/diagnostics/DuplicatedInsertionIntoCollection.md @@ -0,0 +1,16 @@ +# Duplicate adding or pasting a value to a collection (DuplicatedInsertionIntoCollection) + + +## Description + + +## Examples + + +## Sources + + diff --git a/docs/en/diagnostics/ExternalAppStarting.md b/docs/en/diagnostics/ExternalAppStarting.md new file mode 100644 index 00000000000..59ae54e2bc5 --- /dev/null +++ b/docs/en/diagnostics/ExternalAppStarting.md @@ -0,0 +1,78 @@ +# External applications starting (ExternalAppStarting) + + +## Description + +To improve the quality and security of 1C solutions, it is necessary to control the launch of external applications from 1C code. + +This rule applies to all methods of launching external programs, including: +- System +- RunSystem +- RunApp +- BeginRunningApplication +- RunAppAsync +- GotoURL or FileSystems.OpenURL +- FileSystemsClient.RunApp (for client side) and FileSystems.RunApp (for server side) +- FileSystemClient.OpenExplorer +- FileSystemClient.OpenFile + +## Examples + +```bsl +Процедура Метод() + СтрокаКоманды = ""; + ТекущийКаталог = ""; + ДождатьсяЗавершения = Истина; + ОписаниеОповещения = Неопределено; + ПараметрыКоманды = Новый Структура; + + КомандаСистемы(СтрокаКоманды, ТекущийКаталог); // есть замечание + ЗапуститьПриложение(СтрокаКоманды, ТекущийКаталог); // есть замечание + ЗапуститьПриложение(СтрокаКоманды, ТекущийКаталог, Истина); // есть замечание + + НачатьЗапускПриложения(ОписаниеОповещения, СтрокаКоманды, ТекущийКаталог, ДождатьсяЗавершения); // есть замечание + + ПерейтиПоНавигационнойСсылке(СтрокаКоманды); // есть замечание + ФайловаяСистемаКлиент.ОткрытьНавигационнуюСсылку(СтрокаКоманды); // есть замечание + ФайловаяСистемаКлиент.ОткрытьНавигационнуюСсылку(СтрокаКоманды, ОписаниеОповещения); // есть замечание + + ФайловаяСистемаКлиент.ЗапуститьПрограмму("ping 127.0.0.1 -n 5", ПараметрыКоманды); // есть замечание + ФайловаяСистемаКлиент.ЗапуститьПрограмму(СтрокаКоманды, ПараметрыКоманды); // есть замечание + ФайловаяСистема.ЗапуститьПрограмму(СтрокаКоманды); // есть замечание + ФайловаяСистема.ЗапуститьПрограмму(СтрокаКоманды, ПараметрыКоманды); // есть замечание + + ФайловаяСистемаКлиент.ОткрытьПроводник("C:\Users"); // есть замечание + ФайловаяСистемаКлиент.ОткрытьФайл(СтрокаКоманды); // есть замечание + ФайловаяСистемаКлиент.ОткрытьФайл(СтрокаКоманды, ОписаниеОповещения); // есть замечание + +КонецПроцедуры + +&НаКлиенте +Асинх Процедура Подключить() + СтрокаКоманды = ""; + ТекущийКаталог = ""; + ДождатьсяЗавершения = Истина; + + Ждать ЗапуститьПриложениеАсинх(СтрокаКоманды, ТекущийКаталог, ДождатьсяЗавершения); // есть замечание +КонецПроцедуры + +&НаКлиенте +Процедура ПроверкаЗапуститьСистему(ДополнительныеПараметрыКоманднойСтроки, КодВозврата) + ДождатьсяЗавершения = Истина; + + ЗапуститьСистему(); // есть замечание + ЗапуститьСистему(ДополнительныеПараметрыКоманднойСтроки); // есть замечание + ЗапуститьСистему(ДополнительныеПараметрыКоманднойСтроки, ДождатьсяЗавершения); // есть замечание + ЗапуститьСистему(ДополнительныеПараметрыКоманднойСтроки, ДождатьсяЗавершения, КодВозврата); // есть замечание +КонецПроцедуры +``` + +## Sources + + +- [Standard: Application launch security (RU)](https://its.1c.ru/db/v8std#content:774:hdoc) +- Standard: [Restriction on the execution of "external" code (RU)](https://its.1c.ru/db/v8std/content/669/hdoc) diff --git a/docs/en/diagnostics/FileSystemAccess.md b/docs/en/diagnostics/FileSystemAccess.md new file mode 100644 index 00000000000..8d42717a40a --- /dev/null +++ b/docs/en/diagnostics/FileSystemAccess.md @@ -0,0 +1,38 @@ +# File system access (FileSystemAccess) + + +## Description + +It is important to review your code. Be sure to pay attention to accessing the file system and using “external code” + +The found sections of the code must be analyzed, a manual audit of the code must be performed for its correctness and safety. + +## Examples + +```bsl + Текст = Новый ЧтениеТекста(ПутьФайла, КодировкаТекста.ANSI); // есть замечание + Текст = Новый ЗаписьТекста(ПутьФайла, КодировкаТекста.ANSI); // есть замечание + + ЗначениеВФайл(ПутьФайла, ЛичныеДанные); // есть замечание + КопироватьФайл(ПутьФайла, ДругойПутьФайла); // есть замечание + + МассивИмен = Новый Массив(); + МассивИмен.Добавить(ПутьФайла); + ОбъединитьФайлы(МассивИмен, ДругойПутьФайла); // есть замечание + + ПереместитьФайл(ПутьФайла, ДругойПутьФайла); // есть замечание + РазделитьФайл(ПутьФайла, 1024 * 1024 ); // есть замечание + СоздатьКаталог(ИмяКаталога); // есть замечание + УдалитьФайлы(ПутьФайла); // есть замечание +``` + +## Sources + + +* [File system access from application code (RU)](https://its.1c.ru/db/v8std#content:542:hdoc) +* [Standard: Application launch security (RU)](https://its.1c.ru/db/v8std#content:774:hdoc) +* [Safe operation - Developer's Guide (RU](https://its.1c.ru/db/v8323doc#bookmark:dev:TI000000186) diff --git a/docs/en/diagnostics/IncorrectLineBreak.md b/docs/en/diagnostics/IncorrectLineBreak.md index f564fff9a29..337b698595a 100644 --- a/docs/en/diagnostics/IncorrectLineBreak.md +++ b/docs/en/diagnostics/IncorrectLineBreak.md @@ -18,6 +18,15 @@ Complex logical conditions in If ... ElseIf ... EndIf should be carried as follo * logical operators AND, OR are placed at the beginning of a line, and not at the end of the previous line; * 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). +**Examples of configuring exclusions:** + +- If your design standard requires a closing brace and statement separator ";" were written *after* the line containing the last parameter, then you need to change the `listOfIncorrectFirstSymbol` parameter + - instead of the substring `|\);` (at the end of the setting) you need to write the substring `|\)\s*;\s*\S+` + - final version `\)|;|,\s*\S+|\)s*;\s*\S+` + - code example is listed in the examples section + +Without the specified setting, the rule will issue notes on the closing bracket and the operator separator ";", located on a separate line + ## Examples @@ -45,6 +54,25 @@ AmountDocument = AmountWithoutDiscount + AmountAutomaticDiscount; ``` +An example of a possible arrangement of parameters and a closing bracket with the operator separator ";" + +```bsl +Names = New ValueList; +Names.Add(Name, + Synonym); +``` + +An example of a possible location of the closing bracket with the operator separator ";" on a separate line: +- without changing the `listOfIncorrectFirstSymbol` parameter (see above), the diagnostics will generate a issue for such expression wrapping. + +```bsl +Names = New ValueList; +Names.Add( + Name, + Synonym +); +``` + ## Sources diff --git a/docs/en/diagnostics/InternetAccess.md b/docs/en/diagnostics/InternetAccess.md new file mode 100644 index 00000000000..ffbd2238150 --- /dev/null +++ b/docs/en/diagnostics/InternetAccess.md @@ -0,0 +1,21 @@ +# Referring to Internet resources (InternetAccess) + + +## Description + +Check access to Internet resources and the set of transmitted data to prevent the transfer of confidential or protected information. + +## Examples + +```bsl +HTTPConnection = New HTTPConnection("zabbix.localhost", 80); // error +FTPConnection = New FTPConnection(Server, Port, User, Pwd); // error +``` + +## Sources + + diff --git a/docs/en/diagnostics/MagicDate.md b/docs/en/diagnostics/MagicDate.md index 158097d92b9..49635b0166c 100644 --- a/docs/en/diagnostics/MagicDate.md +++ b/docs/en/diagnostics/MagicDate.md @@ -22,3 +22,16 @@ If now < PredictedDate Then HoverBoardIsReal = Undefined; EndIf; ``` + +Also, a good solution is to use a special method with "telling name" that returns +constant + +```bsl +Function DateInventionHover() + Return '20151021'; +EndFunction + +If CurrentDate < DateInventionHover() Then + HoverBoardWillBeInvented = Undefined; +EndIf; +``` diff --git a/docs/en/diagnostics/MissedRequiredParameter.md b/docs/en/diagnostics/MissedRequiredParameter.md new file mode 100644 index 00000000000..1c260e27cd0 --- /dev/null +++ b/docs/en/diagnostics/MissedRequiredParameter.md @@ -0,0 +1,33 @@ +# Missed a required method parameter (MissedRequiredParameter) + + +## Description + +Required parameters must not be omitted when calling methods, otherwise the value `Undefined` will be passed to the parameter, which the method often cannot process. +If the value `Undefined` is valid, then you need to +- explicitly pass a value +- or make the parameter optional with a default value of `Undefined`. +## Examples + +For example + +```bsl +Procedure ChangeFormFieldColor(Form, FiledName, Color) +``` + +Incorrect: + +```bsl +ChangeFormFieldColor(,"Result", StyleColors.ArthursShirtColor); // missing first parameter Form +ChangeFormFieldColor(,,); // missing all required parameters +``` + +Correct: + +```bsl +ChangeFormFieldColor(ThisObject, "Result", Color); // all required parameters are specified +``` + +## Sources + +[Parameters of procedures and functions (RU)](https://its.1c.ru/db/v8std#content:640:hdoc) diff --git a/docs/en/diagnostics/MissingCommonModuleMethod.md b/docs/en/diagnostics/MissingCommonModuleMethod.md new file mode 100644 index 00000000000..ee61d21f3a9 --- /dev/null +++ b/docs/en/diagnostics/MissingCommonModuleMethod.md @@ -0,0 +1,23 @@ +# Referencing a missing common module method (MissingCommonModuleMethod) + + +## Description + +Diagnostics detects erroneous calls to methods of common modules. +Detects the following errors +- method does not exist in the specified common module +- method is in the common module, but it is not exported +- if a common module has no source code, then all calls to its methods are marked as erroneous + +Excluded +- the variable name is the same as the common module name +## Examples + + +## Sources + + diff --git a/docs/en/diagnostics/PrivilegedModuleMethodCall.md b/docs/en/diagnostics/PrivilegedModuleMethodCall.md new file mode 100644 index 00000000000..87647762992 --- /dev/null +++ b/docs/en/diagnostics/PrivilegedModuleMethodCall.md @@ -0,0 +1,16 @@ +# Accessing privileged module methods (PrivilegedModuleMethodCall) + + +## Description + +Code running in `privileged` `mode` must be checked. + +## Examples + + +## Sources + + diff --git a/docs/en/diagnostics/ProtectedModule.md b/docs/en/diagnostics/ProtectedModule.md new file mode 100644 index 00000000000..7a6babe4907 --- /dev/null +++ b/docs/en/diagnostics/ProtectedModule.md @@ -0,0 +1,18 @@ +# Protected modules (ProtectedModule) + + +## Description + +The absence of module sources in the configuration is not recommended. +In the case of a closed, password-protected module, the quality of the code decreases, it is impossible to review the code, and versioning of changes is not carried out. + +## Examples + + +## Sources + + diff --git a/docs/en/diagnostics/PublicMethodsDescription.md b/docs/en/diagnostics/PublicMethodsDescription.md index 2e6b9637d50..cfc30d605cd 100644 --- a/docs/en/diagnostics/PublicMethodsDescription.md +++ b/docs/en/diagnostics/PublicMethodsDescription.md @@ -2,7 +2,7 @@ ## Description -All public methods located inside regions must have a description. +All export methods in the `Public` region must have a description. ## Sources * [Standard: "Procedure and function defenition". Paragraph 2 (RU)](https://its.1c.ru/db/v8std#content:453:hdoc) diff --git a/docs/en/diagnostics/ReservedParameterNames.md b/docs/en/diagnostics/ReservedParameterNames.md new file mode 100644 index 00000000000..50a783d844b --- /dev/null +++ b/docs/en/diagnostics/ReservedParameterNames.md @@ -0,0 +1,22 @@ +# Reserved parameter names (ReservedParameterNames) + + +## Description + + +If a parameter name matches one of a system enumeration's name, then all values of that enumeration will not be available in the local context. +Module code's syntax checking will not detect an error. To prevent this situation, a parameter name should not match all names of system enumerations. + +Parameter names should not contain reserved words such as system enumerations. +The list of reserved words is set by a regular expression. +The search is case-insensitive. + +**For example:** + +"FormGroupType|FormFieldType" + +## Sources + + +* Source: [Standard: Procedure and Function Parameters (RU)](https://its.1c.ru/db/v8std/content/640/hdoc) +* Source: [Standard: Rules for generating variable names (RU)](https://its.1c.ru/db/v8std#content:454:hdoc) diff --git a/docs/en/diagnostics/RewriteMethodParameter.md b/docs/en/diagnostics/RewriteMethodParameter.md index 248d552de25..27128fc7cc9 100644 --- a/docs/en/diagnostics/RewriteMethodParameter.md +++ b/docs/en/diagnostics/RewriteMethodParameter.md @@ -3,14 +3,42 @@ ## Description +It is wrong to write methods in which their arguments are overwritten immediately on entry. + +It is necessary to correct this deficiency by removing the parameters, converting them to local variables. ## Examples +Suspicious code +```bsl +Procedure Configor(Val ConnectionString, Val User = "", Val Pass = "") Export + ConnectionString = "/F""" + DataBaseDir + """"; // Error +... +EndProcedure +``` + +Сorrected: +```bsl +Procedure Configor(Val DataBaseDir, Val User = "", Val Pass = "") Export +ConnectionString = "/F""" + DataBaseDir + """"; // No error +... +EndProcedure +``` +or +```bsl +Procedure Configor(Val DataBaseDir, Val User = "", Val Pass = "") Export + If Not EmpyString(DataBaseDir) Then +NewConnectionString = "/F""" + DataBaseDir + """"; +Else +NewConnectionString = ConnectionString; // Hmm, where is this from? +EndIf; + +... +EndProcedure +``` ## Sources +* [PVS-Studio V763. Parameter is always rewritten in function body before being used](https://pvs-studio.com/ru/docs/warnings/v6023) diff --git a/docs/en/diagnostics/ScheduledJobHandler.md b/docs/en/diagnostics/ScheduledJobHandler.md index e3ef7135868..002e40b5061 100644 --- a/docs/en/diagnostics/ScheduledJobHandler.md +++ b/docs/en/diagnostics/ScheduledJobHandler.md @@ -3,6 +3,19 @@ ## Description +Certain requirements are imposed on the methods of scheduled job handlers. +Any export procedure or function of a non-global common server module can be used as a scheduled job method. If the scheduled job method is a function, then its return value is ignored. + +If the scheduled job is predefined, then its handler should not have parameters. +Otherwise, the parameters of such a scheduled job can be any values ​​that are allowed to be sent to the server. The parameters of a scheduled job must exactly match the parameters of the procedure or function it calls. + +Diagnostics checks the following signs of the correctness of the scheduled job handler method: +- there is a common module and a shared module method specified as a handler +- common module is server +- the method is export +- the method has no parameters if the scheduled job is predefined +- method body is not empty +- there are no other scheduled jobs that refer to the same handler method ## Examples @@ -11,6 +24,8 @@ +- [Set of articles "Scheduled job" - standard 1C (RU)](https://its.1c.ru/db/v8std#browse:13:-1:1:6) +- [Article "Scheduled job" from the developer's guide 1C 8.3 (RU)](https://its.1c.ru/db/v8322doc#bookmark:dev:TI000000794) diff --git a/docs/en/diagnostics/ServerSideExportFormMethod.md b/docs/en/diagnostics/ServerSideExportFormMethod.md index d886a1f4f1c..478e3f60df2 100644 --- a/docs/en/diagnostics/ServerSideExportFormMethod.md +++ b/docs/en/diagnostics/ServerSideExportFormMethod.md @@ -2,7 +2,6 @@ ## Description - In a form module, you can declare export methods that are available in the client context (usually, these are form notification event handlers). For export methods of the form, only the compilation directive `AtClient` can be specified, since for the rest there is no practical sense: accessing form methods from outside is available only after calling the method `GetForm`, which is available only on the client. diff --git a/docs/en/diagnostics/SetPrivilegedMode.md b/docs/en/diagnostics/SetPrivilegedMode.md new file mode 100644 index 00000000000..7477af6fa95 --- /dev/null +++ b/docs/en/diagnostics/SetPrivilegedMode.md @@ -0,0 +1,68 @@ +# Using privileged mode (SetPrivilegedMode) + + +## Description + +Diagnostic finds Privileged mode setup code. +For external code, such as code from external reports/data processors, this action may not be safe. + +The found sections of the code must be analyzed, a manual audit of the code must be performed for its correctness and safety. + +Правило находит вызовы метода The diagnostic finds calls to the `SetPrivilegedMode` method +call to `SetPrivilegedMode(False)` is ignored + +Any export procedures and functions that perform any actions on the server with the privileged mode set unconditionally beforehand are potentially dangerous, as this disables checking the access rights of the current user. The export procedures and functions of the client API of the 1C:Enterprise server require special attention. + +For example, wrong: +```bsl +Procedure ChangeData(...) Export + +SetPrivilegedMode(True); // Disable permission check +// Change data in privileged mode +... +EndProcedure +``` +Correct: +```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 +``` +The exception is when the action performed by the procedure must be allowed (or the return value of the function must be available) to absolutely all categories of users. + +If you still need to use privileged mode within a method, you must use manual access control using the `VerifyAccessRights` method. + +An example of pre-checking before performing actions in privileged mode: +```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 +``` +## Examples + +```bsl + SetPrivilegedMode(True); // error + + Value = True; + SetPrivilegedMode(Value); // error + + SetPrivilegedMode(False); // no error +``` +## Sources + + +* Standard: [Using Privileged Mode (RU)](https://its.1c.ru/db/v8std/content/485/hdoc) +* Standard: [Server API Security (RU)](https://its.1c.ru/db/v8std#content:678:hdoc) +* Standard: [Restriction on the execution of "external" code (RU)](https://its.1c.ru/db/v8std/content/669/hdoc) diff --git a/docs/en/diagnostics/TransferringParametersBetweenClientAndServer.md b/docs/en/diagnostics/TransferringParametersBetweenClientAndServer.md new file mode 100644 index 00000000000..d6eaf85bcee --- /dev/null +++ b/docs/en/diagnostics/TransferringParametersBetweenClientAndServer.md @@ -0,0 +1,112 @@ +# Transferring parameters between the client and the server (TransferringParametersBetweenClientAndServer) + + +## Description + +When transferring control from the client to the server (and vice versa), copies of the parameters are always transferred. + +- When a server procedure or function is called from the client, a copy of the actual parameter is created and this copy is passed to the server side. + +- When control is returned from the server to the client, a copy of the formal parameter (which was handled in the called procedure or function) is also created for transfer back to the client. + +If a formal parameter is specified with the Val modifier, then the value of the parameter will only be passed when the procedure or function is called and will not be passed back when control returns to the client. + +Possible scenarios: + +- If a structure with nested structures is passed from the client method to the server method without the Val modifier, and the parameter does not change inside the server method, then a copy of this structure with all its attachments will be transferred from the server when control returns. +- In the case of transferring a flat collection that does not change, for example, an array, a copy of this collection will also be returned from the server to the client in vain. + +As a result, the absence of the Val modifier in client-server interaction can lead to performance degradation and unnecessary/unnecessary load both by the client and the server. + +The current rule finds server methods that execute from client methods and throws remarks on parameters without the Val modifier that are not set to a value. + +## Examples + +  +1. An example with passing parameters from the client to the server without "Val" and with "Val" +```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 + +``` +This code, when executed, will show the following result +``` +after server Param1= +after server ParamWithVal= +after server Collection.Key1 =   +after server CollectionWithVal.Key2= +``` +It can be seen that all parameters passed through Value do not change their values after execution, incl. and values within collections. + +2. An example of inaccurate parameter transfer +```bsl +&AtClient +Procedure UserGroupsDragNDropFinish(Response, AdditionalParameters) + +If Response = DialogReturnCode.No Then +Return; +EndIf; + +MessageToUser = MoveUserToNewGroup( +AdditionalOptions.DragNDropOptions, +AdditionalParameters.String, +AdditionalParameters.Move +); + +EndProcedure + +// input parameters ArrayUsers and other parameters do not change +// and therefore there is no point in additionally returning them from the server +&AtServer +Function MoveUserToNewGroup(ArrayUsers, NewGroupOwner, Move) + +If NewGroupOwner = Undefined Then +Return Undefined; +EndIf; + +CurrentGroupOwner = Items.UserGroups.CurrentRow; +MessageToUser = UsersService.MovingUserToNewGroup( +ArrayUsers, CurrentGroupOwner, NewGroupOwner, Move); + +Items.UsersList.Update(); +Items.UserGroups.Refresh(); + +Return MessageToUser; + +EndFunction +``` +## Sources + + + +- [Article on 1C:ITS - Call with transfer of control from client to server](https://its.1c.ru/db/v8318doc#bookmark:dev:TI000000153) diff --git a/docs/en/diagnostics/UsageWriteLogEvent.md b/docs/en/diagnostics/UsageWriteLogEvent.md index 241ae91838d..b91b67c66be 100644 --- a/docs/en/diagnostics/UsageWriteLogEvent.md +++ b/docs/en/diagnostics/UsageWriteLogEvent.md @@ -55,7 +55,27 @@ Correct code Raise; EndTry; ``` - +If an outer attempt makes a log entry, then there is no need to do it again in a nested attempt: +```bsl +Процедура ЗагрузитьДанные() Экспорт + Попытка + ВыполнитьЗаписьДанных(); + Исключение + ЗаписьЖурналаРегистрации(); // <- исключение подавляется с записью в ЖР + КонецПопытки; +КонецПроцедуры + +Процедура ВыполнитьЗаписьДанных() + НачатьТранзакцию(); + Попытка + // ... + ЗафиксироватьТранзакцию(); + Исключение + ОтменитьТранзакцию(); + ВызватьИсключение; // <- вложенная попытка, запись в ЖР не требуется + КонецПопытки; +КонецПроцедуры +``` ## Sources +## Description + +`SystemInformation` provides data about the computer and configuration in 1C, which can be used for malicious purposes. + +## Examples + + +## Sources + diff --git a/docs/en/diagnostics/UsingFindElementByString.md b/docs/en/diagnostics/UsingFindElementByString.md index 56136068be1..2b5abd56ba4 100644 --- a/docs/en/diagnostics/UsingFindElementByString.md +++ b/docs/en/diagnostics/UsingFindElementByString.md @@ -1,20 +1,29 @@ -# Using FindByName and FindByCode (UsingFindElementByString) +# Using FindByName, FindByCode and FindByNumber (UsingFindElementByString) ## Description -It is forbidden to use the search methods for elements "FindByName" or "FindByCode". +The rule finds the use of the `FindByName`, `FindByCode` or `FindByNumber` methods using specific numbers, codes and names of elements or documents. +Similar code may not work correctly in other databases. +Often such code is test code included in the release version, which is also not recommended. + +It is recommended to specify constant data values ​​from the database in "Сonstants" or predefined metadata elements. ## Examples +Incorrect: ```bsl Position = Catalogs.Positions.FindByName("Senior Accountant"); ``` +or +```bsl +Position = Catalogs.Positions.FindByCode("00-0000001"); +``` or ```bsl -Position = Catalogs.Positions.FindByCode("00-0000001"); +Object = Documents.Invoice.FindByNumber("0000-000001", CurrentDate()); ``` Acceptable use: @@ -24,3 +33,7 @@ Catalogs.Currencies.FindByCode(CurrentData.CurrencyCodeDigital); ```bsl Catalogs.BankClassifier.FindByCode(BankDetails.BIK); ``` + +```bsl +Documents.Invoice.FindByNumber(Number); +``` diff --git a/docs/en/diagnostics/YoLetterUsage.md b/docs/en/diagnostics/YoLetterUsage.md index de2fc3d43ac..4c4a1f7429f 100644 --- a/docs/en/diagnostics/YoLetterUsage.md +++ b/docs/en/diagnostics/YoLetterUsage.md @@ -7,4 +7,4 @@ In code it is prohibited to use character "yo" ("ё"). Exception is interface te ## Sources -* [Standard: Modules texts(RU)](https://its.1c.ru/db/v8std#content:456:hdoc) +* Source: [Standard: Modules (RU)](https://its.1c.ru/db/v8std#content:456:hdoc) diff --git a/docs/en/features/ConfigurationFile.md b/docs/en/features/ConfigurationFile.md index 04d4bba57b6..ef7c663dba8 100644 --- a/docs/en/features/ConfigurationFile.md +++ b/docs/en/features/ConfigurationFile.md @@ -7,25 +7,35 @@ If there is no configuration file, an attempt will be made to find the ".bsl-lan ## Settings -|Name|Type|Description| -|:--|:-:|:--| -|`language`|`String`|Set the language for displaying diagnosed comments. Supported languages:
* `ru` - for Russian (*default*)
* `en` - for English| -|`codeLens`|`JSON-Object`|Contains the settings for displaying `lens` in advanced code editors/IDEs *(for example, [Visual Studio Code](https://code.visualstudio.com/))*, which displays various information above a block of code. Object properties| -|⤷   `parameters`|`JSON-Object`|Collection of lens settings. Collection items are json-objects with the following structure:
* *object key* - string, is lens key
* *object value* - if is boolean, then interpreted as lens off-switch (`false`) or on-switch with default parameters (`true`), if is type `json-object`, collection of lens parameters.| -|   ⤷   `cognitiveComplexity`|`Boolean` or `JSON-Object`|Enables displaying the value of the [cognitive complexity](../diagnostics/CognitiveComplexity.md) of the method over its definition. The default is ` true `. Lens options: `complexityThreshold` - lens response threshold. The default is - `-1`.| -|   ⤷   `cyclomaticComplexity`|`Boolean` or `JSON-Object`|Enables displaying the value of the [cyclomatic complexity](../diagnostics/CyclomaticComplexity.md) of the method over its definition. The default is `true`. Lens options: `complexityThreshold` - lens response threshold. The default is - `-1`.| -|`diagnostics`|`JSON-Object`|Contains diagnostic settings| -|⤷   `computeTrigger`|`String`|Event that will trigger the code analysis procedure to diagnose comments. Possible values:
* `onType` -when editing a file (online) ***on large files can significantly slow down editing ***
* `onSave` - when saving a file (*default*)
`never` - analysis will not be performed| -|⤷   `ordinaryAppSupport`|`Boolean>`|Ordinary client support. Diagnostics will require taking into account the features of a ordinary application. Values:
* `true` - the configuration uses ordinary application *(default)*
* `false` - ignore ordinary application warnings| -|⤷   `skipSupport`|`String`|This parameter sets **1C configuration** file skipping mode *(for example files are not analyzed for issues)* which are "on support" from vendor configuration. Possible values:
* `withSupport` - skip all modules set "on support" *(all "locks" types)*
* `withSupportLocked` - skip modules set "on support" with prohibited modification *("yellow closed lock")*
* `never` - skip no modules as support mode is not analyzed *(set by default)*| -|⤷   `mode`|`String`|Setting for controlling the diagnostic settings accounting mode. Possible options:
* `OFF` - All diagnostics are considered to be turned off, regardless of their settings.
* `ON` - All diagnostics enabled by default are considered enabled, the rest - depending on personal settings
* `EXCEPT` - All diagnostics other than those specified are considered enabled.
* `ONLY` - Only the specified diagnostics are considered enabled.
* `ALL` - All diagnostics are considered enabled| -|⤷   `parameters`|`JSON-Object`|Parameter is a collection of diagnostics parameters. Collection items are json-objects with the following structure:
* *object key* - string, is diagnostic key
* *object value* - if is boolean, then interpreted as diagnostic off-switch (`false`) or on-switch with default parameters (`true`), if is type `json-object`, collection of diagnostic parameters.

Key, if set to ON by default and all allowed parameters and examples are given on the diagnostic page.| -|`documentLink`|`JSON-Object`|Contains documentation link settings| -|⤷   `showDiagnosticDescription`|`Boolean`|Show additional links to diagnostics documentation. By default, the parameter is off (*set to `false`*)| -|`useDevSite`|`Boolean`|When you turn on the settings, the resulting documentation links will lead to the develop version of the site. By default, the parameter is off (*set to `false`*)| -|`siteRoot`|`String`|The path to the root of the site with the documentation. By default, the parameter value is `"https://1c-syntax.github.io/bsl-language-server"` | -|`traceLog`|`String`|To log all requests *(incoming and outgoing)* between **BSL Language Server** and **Language Client** from used editor/IDE, this parameter sets log file path. The path can set either absolute or relative *(from project root)*, by default the value is not set.

**WARNING**

* When starting **BSL Language Server** overwrites this file
* Speed of interaction between client and server **DRAMATICALLY REDUCED**| -|`configurationRoot`|`String`|This parameter is intended to indicate the root directory the 1C configuration files are located in the project directory. It can be useful if there are several configuration directories in the same project directory or when the structure of the project directory is so complex. By default, the parameter is empty and `BSL Language Server` determines the location of the configuration root directory independently| +| Name | Type | Description | +|:---------------------------------------------------------------|:--------------------------:|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `language` | `String` | Set the language for displaying diagnosed comments. Supported languages:
* `ru` - for Russian (*default*)
* `en` - for English | +| `codeLens` | `JSON-Object` | Contains settings for displaying `lenses` in advanced code/IDEs *(eg [Visual Studio Code](https://code.visualstudio.com/))*, which displays various information above the code block. | +| ⤷   `parameters` | `JSON-Object` | Collection of lens settings. Collection items are json-objects with the following structure:
* *object key* - string, is lens key
* *object value* - if is boolean, then interpreted as lens off-switch (`false`) or on-switch with default parameters (`true`), if is type `json-object`, collection of lens parameters. | +|    ⤷   `cognitiveComplexity` | `Boolean` or `JSON-Object` | Enables displaying the value of the [cognitive complexity](../diagnostics/CognitiveComplexity.md) of the method over its definition. The default is ` true `. Lens options: `complexityThreshold` - lens response threshold. The default is - `-1`. | +|    ⤷   `cyclomaticComplexity` | `Boolean` or `JSON-Object` | Enables displaying the value of the [cyclomatic complexity](../diagnostics/CyclomaticComplexity.md) of the method over its definition. The default is `true`. Lens options: `complexityThreshold` - lens response threshold. The default is - `-1`. | +| `diagnostics` | `JSON-Object` | Contains diagnostic settings | +| ⤷   `computeTrigger` | `String` | Event that will trigger the code analysis procedure to diagnose comments. Possible values:
* `onType` -when editing a file (online) ***on large files can significantly slow down editing ***
* `onSave` - when saving a file (*default*)
`never` - analysis will not be performed | +| ⤷   `ordinaryAppSupport` | `Boolean` | Ordinary client support. Diagnostics will require taking into account the features of a ordinary application. Values:
* `true` - the configuration uses ordinary application *(default)*
* `false` - ignore ordinary application warnings | +| ⤷   `skipSupport` | `String` | This parameter sets **1C configuration** file skipping mode *(for example files are not analyzed for issues)* which are "on support" from vendor configuration. Possible values:
* `withSupport` - skip all modules set "on support" *(all "locks" types)*
* `withSupportLocked` - skip modules set "on support" with prohibited modification *("yellow closed lock")*
* `never` - skip no modules as support mode is not analyzed *(set by default)* | +| ⤷   `mode` | `String` | Setting for controlling the diagnostic settings accounting mode. Possible options:
* `OFF` - All diagnostics are considered to be turned off, regardless of their settings.
* `ON` - All diagnostics enabled by default are considered enabled, the rest - depending on personal settings
* `EXCEPT` - All diagnostics other than those specified are considered enabled.
* `ONLY` - Only the specified diagnostics are considered enabled.
* `ALL` - All diagnostics are considered enabled | +| ⤷   `parameters` | `JSON-Object` | Parameter is a collection of diagnostics parameters. Collection items are json-objects with the following structure:
* *object key* - string, is diagnostic key
* *object value* - if is boolean, then interpreted as diagnostic off-switch (`false`) or on-switch with default parameters (`true`), if is type `json-object`, collection of diagnostic parameters.

Key, if set to ON by default and all allowed parameters and examples are given on the diagnostic page. | +| ⤷   `subsystemsFilter` | `JSON-Object` | Filter by configuration subsystems | +| ⤷   `analyzeOnStart` | `Boolean` | Starting the analysis of the entire project at server startup. If enabled, after the context is built on the client, information about diagnostics in all project files will be sent. | +|    ⤷   `include` | `Array` `String` | List of names of subsystems for which objects the analysis is performed, including child subsystems | +|    ⤷   `exclude` | `Array` `String` | List of names of subsystems excluded from analysis, including child subsystems | +| `documentLink` | `JSON-Object` | Contains documentation link settings | +| ⤷   `showDiagnosticDescription` | `Boolean` | Show additional links to diagnostics documentation. By default, the parameter is off (*set to `false`*) | +| `inlayHint` | `JSON-Object` | ontains settings for displaying `inlay hints` in advanced code editors/IDEs *(for example [Visual Studio Code](https://code.visualstudio.com/))*, which displays various information directly in the code line. | +| ⤷   `parameters` | `JSON-Object` | A collection of inlay hints settings. The elements of the collection are json objects of the following structure:*
*object key* - a string that is an identifier of inlay hint*
*object value* - can take either a boolean value, and then it is interpreted as disabling inlay hint (`false`) or enabling them with parameters by default (`true`), or a value of type `json-object`, which is a set of inlay hint settings. | +|    ⤷   `cognitiveComplexity` | `Boolean` or `JSON-Object` | Enables displaying the value of the [Cognitive Complexity](../diagnostics/CognitiveComplexity.md) method as inlay hints. By default, the setting is set to `true`. | +|    ⤷   `cyclomaticComplexity` | `Boolean` or `JSON-Object` | Enables displaying the value of the [Cyclomatic Complexity](../diagnostics/CyclomaticComplexity.md) method as inlay hints. By default, the setting is set to `true`. | +|    ⤷   `sourceDefinedMethodCall` | `Boolean` or `JSON-Object` | Enables displaying the parameters of the invoked configuration/library method as inlay hints. By default, the setting is set to `true`. Available parameters:
* `showParametersWithTheSameName` - show parameters with names contained in the passed value. The default parameter value is `false`.
* `showDefaultValues` - show default values for parameters not passed. The default value of the parameter is `true`. | +| `useDevSite` | `Boolean` | When you turn on the settings, the resulting documentation links will lead to the develop version of the site. By default, the parameter is off (*set to `false`*) | +| `siteRoot` | `String` | The path to the root of the site with the documentation. By default, the parameter value is `"https://1c-syntax.github.io/bsl-language-server"` | +| `traceLog` | `String` | To log all requests *(incoming and outgoing)* between **BSL Language Server** and **Language Client** from used editor/IDE, this parameter sets log file path. The path can set either absolute or relative *(from project root)*, by default the value is not set.

**WARNING**

* When starting **BSL Language Server** overwrites this file
* Speed of interaction between client and server **DRAMATICALLY REDUCED** | +| `configurationRoot` | `String` | This parameter is intended to indicate the root directory the 1C configuration files are located in the project directory. It can be useful if there are several configuration directories in the same project directory or when the structure of the project directory is so complex. By default, the parameter is empty and `BSL Language Server` determines the location of the configuration root directory independently | +| `sendErrors` | `String` | Mode for sending error messages to BSL Language Server developers. More [Monitoring](Monitoring.md).Possible values:
* `ask` - ask permission on every error *(set by default)*.
* `send` - always send error messages.
* `never` - never send error messages. | You can use the following JSON schema to make it easier to compile and edit a configuration file: @@ -38,9 +48,12 @@ https://1c-syntax.github.io/bsl-language-server/configuration/schema.json Setting example: * Language of diagnostics messages - English; -* Changes the diagnostic setting for [LineLength - Line Length limit](../diagnostics/LineLength.md), set the limit for the length of a string to 140 characters; +* Changes the diagnostic setting [LineLength - Line length limit](../diagnostics/LineLength.md) by setting + line length limit of 140 characters; * Disable [MethodSize - Method size restriction diagnostic](../diagnostics/MethodSize.md). * Enables the calculation of diagnostics in continuous mode (`computeTrigger = onType`) +* Diagnostics are calculated only for the objects of the "StandardSubsystems" subsystem, with the exception of "ReportVariants" and " + ObjectVersioning" ```json { @@ -53,6 +66,15 @@ Setting example: "maxLineLength": 140 }, "MethodSize": false + }, + "subsystemsFilter": { + "include": [ + "StandardSubsystems" + ], + "exclude": [ + "ReportVariants", + "ObjectVersioning" + ] } } } diff --git a/docs/en/features/Monitoring.md b/docs/en/features/Monitoring.md new file mode 100644 index 00000000000..2bae2d04372 --- /dev/null +++ b/docs/en/features/Monitoring.md @@ -0,0 +1,280 @@ +# Monitoring and reporting errors + +BSL Language Server contains a mechanism for sending error data to Sentry. + +The public Sentry.io is used as the Sentry server at https://sentry.io/organizations/1c-syntax/projects/bsl-language-server + +Unfortunately, the peculiarities of configuring access to Sentry.io limit the ability to view data +unauthorized users. + +## Scheme + +In the [configuration file](ConfigurationFile.md) of the BSL Language Server, you can configure the mode for sending error messages. +The send mode can take one of three values: + +* ask (default); +* send always; +* never send. + +If the configuration file is missing a setting or has a value of "ask", when an error occurs +the connected language client (used by the IDE) is sent a question about further actions with an error +with the following answer options: + +* send this error but ask again; +* don't send this error but ask again. +* send this error and don't ask again; +* don't send this error and don't ask again; + +You can completely refuse to answer (for example, by clicking on the cross next to the notification with the question). +Lack of response is perceived as "don't send this error, but ask again". + +The error message does not contain user or workstation identification information, +except for the generated session UUID to bind errors that occur within one +launching BSL Language Server. + +> Attention! + +If you enable debug logging (by setting `logback` or using environment variables), the contents of the logs (the last 100 entries) will be attached to the event that is sent. + +Some messages sent between Language Client and BSL Language Server contain source code snippets +or the entire text of the file. +These fragments can also be attached to the sent message. + +Sending message example: + +??? event.json + + ```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 + }, + { + "function": "lambda$prepareCallHierarchy$8", + "module": "com.github._1c_syntax.bsl.languageserver.BSLTextDocumentService", + "filename": "BSLTextDocumentService.java", + "abs_path": "BSLTextDocumentService.java", + "lineno": 234, + "in_app": true + }, + { + "function": "prepareCallHierarchy", + "module": "com.github._1c_syntax.bsl.languageserver.providers.CallHierarchyProvider", + "filename": "CallHierarchyProvider.java", + "abs_path": "CallHierarchyProvider.java", + "lineno": 62, + "in_app": true + } + ] + }, + "thread_id": 24 + }, + { + "type": "CompletionException", + "value": "java.lang.RuntimeException: psss", + "module": "java.util.concurrent", + "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 + }, + { + "function": "completeThrowable", + "module": "java.util.concurrent.CompletableFuture", + "in_app": false + }, + { + "function": "encodeThrowable", + "module": "java.util.concurrent.CompletableFuture", + "in_app": false + } + ] + }, + "thread_id": 24 + } + ] + }, + "extra": { + "thread_name": "ForkJoinPool.commonPool-worker-19" + }, + "fingerprint": [ + "{{ default }}" + ], + "grouping_config": { + "enhancements": "eJybzDRxY3J-bm5-npWRgaGlroGxrpHxBABcYgcZ", + "id": "newstyle:2019-10-29" + }, + "hashes": [ + "4a63b2a190b48dc2bbafb225c5140009", + "cfeccf65e86c6129d81e7fd1df568ce3" + ], + "ingest_path": [ + { + "version": "22.6.0", + "public_key": "XE7QiyuNlja9PZ7I9qJlwQotzecWrUIN91BAO7Q5R38" + } + ], + "key_id": "1646438", + "level": "error", + "logentry": { + "formatted": "Internal error: java.lang.RuntimeException: psss" + }, + "logger": "org.eclipse.lsp4j.jsonrpc.RemoteEndpoint", + "metadata": { + "display_title_with_tree_label": false, + "function": "encodeThrowable", + "type": "CompletionException", + "value": "java.lang.RuntimeException: psss" + }, + "nodestore_insert": 1657796884.036383, + "received": 1657796882.652077, + "sdk": { + "name": "sentry.java.spring-boot", + "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" + } + ] + }, + "timestamp": 1657796877.875, + "title": "CompletionException: java.lang.RuntimeException: psss", + "type": "error", + "user": { + "id": "49516eb9-2a0d-4a15-bd96-978b68d8d0df" + }, + "version": "7", + "location": null + } + ``` \ No newline at end of file diff --git a/docs/en/features/index.md b/docs/en/features/index.md index 5a4591b3ae1..8111df669e6 100644 --- a/docs/en/features/index.md +++ b/docs/en/features/index.md @@ -4,3 +4,4 @@ Additional features BSL Language Server * [Configuration](ConfigurationFile.md) * [Diagnostic ignorance](DiagnosticIgnorance.md) +* [Monitoring](Monitoring.md) diff --git a/docs/en/index.md b/docs/en/index.md index bddae9cae38..2607e338947 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -2,13 +2,12 @@ [![Actions Status](https://github.com/1c-syntax/bsl-language-server/workflows/Java%20CI/badge.svg)](https://github.com/1c-syntax/bsl-language-server/actions) [![Download](https://img.shields.io/github/release/1c-syntax/bsl-language-server.svg?label=download&style=flat)](https://github.com/1c-syntax/bsl-language-server/releases/latest) -[![JitPack](https://jitpack.io/v/1c-syntax/bsl-language-server.svg)](https://jitpack.io/#1c-syntax/bsl-language-server) +[![Latest release](https://badgen.net/github/release/1c-syntax/bsl-language-server)](https://github.com/1c-syntax/bsl-language-server/releases) [![GitHub Releases](https://img.shields.io/github/downloads/1c-syntax/bsl-language-server/latest/total?style=flat-square)](https://github.com/1c-syntax/bsl-language-server/releases) [![GitHub All Releases](https://img.shields.io/github/downloads/1c-syntax/bsl-language-server/total?style=flat-square)](https://github.com/1c-syntax/bsl-language-server/releases) [![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=alert_status)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) [![Maintainability](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=coverage)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) -[![Qodana](https://github.com/1c-syntax/bsl-language-server/actions/workflows/qodana.yml/badge.svg)](https://1c-syntax.github.io/bsl-language-server/qodana) [![Transifex](https://img.shields.io/badge/translation-transifex-green)](https://www.transifex.com/1c-syntax/bsl-language-server) [![Benchmark](bench/benchmark.svg)](bench/index.html) [![telegram](https://img.shields.io/badge/telegram-chat-green.svg)](https://t.me/bsl_language_server) @@ -18,6 +17,7 @@ * [Contributing guidelines](contributing/index.md) * Capabilities * Run from command line +* Run in websocket mode * Run in analyzer mode * Run in formatter mode * Configuration file @@ -32,7 +32,7 @@ Perfomance measurement - [SSL 3.1](../bench/index.html) -## Capabilities +## Features * File formatting * Selected region formatting @@ -46,23 +46,23 @@ Perfomance measurement - [SSL 3.1](../bench/index.html) * Expand selection * Display color representation and convert between `Color` and `WebColors` * Diagnostics -* Quick fixes for several diagnostics +* Quick fixes and code actions for several diagnostics * Run diagnostics engine from command line * Run formatter engine from command line -* Rename symbol +* Renaming Symbols ## Supported protocol operations ??? workspace -| Operation | Supported | Comment | -| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [didChangeWorkspaceFolders](https://microsoft.github.io/language-server-protocol/specification-current#workspace_didChangeWorkspaceFolders) | no | | -| [didChangeConfiguration](https://microsoft.github.io/language-server-protocol/specification#workspace_didChangeConfiguration) | yes | with restrictions, see [#1431](https://github.com/1c-syntax/bsl-language-server/issues/1431) | -| [didChangeWatchedFiles](https://microsoft.github.io/language-server-protocol/specification#workspace_didChangeWatchedFiles) | no | | -| [symbol](https://microsoft.github.io/language-server-protocol/specification#workspace_symbol) | yes | | -| [executeCommand](https://microsoft.github.io/language-server-protocol/specification#workspace_executeCommand) | no | | -| [applyEdit](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_applyEdit) | no | | -| [willCreateFiles](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_willCreateFiles) | no | | +    | Operation                                                     | Support                                                    | Commentary                                                  | +    | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +    | [didChangeWorkspaceFolders](https://microsoft.github.io/language-server-protocol/specification-current#workspace_didChangeWorkspaceFolders) | no   |                                                              | +    | [didChangeConfiguration](https://microsoft.github.io/language-server-protocol/specification#workspace_didChangeConfiguration) | yes | with restrictions see [#1431](https://github.com/1c-syntax/bsl-language-server/issues/1431) | +    | [didChangeWatchedFiles](https://microsoft.github.io/language-server-protocol/specification#workspace_didChangeWatchedFiles) | no   |                                                              | +    | [symbol](https://microsoft.github.io/language-server-protocol/specification#workspace_symbol) | yes |                                                              | +    | [executeCommand](https://microsoft.github.io/language-server-protocol/specification#workspace_executeCommand) | yes |                                                              | +    | [applyEdit](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_applyEdit) | no   |                                                              | +    | [willCreateFiles](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_willCreateFiles) |   no  |                                                              | ??? "Text Synchronization" | Opertaion | Supported | Comment | @@ -75,42 +75,45 @@ Perfomance measurement - [SSL 3.1](../bench/index.html) | [willSaveWaitUntil](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_willSaveWaitUntil) | no | | | ??? textDocument -| Operation | Supported | Comment | Configurable? | -| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ---------------- | -| [publishDiagnostics](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_publishDiagnostics) | yes | tagSupport = true
versionSupport = true
[список диагностик](./diagnostics/index.md) | yes | -| [completion](https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/diagnostics/index.md) | no | resolveProvider = false | | -| [completionItem/resolve](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#completionItem_resolve) | no | | | -| [hover](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover) | yes | contentFormat = MarkupContent | | -| [signatureHelp](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp) | no | | | -| [declaration](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_declaration) | no | not applicable in 1C:Enterprise | | -| [definition](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_definition) | yes | linkSupport = true | | -| [typeDefinition](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_typeDefinition) | no | | | -| [implementation](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_implementation) | no | not applicable in 1C:Enterprise | | -| [references](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references) | yes | | | -| [documentHighlight](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentHighlight) | no | | | -| [documentSymbol](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentSymbol) | yes | hierarchicalDocumentSymbolSupport = true | | -| [codeAction](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction) | yes | codeActionKinds = ? (see [#1433](https://github.com/1c-syntax/bsl-language-server/issues/1433))
isPreferredSupport = true | yes | -| [codeAction/resolve](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#codeAction_resolve) | no | | | -| [codeLens](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeLens) | yes | resolveProvider = false | да | -| [codeLens/resolve](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#codeLens_resolve) | no | | | -| [codeLens/refresh](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#codeLens_refresh) | no | | | -| [documentLink](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentLink) | yes | Displaying hyperlinks to diagnostics documentation.
tooltipSupport = true
resolveProvider = false | yes | -| [documentLink/resolve](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#documentLink_resolve) | no | | | -| [documentColor](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentColor) | yes | | | -| [colorPresentation](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_colorPresentation) | yes | | | -| [formatting](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting) | yes | | | -| [rangeFormatting](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_rangeFormatting) | yes | | | -| [onTypeFormatting](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_onTypeFormatting) | no | | | -| [rename](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_rename) | yes | | | -| [prepareRename](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_prepareRename) | yes | | | -| [foldingRange](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_foldingRange) | yes | | | -| [selectionRange](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_selectionRange) | yes | | | -| [prepareCallHierarchy](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_prepareCallHierarchy) | yes | | | -| [callHierarchy/incomingCalls](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#callHierarchy_incomingCalls) | yes | | | -| [callHierarchy/outgoingCalls](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#callHierarchy_outgoingCalls) | yes | | | -| [semanticTokens](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_semanticTokens) | no | | | -| [linkedEditingRange](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_linkedEditingRange) | no | | | -| [moniker](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_moniker) | no | | | + | Operation | Support | Commentary | Is configured? | + | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ---------------- | + | [publishDiagnostics](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_publishDiagnostics) | yes | tagSupport = true
versionSupport = true
[diagnostics](./diagnostics/index.md) | yes | + | [completion](https://github.com/1c-syntax/bsl-language-server/blob/develop/docs/diagnostics/index.md) | no | resolveProvider = false | | + | [completionItem/resolve](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#completionItem_resolve) | no | | | + | [hover](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_hover) | yes | contentFormat = MarkupContent | | + | [signatureHelp](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_signatureHelp) | no | | | + | [declaration](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_declaration) | no | not applicable in 1C:Enterprise | | + | [definition](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_definition) | yes | linkSupport = true | | + | [typeDefinition](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_typeDefinition) | no | | | + | [implementation](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_implementation) | no | not applicable in 1C:Enterprise | | + | [references](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references) | yes | | | + | [documentHighlight](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentHighlight) | no | | | + | [documentSymbol](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentSymbol) | yes | hierarchicalDocumentSymbolSupport = true | | + | [codeAction](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction) | yes | codeActionKinds = ? (см. [#1433](https://github.com/1c-syntax/bsl-language-server/issues/1433))
isPreferredSupport = true | yes | + | [codeAction/resolve](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#codeAction_resolve) | no | | | + | [codeLens](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeLens) | yes | resolveProvider = false | yes | + | [codeLens/resolve](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#codeLens_resolve) | yes | | | + | [codeLens/refresh](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#codeLens_refresh) | yes | | | + | [documentLink](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentLink) | yes | Showing hyperlinks to documentation on diagnostics.
tooltipSupport = true
resolveProvider = false | yes | + | [documentLink/resolve](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#documentLink_resolve) | no | | | + | [documentColor](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentColor) | yes | | | + | [colorPresentation](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_colorPresentation) | yes | | | + | [formatting](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting) | yes | | | + | [rangeFormatting](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_rangeFormatting) | yes | | | + | [onTypeFormatting](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_onTypeFormatting) | no | | | + | [rename](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_rename) | yes | | | + | [prepareRename](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_prepareRename) | yes | | | + | [foldingRange](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_foldingRange) | yes | | | + | [selectionRange](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_selectionRange) | yes | | | + | [prepareCallHierarchy](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_prepareCallHierarchy) | yes | | | + | [callHierarchy/incomingCalls](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#callHierarchy_incomingCalls) | yes | | | + | [callHierarchy/outgoingCalls](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#callHierarchy_outgoingCalls) | yes | | | + | [semanticTokens](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_semanticTokens) | no | | | + | [linkedEditingRange](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_linkedEditingRange) | no | | | + | [moniker](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_moniker) | no | | | + | [inlayHint](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_inlayHint) | yes | resolveProvider = false | yes | + | [inlayHint/resolve](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#inlayHint_resolve) | no | | | + | [inlayHint/refresh](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#workspace_inlayHint_refresh) | yes | | | @@ -127,16 +130,60 @@ Usage: bsl-language-server [-h] [-c=] [COMMAND [ARGS]] Path to language server configuration file -h, --help Show this help message and exit Commands: - analyze, -a, --analyze Run analysis and get diagnostic info - format, -f, --format Format files in source directory - version, -v, --version Print version - lsp, --lsp LSP server mode (default) + analyze, -a, --analyze Run analysis and get diagnostic info + format, -f, --format Format files in source directory + version, -v, --version Print version + lsp, --lsp LSP server mode (default) + websocket, -w, --websocket Websocket server mode ``` Starting BSL Language Server in standard mode will run the Language Server communicating via [LSP]([language server protocol](https://microsoft.github.io/language-server-protocol/)). stdin and stdout are used for communication. By default diagnostics texts are displayed in Russian. To switch the diagnostics text language you need to set parameter `language` in configuration file or raise an event `workspace/didChangeConfiguration`: +```json +{ + "language": "en" +} +``` + + + +## Run in websocket mode + +By default, interaction with the server goes through standard input / output streams. +But you can run BSL Language Server with a built-in web server and interact with it via websocket. + +To do this, start the BSL Language Server with the `--websocket` or `-w` option: + +```sh +Usage: bsl-language-server websocket [-h] [--app.websocket.lsp-path=] + [-c=] [--server.port=] +Websocket server mode + --app.websocket.lsp-path= + Path to LSP endpoint. Default is /lsp + -c, --configuration= Path to language server configuration file + -h, --help Show this help message and exit + --server.port= Port to listen. Default is 8025 +``` + +Once started, BSL Language Server will be available at `ws://localhost:8025/lsp`. + +To redefine the port to the LSP server, you must use the `--server.port` option and the port number. +To redefine the path to the LSP server, you must use the `--app.websocket.lsp-path` option and a path starting with `/`. + +An example of running BSL Language Server in websocket mode with port 8080: + +```sh +java -jar bsl-language-server.jar --websocket --server.port=8080 +``` + +> For large projects, it is recommended to specify the -Xmx parameter, which is responsible for the RAM limit for the java process. The amount of allocated memory depends on the size of the analyzed codebase. + +```sh +java -Xmx4g -jar bsl-language-server.jar ... other parameters +``` + ## Run in analyzer mode diff --git a/docs/en/reporters/code-quality.md b/docs/en/reporters/code-quality.md new file mode 100644 index 00000000000..c3fa156439e --- /dev/null +++ b/docs/en/reporters/code-quality.md @@ -0,0 +1,7 @@ +# CodeQuality reporter + +Reporter option - `code-quality` + +## Description + +Output the analysis results into file `bsl-code-quality.json` in the current workspace directory. Output format is described in GitLab documentation, section [Code Quality](https://docs.gitlab.com/ci/testing/code_quality/#code-quality-report-format) diff --git a/docs/en/reporters/index.md b/docs/en/reporters/index.md index 74b41ce4550..cdb1ee43dda 100644 --- a/docs/en/reporters/index.md +++ b/docs/en/reporters/index.md @@ -9,4 +9,5 @@ Used to get analysis results. * [junit](junit.md); * [tslint](tslint.md); * [sarif](sarif.md); +* [code-quality](code-quality.md); * [console](console.md). diff --git a/docs/en/systemRequirements.md b/docs/en/systemRequirements.md index 0bba7dd7804..b03a960afb4 100644 --- a/docs/en/systemRequirements.md +++ b/docs/en/systemRequirements.md @@ -6,7 +6,7 @@ Using `BSL Language Server` has some limitations, listed bellow `BSL Language Server` is a console Java application and requires the presence of a Java virtual machine on the computer. -The minimum supported version is Java 11, but as part of the build pipelines, a health check is performed when using more recent versions. Java versions 11 and 17 are currently supported. +The minimum supported version is Java 17, but as part of the build pipelines, a health check is performed when using more recent versions. Java versions 17, 21 and 23 are currently supported. JDK vendor is also interesting. Due to the changed licensing policy of Oracle, it is recommended to use open implementations of the `OpenJDK` virtual machine: AdoptOpenJDK, Liberica JDK. @@ -14,6 +14,6 @@ JDK vendor is also interesting. Due to the changed licensing policy of Oracle, i `BSL Language Server` should work on all systems running modern desktop and server operating systems which supported Java. The most popular environments are tested as part of the build pipelines: -- Windows 7/10, Windows server 2012 and higher supported +- Windows 7/10/11, Windows server 2012 and higher supported - latest Linux OS supported. - latest MacOS supported diff --git a/docs/features/ConfigurationFile.md b/docs/features/ConfigurationFile.md index f7cb3ba6d6c..5d53f61fb81 100644 --- a/docs/features/ConfigurationFile.md +++ b/docs/features/ConfigurationFile.md @@ -1,36 +1,45 @@ # Конфигурирование BSL Language Server -BSL Language Server предоставляет возможность изменения настроек, заложенных разработчиками, с помощью конфигурационного файла в формате json. -Созданный файл необходимо указать с помощью ключа `--configuration ` *(или кратко `-c`)* при запуске BSL Language Server в качестве консольного приложения либо, если же используется редактор/IDE с плагином-клиентом BSL Language Server, разместить его в соответствии с документацией *(обычно это корень проекта либо рабочей области)*. +BSL Language Server предоставляет возможность изменения настроек, заложенных разработчиками, с помощью конфигурационного +файла в формате json. +Созданный файл необходимо указать с помощью ключа `--configuration ` *(или кратко `-c`)* при запуске BSL Language Server +в качестве консольного приложения либо, если же используется редактор/IDE с плагином-клиентом BSL Language Server, +разместить его в соответствии с документацией *(обычно это корень проекта либо рабочей области)*. -В случае отсутствия конфигурационного файла будет предпринята попытка найти файл ".bsl-language-server.json" в "%HOMEPATH%" +В случае отсутствия конфигурационного файла будет предпринята попытка найти файл ".bsl-language-server.json" в " +%HOMEPATH%" ## Описание настроек -|Наименование|Тип|Описание| -|:--|:-:|:--| -|`language`|`Строка`|Этот параметр устанавливает язык отображения диагностированных замечаний. На данный момент поддерживаются два языка:
* `ru` - для русского языка (*используется по умолчанию*)
* `en` - для английского языка| -|`codeLens`|`JSON-Объект`|Содержит настройки отображения `линз` в продвинутых кода/IDE *(например [Visual Studio Code](https://code.visualstudio.com/))*, в которых выводится различная информация над блоком кода. Свойства объекта| -|⤷   `parameters`|`JSON-Объект`|Коллекция настроек линз. Элементами коллекции являются json-объекты следующей структуры:
* *ключ объекта* - строка, являющаяся идентификатором линзы
* *значение объекта* - может принимать либо булево значение, и тогда интерпретируется как отключение линзы (`false`) или ее включение с параметрами по умолчанию (`true`), либо значение типа `json-объект`, представляющего собой набор настроек линзы.| -|   ⤷   `cognitiveComplexity`|`Булево` или `JSON-Объект`|Включает отображение значения [когнитивной сложности](../diagnostics/CognitiveComplexity.md) метода над его определением. По умолчанию настройка установлена в `true`. Доступные параметры линзы: `complexityThreshold` - порог, после которого линза начинает срабатывать. Значение параметра по умолчанию - `-1`.| -|   ⤷   `cyclomaticComplexity`|`Булево` или `JSON-Объект`|Включает отображение значения [цикломатической сложности](../diagnostics/CyclomaticComplexity.md) метода. По умолчанию настройка установлена в `true`. Доступные параметры линзы: `complexityThreshold` - порог, после которого линза начинает срабатывать. Значение параметра по умолчанию - `-1`.| -|`diagnostics`|`JSON-Объект`|Содержит настройки диагностик| -|⤷   `computeTrigger`|`Строка`|С помощью этого параметра можно указать событие, при котором будет вызвана процедура анализа кода для диагностирования замечаний. Возможные значения:
* `onType` - при редактировании файла (онлайн) ***на больших файлах может ЗНАЧИТЕЛЬНО замедлять редактирование***
* `onSave` - при сохранении файла (*используется по умолчанию*)
* `never` - анализ выполняться не будет| -|⤷   `ordinaryAppSupport`|`Булево`|Поддержка обычного клиента. Диагностики будут требовать учитывать особенности обычного приложения. Возможные значения:
* `true` - конфигурация разрабатывается с поддержкой обычного клиента *(установлен по умолчанию)*
* `false` - игнорировать предупреждения связанные с особенностями обычного клиента| -|⤷   `skipSupport`|`Строка`|Этим параметром настраивается режим пропуска файлов *(т.е. файлы не анализируются на предмет наличия замечаний)* **конфигурации 1С**, находящихся "на поддержке" конфигурации поставщика. Возможные значения:
* `withSupport` - пропускаются все модули, находящиеся "на поддержке" *(все виды "замков")*
* `withSupportLocked` - пропускаются только модули, находящиеся "на поддержке" с запретом изменений *("желтый закрытый замок")*
* `never` - режим поддержки не анализируется и модули не пропускаются *(установлен по умолчанию)*| -|⤷   `mode`|`Строка`|Настройка для управления режимом учета настроек диагностик. Возможные варианты:
* `OFF` - Все диагностики считаются выключенными, вне зависимости от их настроек
* `ON` - Все диагностики включенные по умолчанию считаются включенными, остальные - в зависимости от личных настроек
* `EXCEPT` - Все диагностистики, кроме указанных, считаются включенными
* `ONLY` - Только указанные диагностики считаются включенными
* `ALL` - Все диагностики считаются включенными| -|⤷   `parameters`|`JSON-Объект`|Параметр представляет собой коллекцию настроек диагностик. Элементами коллекции являются json-объекты следующей структуры:
* *ключ объекта* - строка, являющаяся ключом диагностики
* *значение объекта* - может принимать либо булево значение, и тогда интерпретируется как отключение диагностики (`false`) или ее включение с параметрами по умолчанию (`true`), либо значение типа `json-объект`, представляющего собой набор настроек диагностики.

Ключ, включена ли по умолчанию, а также описание возможных параметров и примеры для конфигурационного файла представлены на странице с описанием каждой диагностики.| -|⤷   `subsystemsFilter`|`JSON-Объект`|Фильтр по подсистемам конфигурации| -|⤷   `analyzeOnStart`|`Булево`|Запустить анализ всего проекта при запуске сервера. Если включено, после построения контекста на клиента будет отправлена информация о диагностиках во всех файлах проекта.| -|   ⤷   `include`|`Массив` `Строка`|Список имен подсистем по объектам которых выполняется анализ, включая подчиненные подсистемы| -|   ⤷   `exclude`|`Массив` `Строка`|Список имен подсистем исключенных из анализа, включая подчиненные подсистемы| -|`documentLink`|`JSON-Объект`|Содержит настройки ссылок на документацию| -|⤷   `showDiagnosticDescription`|`Булево`|Показывать дополнительные ссылки на документацию по диагностикам. По умолчанию параметр выключен (*установлен в `false`*)| -|`useDevSite`|`Булево`|При включении настройки формирующиеся ссылки на документацию будут вести на develop-версию сайта. По умолчанию параметр выключен (*установлен в `false`*)| -|`siteRoot`|`Строка`|Путь к корню сайта с документацией. По умолчанию параметр имеет значение `"https://1c-syntax.github.io/bsl-language-server"` | -|`traceLog`|`Строка`|Для логирования всех запросов *(входящих и исходящих)* между **BSL Language Server** и **Language Client** из используемого редактора/IDE, в этом параметре можно указать путь к файлу лога. Путь можно указывать как абсолютный, так и относительный *(от корня анализируемого проекта)*, по умолчанию значение не заполнено.

**ВНИМАНИЕ**

* При запуске **BSL Language Server** перезаписывает указанный файл
* Скорость взаимодействия между клиентом и сервером **ЗНАЧИТЕЛЬНО ЗАМЕДЛЯЕТСЯ**| -|`configurationRoot`|`Строка`|Данный параметр предназначен для указания корневого каталога, в котором находятся файлы конфигурации 1С в каталоге проекта. Может быть полезен в случае нахождения нескольких каталогов конфигураций в одном каталоге проекта либо при сложной структуре каталога проекта. По умолчанию параметр не заполнен и `BSL Language Server` самостоятельно определяет расположение корневого каталога конфигурации| -|`sendErrors`|`Строка`|Режим отправки сообщений об ошибках разработчикам BSL Language Server. Подробнее - на странице [Мониторинг и отправка ошибок](Monitoring.md). Возможные значения:
* `ask` - спрашивать разрешение при каждой ошибке *(установлен по умолчанию)*.
* `send` - всегда отправлять сообщения об ошибках.
* `never` - никогда не отправлять сообщения об ошибках.| +| Наименование | Тип | Описание | +|:---------------------------------------------------------------|:--------------------------:|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `language` | `Строка` | Этот параметр устанавливает язык отображения диагностированных замечаний. На данный момент поддерживаются два языка:
* `ru` - для русского языка (*используется по умолчанию*)
* `en` - для английского языка | +| `codeLens` | `JSON-Объект` | Содержит настройки отображения `линз` в продвинутых кода/IDE *(например [Visual Studio Code](https://code.visualstudio.com/))*, в которых выводится различная информация над блоком кода. | +| ⤷   `parameters` | `JSON-Объект` | Коллекция настроек линз. Элементами коллекции являются json-объекты следующей структуры:
* *ключ объекта* - строка, являющаяся идентификатором линзы
* *значение объекта* - может принимать либо булево значение, и тогда интерпретируется как отключение линзы (`false`) или ее включение с параметрами по умолчанию (`true`), либо значение типа `json-объект`, представляющего собой набор настроек линзы. | +|    ⤷   `cognitiveComplexity` | `Булево` или `JSON-Объект` | Включает отображение значения [когнитивной сложности](../diagnostics/CognitiveComplexity.md) метода над его определением. По умолчанию настройка установлена в `true`. Доступные параметры линзы: `complexityThreshold` - порог, после которого линза начинает срабатывать. Значение параметра по умолчанию - `-1`. | +|    ⤷   `cyclomaticComplexity` | `Булево` или `JSON-Объект` | Включает отображение значения [цикломатической сложности](../diagnostics/CyclomaticComplexity.md) метода. По умолчанию настройка установлена в `true`. Доступные параметры линзы: `complexityThreshold` - порог, после которого линза начинает срабатывать. Значение параметра по умолчанию - `-1`. | +| `diagnostics` | `JSON-Объект` | Содержит настройки диагностик | +| ⤷   `computeTrigger` | `Строка` | С помощью этого параметра можно указать событие, при котором будет вызвана процедура анализа кода для диагностирования замечаний. Возможные значения:
* `onType` - при редактировании файла (онлайн) ***на больших файлах может ЗНАЧИТЕЛЬНО замедлять редактирование***
* `onSave` - при сохранении файла (*используется по умолчанию*)
* `never` - анализ выполняться не будет | +| ⤷   `ordinaryAppSupport` | `Булево` | Поддержка обычного клиента. Диагностики будут требовать учитывать особенности обычного приложения. Возможные значения:
* `true` - конфигурация разрабатывается с поддержкой обычного клиента *(установлен по умолчанию)*
* `false` - игнорировать предупреждения связанные с особенностями обычного клиента | +| ⤷   `skipSupport` | `Строка` | Этим параметром настраивается режим пропуска файлов *(т.е. файлы не анализируются на предмет наличия замечаний)* **конфигурации 1С**, находящихся "на поддержке" конфигурации поставщика. Возможные значения:
* `withSupport` - пропускаются все модули, находящиеся "на поддержке" *(все виды "замков")*
* `withSupportLocked` - пропускаются только модули, находящиеся "на поддержке" с запретом изменений *("желтый закрытый замок")*
* `never` - режим поддержки не анализируется и модули не пропускаются *(установлен по умолчанию)* | +| ⤷   `mode` | `Строка` | Настройка для управления режимом учета настроек диагностик. Возможные варианты:
* `OFF` - Все диагностики считаются выключенными, вне зависимости от их настроек
* `ON` - Все диагностики включенные по умолчанию считаются включенными, остальные - в зависимости от личных настроек
* `EXCEPT` - Все диагностистики, кроме указанных, считаются включенными
* `ONLY` - Только указанные диагностики считаются включенными
* `ALL` - Все диагностики считаются включенными | +| ⤷   `parameters` | `JSON-Объект` | Параметр представляет собой коллекцию настроек диагностик. Элементами коллекции являются json-объекты следующей структуры:
* *ключ объекта* - строка, являющаяся ключом диагностики
* *значение объекта* - может принимать либо булево значение, и тогда интерпретируется как отключение диагностики (`false`) или ее включение с параметрами по умолчанию (`true`), либо значение типа `json-объект`, представляющего собой набор настроек диагностики.

Ключ, включена ли по умолчанию, а также описание возможных параметров и примеры для конфигурационного файла представлены на странице с описанием каждой диагностики. | +| ⤷   `subsystemsFilter` | `JSON-Объект` | Фильтр по подсистемам конфигурации | +| ⤷   `analyzeOnStart` | `Булево` | Запустить анализ всего проекта при запуске сервера. Если включено, после построения контекста на клиента будет отправлена информация о диагностиках во всех файлах проекта. | +|    ⤷   `include` | `Массив` `Строка` | Список имен подсистем по объектам которых выполняется анализ, включая подчиненные подсистемы | +|    ⤷   `exclude` | `Массив` `Строка` | Список имен подсистем исключенных из анализа, включая подчиненные подсистемы | +| `documentLink` | `JSON-Объект` | Содержит настройки ссылок на документацию | +| ⤷   `showDiagnosticDescription` | `Булево` | Показывать дополнительные ссылки на документацию по диагностикам. По умолчанию параметр выключен (*установлен в `false`*) | +| `inlayHint` | `JSON-Объект` | Содержит настройки отображения `inlay hints` в продвинутых редакторах кода/IDE *(например [Visual Studio Code](https://code.visualstudio.com/))*, в которых выводится различная информация прямо в строке с кодом. | +| ⤷   `parameters` | `JSON-Объект` | Коллекция настроек inlay hints. Элементами коллекции являются json-объекты следующей структуры:
* *ключ объекта* - строка, являющаяся идентификатором inlay hint
* *значение объекта* - может принимать либо булево значение, и тогда интерпретируется как отключение inlay hint (`false`) или их включение с параметрами по умолчанию (`true`), либо значение типа `json-объект`, представляющего собой набор настроек inlay hint. | +|    ⤷   `cognitiveComplexity` | `Булево` или `JSON-Объект` | Включает отображение значения [когнитивной сложности](../diagnostics/CognitiveComplexity.md) метода в виде inlay hints. По умолчанию настройка установлена в `true`. | +|    ⤷   `cyclomaticComplexity` | `Булево` или `JSON-Объект` | Включает отображение значения [цикломатической сложности](../diagnostics/CyclomaticComplexity.md) метода в виде inlay hints. По умолчанию настройка установлена в `true`. | +|    ⤷   `sourceDefinedMethodCall` | `Булево` или `JSON-Объект` | Включает отображение параметров вызываемого метода конфигурации/библиотеки в виде inlay hints. По умолчанию настройка установлена в `true`. Доступные параметры:
* `showParametersWithTheSameName` - отображать параметры с именами, содержащимися в передаваемом значении. Значение параметра по умолчанию - `false`.
* `showDefaultValues` - отображать значения по умолчанию для непереданных параметров. Значение параметра по умолчанию - `true`. | +| `useDevSite` | `Булево` | При включении настройки формирующиеся ссылки на документацию будут вести на develop-версию сайта. По умолчанию параметр выключен (*установлен в `false`*) | +| `siteRoot` | `Строка` | Путь к корню сайта с документацией. По умолчанию параметр имеет значение `"https://1c-syntax.github.io/bsl-language-server"` | +| `traceLog` | `Строка` | Для логирования всех запросов *(входящих и исходящих)* между **BSL Language Server** и **Language Client** из используемого редактора/IDE, в этом параметре можно указать путь к файлу лога. Путь можно указывать как абсолютный, так и относительный *(от корня анализируемого проекта)*, по умолчанию значение не заполнено.

**ВНИМАНИЕ**

* При запуске **BSL Language Server** перезаписывает указанный файл
* Скорость взаимодействия между клиентом и сервером **ЗНАЧИТЕЛЬНО ЗАМЕДЛЯЕТСЯ** | +| `configurationRoot` | `Строка` | Данный параметр предназначен для указания корневого каталога, в котором находятся файлы конфигурации 1С в каталоге проекта. Может быть полезен в случае нахождения нескольких каталогов конфигураций в одном каталоге проекта либо при сложной структуре каталога проекта. По умолчанию параметр не заполнен и `BSL Language Server` самостоятельно определяет расположение корневого каталога конфигурации | +| `sendErrors` | `Строка` | Режим отправки сообщений об ошибках разработчикам BSL Language Server. Подробнее - на странице [Мониторинг и отправка ошибок](Monitoring.md). Возможные значения:
* `ask` - спрашивать разрешение при каждой ошибке *(установлен по умолчанию)*.
* `send` - всегда отправлять сообщения об ошибках.
* `never` - никогда не отправлять сообщения об ошибках. | Для облегчения составления и редактирования конфигурационного файла можно использовать следующую JSON-схему: @@ -43,10 +52,12 @@ https://1c-syntax.github.io/bsl-language-server/configuration/schema.json Ниже приведен пример настройки: * Устанавливает язык сообщений диагностик - английский; -* Изменяет настройку диагностики [LineLength - Ограничение на длину строки](../diagnostics/LineLength.md), устанавливая предел длины строки в 140 символов; +* Изменяет настройку диагностики [LineLength - Ограничение на длину строки](../diagnostics/LineLength.md), устанавливая + предел длины строки в 140 символов; * Отключает диагностику [MethodSize - Ограничение на размер метода](../diagnostics/MethodSize.md). * Включает расчет диагностик в непрерывном режиме (`computeTrigger = onType`) -* Диагностики рассчитываются только по объектам подсистемы "СтандартныеПодсистемы" за исключением "ВариантыОтчетов" и "ВерсионированиеОбъектов" +* Диагностики рассчитываются только по объектам подсистемы "СтандартныеПодсистемы" за исключением "ВариантыОтчетов" и " + ВерсионированиеОбъектов" ```json { @@ -61,8 +72,13 @@ https://1c-syntax.github.io/bsl-language-server/configuration/schema.json "MethodSize": false }, "subsystemsFilter": { - "include": ["СтандартныеПодсистемы"], - "exclude": ["ВариантыОтчетов", "ВерсионированиеОбъектов"] + "include": [ + "СтандартныеПодсистемы" + ], + "exclude": [ + "ВариантыОтчетов", + "ВерсионированиеОбъектов" + ] } } } diff --git a/docs/index.md b/docs/index.md index 82eff10f92a..6d74f53391c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -2,13 +2,12 @@ [![Actions Status](https://github.com/1c-syntax/bsl-language-server/workflows/Java%20CI/badge.svg)](https://github.com/1c-syntax/bsl-language-server/actions) [![Download](https://img.shields.io/github/release/1c-syntax/bsl-language-server.svg?label=download&style=flat)](https://github.com/1c-syntax/bsl-language-server/releases/latest) -[![JitPack](https://jitpack.io/v/1c-syntax/bsl-language-server.svg)](https://jitpack.io/#1c-syntax/bsl-language-server) +[![Latest release](https://badgen.net/github/release/1c-syntax/bsl-language-server)](https://github.com/1c-syntax/bsl-language-server/releases) [![GitHub Releases](https://img.shields.io/github/downloads/1c-syntax/bsl-language-server/latest/total?style=flat-square)](https://github.com/1c-syntax/bsl-language-server/releases) [![GitHub All Releases](https://img.shields.io/github/downloads/1c-syntax/bsl-language-server/total?style=flat-square)](https://github.com/1c-syntax/bsl-language-server/releases) [![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=alert_status)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) [![Maintainability](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=1c-syntax_bsl-language-server&metric=coverage)](https://sonarcloud.io/dashboard?id=1c-syntax_bsl-language-server) -[![Qodana](https://github.com/1c-syntax/bsl-language-server/actions/workflows/qodana.yml/badge.svg)](https://1c-syntax.github.io/bsl-language-server/qodana) [![Transifex](https://img.shields.io/badge/translation-transifex-green)](https://www.transifex.com/1c-syntax/bsl-language-server) [![Benchmark](bench/benchmark.svg)](bench/index.html) [![telegram](https://img.shields.io/badge/telegram-chat-green.svg)](https://t.me/bsl_language_server) @@ -61,7 +60,7 @@ | [didChangeConfiguration](https://microsoft.github.io/language-server-protocol/specification#workspace_didChangeConfiguration) | yes | с ограничениями, см. [#1431](https://github.com/1c-syntax/bsl-language-server/issues/1431) | | [didChangeWatchedFiles](https://microsoft.github.io/language-server-protocol/specification#workspace_didChangeWatchedFiles) | no | | | [symbol](https://microsoft.github.io/language-server-protocol/specification#workspace_symbol) | yes | | - | [executeCommand](https://microsoft.github.io/language-server-protocol/specification#workspace_executeCommand) | no | | + | [executeCommand](https://microsoft.github.io/language-server-protocol/specification#workspace_executeCommand) | yes | | | [applyEdit](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_applyEdit) | no | | | [willCreateFiles](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_willCreateFiles) | no | | @@ -112,6 +111,9 @@ | [semanticTokens](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_semanticTokens) | no | | | | [linkedEditingRange](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_linkedEditingRange) | no | | | | [moniker](https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_moniker) | no | | | + | [inlayHint](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_inlayHint) | yes | resolveProvider = false | да | + | [inlayHint/resolve](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#inlayHint_resolve) | no | | | + | [inlayHint/refresh](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#workspace_inlayHint_refresh) | yes | | | @@ -204,7 +206,7 @@ Run analysis and get diagnostic info ``` Для указания каталога расположения анализируемых исходников используется параметр `--srcDir` (сокращенно `-s`), за которым следует путь (относительный или абсолютный) к каталогу исходников. -Для формирования отчета об анализе требуется указать один или "репортеров". Для указания репортера используется параметр `--reporter` (сокращенно `-r`), за которым следует ключ репортера. Допустимо указывать несколько репортеров. Список репортетов см. в разделе **Репортеры**. +Для формирования отчета об анализе требуется указать один из "репортеров". Для указания репортера используется параметр `--reporter` (сокращенно `-r`), за которым следует ключ репортера. Допустимо указывать несколько репортеров. Список репортетов см. в разделе **Репортеры**. Пример строки запуска анализа: diff --git a/docs/reporters/code-quality.md b/docs/reporters/code-quality.md new file mode 100644 index 00000000000..9f6932d2c5a --- /dev/null +++ b/docs/reporters/code-quality.md @@ -0,0 +1,7 @@ +# CodeQuality reporter + +Ключ репортера - `code-quality` + +## Описание + +Выводит результаты анализа в файл `bsl-code-quality.json` в текущей рабочей директории. Формат вывода описан в документации GitLab, раздел [Code Quality](https://docs.gitlab.com/ci/testing/code_quality/#code-quality-report-format) diff --git a/docs/reporters/index.md b/docs/reporters/index.md index d47c679b936..529706db773 100644 --- a/docs/reporters/index.md +++ b/docs/reporters/index.md @@ -9,4 +9,5 @@ * [junit](junit.md); * [tslint](tslint.md); * [sarif](sarif.md); +* [code-quality](code-quality.md); * [console](console.md). diff --git a/docs/systemRequirements.md b/docs/systemRequirements.md index 750751402fa..5d97384198a 100644 --- a/docs/systemRequirements.md +++ b/docs/systemRequirements.md @@ -6,7 +6,7 @@ `BSL Language Server` представляет собой консольное Java приложение, соответственно, для его функционирования необходимо наличие виртуальной машины Java на компьютере. -На данный момент минимальной поддерживаемой версией является Java 11, но в рамках сборочных конвейеров происходит проверка работоспособности при использовании более свежих версий. На данный момент поддерживаются Java версий 11 и 17. +На данный момент минимальной поддерживаемой версией является Java 17, но в рамках сборочных конвейеров происходит проверка работоспособности при использовании более свежих версий. На данный момент поддерживаются Java версий 17, 21, 23. Кроме версии Java интересен и вендор JDK. В связи с изменившейся политикой лицензирования Oracle, рекомендуется использование открытых реализаций виртуальной машины `OpenJDK`: AdoptOpenJDK, Liberica JDK. @@ -14,6 +14,6 @@ `BSL Language Server` должен работать на всех системах под управлением современных десктопных и серверных операционных систем, для которых существует поддержка Java. В рамках сборочных конвейеров происходит тестирование наиболее популярных окружений: -- гарантированно работает на последних версиях OS семейства Windows 7/10, включая серверные 2012 и выше +- гарантированно работает на последних версиях OS семейства Windows 7/10/11, включая серверные 2012 и выше - поддерживаются OS на ядре Linux, в частности проводится тестирование каждого изменения на Ubuntu, в промышленной эксплуатации подтверждена работоспособность на CentOS версий 6 и 7. - поддерживается MacOS последних версий diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 7454180f2ae..9bbc975c742 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 2e6e5897b52..37f853b1c84 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index c53aefaa5fc..faf93008b77 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright 2015-2021 the original authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,6 +15,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # @@ -32,10 +34,10 @@ # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: # * functions; -# * expansions $var, ${var}, ${var:-default}, ${var+SET}, -# ${var#prefix}, ${var%suffix}, and $( cmd ); -# * compound commands having a testable exit status, especially case; -# * various built-in commands including command, set, and ulimit. +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». # # Important for patching: # @@ -55,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -80,13 +82,11 @@ do esac done -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" +# This is normally unused +# shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -133,22 +133,29 @@ location of your Java installation." fi else JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -193,11 +200,15 @@ if "$cygwin" || "$msys" ; then done fi -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ @@ -205,6 +216,12 @@ set -- \ org.gradle.wrapper.GradleWrapperMain \ "$@" +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. diff --git a/gradlew.bat b/gradlew.bat index 107acd32c4e..9d21a21834d 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,8 +13,10 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +27,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -56,11 +59,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -75,13 +78,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/jitpack.yml b/jitpack.yml deleted file mode 100644 index c9e5a8ab06d..00000000000 --- a/jitpack.yml +++ /dev/null @@ -1,4 +0,0 @@ -before_install: - - source ~/.sdkman/bin/sdkman-init.sh - - sdk install java 17.0.1-tem - - sdk use java 17.0.1-tem diff --git a/lombok.config b/lombok.config index 0206de4de79..9ed93ece8d2 100644 --- a/lombok.config +++ b/lombok.config @@ -1,4 +1,6 @@ lombok.anyConstructor.addConstructorProperties=true +lombok.copyableannotations+=org.springframework.beans.factory.annotation.Qualifier +lombok.copyableannotations+=org.springframework.beans.factory.annotation.Value lombok.addLombokGeneratedAnnotation=true lombok.log.fieldName=LOGGER lombok.extern.findbugs.addSuppressFBWarnings = true diff --git a/qodana.yaml b/qodana.yaml deleted file mode 100644 index 446ab3156d0..00000000000 --- a/qodana.yaml +++ /dev/null @@ -1,8 +0,0 @@ -version: "1.0" -linter: jetbrains/qodana-jvm-community:2022.2 -profile: - name: qodana.starter -include: - - name: CheckDependencyLicenses -exclude: - - name: OptionalUsedAsFieldOrParameterType diff --git a/src/jmh/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/VariableSymbolCreate.java b/src/jmh/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/VariableSymbolCreate.java index 994dcca3d88..f60f8134312 100644 --- a/src/jmh/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/VariableSymbolCreate.java +++ b/src/jmh/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/VariableSymbolCreate.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/AnalyzeProjectOnStart.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/AnalyzeProjectOnStart.java index dd8c52957f1..b27822265f1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/AnalyzeProjectOnStart.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/AnalyzeProjectOnStart.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -25,6 +25,7 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.context.events.ServerContextPopulatedEvent; import com.github._1c_syntax.bsl.languageserver.providers.DiagnosticProvider; +import com.github._1c_syntax.bsl.languageserver.utils.NamedForkJoinWorkerThreadFactory; import com.github._1c_syntax.bsl.languageserver.utils.Resources; import lombok.RequiredArgsConstructor; import org.springframework.context.event.EventListener; @@ -63,7 +64,8 @@ public void handleEvent(ServerContextPopulatedEvent event) { var progress = workDoneProgressHelper.createProgress(documentContexts.size(), getMessage("filesSuffix")); progress.beginProgress(getMessage("analyzeProject")); - var executorService = new ForkJoinPool(ForkJoinPool.getCommonPoolParallelism()); + var factory = new NamedForkJoinWorkerThreadFactory("analyze-on-start-"); + var executorService = new ForkJoinPool(ForkJoinPool.getCommonPoolParallelism(), factory, null, true); try { executorService.submit(() -> diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/AutoServerInfo.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/AutoServerInfo.java index a004af00003..a8454bdc755 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/AutoServerInfo.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/AutoServerInfo.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,12 +21,12 @@ */ package com.github._1c_syntax.bsl.languageserver; +import jakarta.annotation.PostConstruct; import lombok.EqualsAndHashCode; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSBinding.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSBinding.java index e6318fe9755..d3e47adaadf 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSBinding.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSBinding.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java index 2e2051ceec6..8a019fc1593 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncher.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,8 +28,6 @@ import com.github._1c_syntax.bsl.languageserver.cli.WebsocketCommand; import com.github._1c_syntax.utils.CaseInsensitivePattern; import lombok.RequiredArgsConstructor; -import org.jetbrains.annotations.NotNull; -import org.springframework.boot.CommandLineRunner; import org.springframework.boot.ExitCodeGenerator; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; @@ -62,7 +60,7 @@ }, usageHelpAutoWidth = true, synopsisSubcommandLabel = "[COMMAND [ARGS]]", - footer = "@|green Copyright(c) 2018-2022|@", + footer = "@|green Copyright(c) 2018-2025|@", header = "@|green BSL language server|@") @SpringBootApplication(scanBasePackageClasses = BSLLSPLauncher.class) @Component @@ -72,7 +70,7 @@ havingValue = "true", matchIfMissing = true) @RequiredArgsConstructor -public class BSLLSPLauncher implements Callable, CommandLineRunner, ExitCodeGenerator { +public class BSLLSPLauncher implements Callable, ExitCodeGenerator { private static final String DEFAULT_COMMAND = "lsp"; @@ -107,7 +105,10 @@ public static void main(String[] args) { var applicationContext = new SpringApplicationBuilder(BSLLSPLauncher.class) .web(getWebApplicationType(args)) .run(args); + var launcher = applicationContext.getBean(BSLLSPLauncher.class); + launcher.run(args); + if (launcher.getExitCode() >= 0) { System.exit( SpringApplication.exit(applicationContext) @@ -115,8 +116,7 @@ public static void main(String[] args) { } } - @Override - public void run(String[] args) { + public void run(String... args) { var cmd = new CommandLine(this, picocliFactory); // проверка использования дефолтной команды @@ -147,7 +147,6 @@ public void run(String[] args) { } - @NotNull private static String[] addDefaultCommand(String[] args) { List tmpList = new ArrayList<>(Arrays.asList(args)); tmpList.add(0, DEFAULT_COMMAND); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServer.java index 11e6595c7f4..3c3687960c7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -26,7 +26,9 @@ import com.github._1c_syntax.bsl.languageserver.jsonrpc.DiagnosticParams; import com.github._1c_syntax.bsl.languageserver.jsonrpc.Diagnostics; import com.github._1c_syntax.bsl.languageserver.jsonrpc.ProtocolExtension; +import com.github._1c_syntax.bsl.languageserver.providers.CommandProvider; import com.github._1c_syntax.bsl.languageserver.providers.DocumentSymbolProvider; +import com.github._1c_syntax.bsl.languageserver.utils.NamedForkJoinWorkerThreadFactory; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.eclipse.lsp4j.CallHierarchyRegistrationOptions; @@ -40,10 +42,12 @@ import org.eclipse.lsp4j.DocumentLinkOptions; import org.eclipse.lsp4j.DocumentRangeFormattingOptions; import org.eclipse.lsp4j.DocumentSymbolOptions; +import org.eclipse.lsp4j.ExecuteCommandOptions; import org.eclipse.lsp4j.FoldingRangeProviderOptions; import org.eclipse.lsp4j.HoverOptions; import org.eclipse.lsp4j.InitializeParams; import org.eclipse.lsp4j.InitializeResult; +import org.eclipse.lsp4j.InlayHintRegistrationOptions; import org.eclipse.lsp4j.ReferenceOptions; import org.eclipse.lsp4j.RenameCapabilities; import org.eclipse.lsp4j.RenameOptions; @@ -69,6 +73,7 @@ import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ForkJoinPool; @Slf4j @Component @@ -78,9 +83,11 @@ public class BSLLanguageServer implements LanguageServer, ProtocolExtension { private final LanguageServerConfiguration configuration; private final BSLTextDocumentService textDocumentService; private final BSLWorkspaceService workspaceService; + private final CommandProvider commandProvider; private final ClientCapabilitiesHolder clientCapabilitiesHolder; private final ServerContext context; private final ServerInfo serverInfo; + private boolean shutdownWasCalled; @Override @@ -89,7 +96,13 @@ public CompletableFuture initialize(InitializeParams params) { clientCapabilitiesHolder.setCapabilities(params.getCapabilities()); setConfigurationRoot(params); - CompletableFuture.runAsync(context::populateContext); + + var factory = new NamedForkJoinWorkerThreadFactory("populate-context-"); + var executorService = new ForkJoinPool(ForkJoinPool.getCommonPoolParallelism(), factory, null, true); + CompletableFuture + .runAsync(context::populateContext, executorService) + .thenAccept(unused -> executorService.shutdown()) + ; var capabilities = new ServerCapabilities(); capabilities.setTextDocumentSync(getTextDocumentSyncOptions()); @@ -108,6 +121,8 @@ public CompletableFuture initialize(InitializeParams params) { capabilities.setSelectionRangeProvider(getSelectionRangeProvider()); capabilities.setColorProvider(getColorProvider()); capabilities.setRenameProvider(getRenameProvider(params)); + capabilities.setInlayHintProvider(getInlayHintProvider()); + capabilities.setExecuteCommandProvider(getExecuteCommandProvider()); var result = new InitializeResult(capabilities, serverInfo); @@ -308,4 +323,17 @@ private static Boolean getRenamePrepareSupport(InitializeParams params) { .orElse(false); } + private static InlayHintRegistrationOptions getInlayHintProvider() { + var inlayHintOptions = new InlayHintRegistrationOptions(); + inlayHintOptions.setResolveProvider(Boolean.FALSE); + inlayHintOptions.setWorkDoneProgress(Boolean.FALSE); + return inlayHintOptions; + } + + private ExecuteCommandOptions getExecuteCommandProvider() { + var executeCommandOptions = new ExecuteCommandOptions(); + executeCommandOptions.setCommands(commandProvider.getCommandIds()); + executeCommandOptions.setWorkDoneProgress(Boolean.FALSE); + return executeCommandOptions; + } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentService.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentService.java index 53ce1ed6b1b..313d6238aab 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentService.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentService.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -39,10 +39,12 @@ import com.github._1c_syntax.bsl.languageserver.providers.FoldingRangeProvider; import com.github._1c_syntax.bsl.languageserver.providers.FormatProvider; import com.github._1c_syntax.bsl.languageserver.providers.HoverProvider; +import com.github._1c_syntax.bsl.languageserver.providers.InlayHintProvider; import com.github._1c_syntax.bsl.languageserver.providers.ReferencesProvider; import com.github._1c_syntax.bsl.languageserver.providers.RenameProvider; import com.github._1c_syntax.bsl.languageserver.providers.SelectionRangeProvider; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import jakarta.annotation.PreDestroy; import lombok.RequiredArgsConstructor; import org.eclipse.lsp4j.CallHierarchyIncomingCall; import org.eclipse.lsp4j.CallHierarchyIncomingCallsParams; @@ -74,6 +76,8 @@ import org.eclipse.lsp4j.FoldingRangeRequestParams; import org.eclipse.lsp4j.Hover; import org.eclipse.lsp4j.HoverParams; +import org.eclipse.lsp4j.InlayHint; +import org.eclipse.lsp4j.InlayHintParams; import org.eclipse.lsp4j.Location; import org.eclipse.lsp4j.LocationLink; import org.eclipse.lsp4j.PrepareRenameDefaultBehavior; @@ -90,13 +94,15 @@ import org.eclipse.lsp4j.jsonrpc.messages.Either; import org.eclipse.lsp4j.jsonrpc.messages.Either3; import org.eclipse.lsp4j.services.TextDocumentService; +import org.springframework.scheduling.concurrent.CustomizableThreadFactory; import org.springframework.stereotype.Component; import java.net.URI; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; -import java.util.stream.Collectors; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; @Component @RequiredArgsConstructor @@ -118,6 +124,14 @@ public class BSLTextDocumentService implements TextDocumentService, ProtocolExte private final SelectionRangeProvider selectionRangeProvider; private final ColorProvider colorProvider; private final RenameProvider renameProvider; + private final InlayHintProvider inlayHintProvider; + + private final ExecutorService executorService = Executors.newCachedThreadPool(new CustomizableThreadFactory("text-document-service-")); + + @PreDestroy + private void onDestroy() { + executorService.shutdown(); + } @Override public CompletableFuture hover(HoverParams params) { @@ -125,8 +139,9 @@ public CompletableFuture hover(HoverParams params) { if (documentContext == null) { return CompletableFuture.completedFuture(null); } - return CompletableFuture.supplyAsync(() -> - hoverProvider.getHover(documentContext, params).orElse(null) + return CompletableFuture.supplyAsync( + () -> hoverProvider.getHover(documentContext, params).orElse(null), + executorService ); } @@ -139,8 +154,9 @@ public CompletableFuture, List - Either.forRight(definitionProvider.getDefinition(documentContext, params)) + return CompletableFuture.supplyAsync( + () -> Either.forRight(definitionProvider.getDefinition(documentContext, params)), + executorService ); } @@ -151,11 +167,13 @@ public CompletableFuture> references(ReferenceParams pa return CompletableFuture.completedFuture(Collections.emptyList()); } - return CompletableFuture.supplyAsync(() -> referencesProvider.getReferences(documentContext, params)); + return CompletableFuture.supplyAsync( + () -> referencesProvider.getReferences(documentContext, params), + executorService + ); } @Override - @SuppressWarnings("deprecation") public CompletableFuture>> documentSymbol( DocumentSymbolParams params ) { @@ -164,10 +182,11 @@ public CompletableFuture>> docume return CompletableFuture.completedFuture(null); } - return CompletableFuture.supplyAsync(() -> - documentSymbolProvider.getDocumentSymbols(documentContext).stream() + return CompletableFuture.supplyAsync( + () -> documentSymbolProvider.getDocumentSymbols(documentContext).stream() .map(Either::forRight) - .collect(Collectors.toList()) + .toList(), + executorService ); } @@ -178,7 +197,10 @@ public CompletableFuture>> codeAction(CodeActio return CompletableFuture.completedFuture(null); } - return CompletableFuture.supplyAsync(() -> codeActionProvider.getCodeActions(params, documentContext)); + return CompletableFuture.supplyAsync( + () -> codeActionProvider.getCodeActions(params, documentContext), + executorService + ); } @Override @@ -188,7 +210,10 @@ public CompletableFuture> codeLens(CodeLensParams param return CompletableFuture.completedFuture(Collections.emptyList()); } - return CompletableFuture.supplyAsync(() -> codeLensProvider.getCodeLens(documentContext)); + return CompletableFuture.supplyAsync( + () -> codeLensProvider.getCodeLens(documentContext), + executorService + ); } @Override @@ -198,7 +223,10 @@ public CompletableFuture resolveCodeLens(CodeLens unresolved) { if (documentContext == null) { return CompletableFuture.completedFuture(unresolved); } - return CompletableFuture.supplyAsync(() -> codeLensProvider.resolveCodeLens(documentContext, unresolved, data)); + return CompletableFuture.supplyAsync( + () -> codeLensProvider.resolveCodeLens(documentContext, unresolved, data), + executorService + ); } @Override @@ -208,8 +236,10 @@ public CompletableFuture> formatting(DocumentFormatting return CompletableFuture.completedFuture(null); } - List edits = formatProvider.getFormatting(params, documentContext); - return CompletableFuture.completedFuture(edits); + return CompletableFuture.supplyAsync( + () -> formatProvider.getFormatting(params, documentContext), + executorService + ); } @Override @@ -219,8 +249,10 @@ public CompletableFuture> rangeFormatting(DocumentRange return CompletableFuture.completedFuture(null); } - List edits = formatProvider.getRangeFormatting(params, documentContext); - return CompletableFuture.completedFuture(edits); + return CompletableFuture.supplyAsync( + () -> formatProvider.getRangeFormatting(params, documentContext), + executorService + ); } @Override @@ -230,7 +262,10 @@ public CompletableFuture> foldingRange(FoldingRangeRequestPar return CompletableFuture.completedFuture(null); } - return CompletableFuture.supplyAsync(() -> foldingRangeProvider.getFoldingRange(documentContext)); + return CompletableFuture.supplyAsync( + () -> foldingRangeProvider.getFoldingRange(documentContext), + executorService + ); } @Override @@ -241,13 +276,16 @@ public CompletableFuture> prepareCallHierarchy(CallHiera return CompletableFuture.completedFuture(null); } - return CompletableFuture.supplyAsync(() -> { - List callHierarchyItems = callHierarchyProvider.prepareCallHierarchy(documentContext, params); - if (callHierarchyItems.isEmpty()) { - return null; - } - return callHierarchyItems; - }); + return CompletableFuture.supplyAsync( + () -> { + List callHierarchyItems = callHierarchyProvider.prepareCallHierarchy(documentContext, params); + if (callHierarchyItems.isEmpty()) { + return null; + } + return callHierarchyItems; + }, + executorService + ); } @Override @@ -259,7 +297,10 @@ public CompletableFuture> callHierarchyIncomingC return CompletableFuture.completedFuture(Collections.emptyList()); } - return CompletableFuture.supplyAsync(() -> callHierarchyProvider.incomingCalls(documentContext, params)); + return CompletableFuture.supplyAsync( + () -> callHierarchyProvider.incomingCalls(documentContext, params), + executorService + ); } @Override @@ -271,7 +312,10 @@ public CompletableFuture> callHierarchyOutgoingC return CompletableFuture.completedFuture(Collections.emptyList()); } - return CompletableFuture.supplyAsync(() -> callHierarchyProvider.outgoingCalls(documentContext, params)); + return CompletableFuture.supplyAsync( + () -> callHierarchyProvider.outgoingCalls(documentContext, params), + executorService + ); } @Override @@ -281,7 +325,10 @@ public CompletableFuture> selectionRange(SelectionRangePara return CompletableFuture.completedFuture(Collections.emptyList()); } - return CompletableFuture.supplyAsync(() -> selectionRangeProvider.getSelectionRange(documentContext, params)); + return CompletableFuture.supplyAsync( + () -> selectionRangeProvider.getSelectionRange(documentContext, params), + executorService + ); } @Override @@ -291,7 +338,10 @@ public CompletableFuture> documentColor(DocumentColorPara return CompletableFuture.completedFuture(Collections.emptyList()); } - return CompletableFuture.supplyAsync(() -> colorProvider.getDocumentColor(documentContext)); + return CompletableFuture.supplyAsync( + () -> colorProvider.getDocumentColor(documentContext), + executorService + ); } @Override @@ -301,7 +351,23 @@ public CompletableFuture> colorPresentation(ColorPresent return CompletableFuture.completedFuture(Collections.emptyList()); } - return CompletableFuture.supplyAsync(() -> colorProvider.getColorPresentation(documentContext, params)); + return CompletableFuture.supplyAsync( + () -> colorProvider.getColorPresentation(documentContext, params), + executorService + ); + } + + @Override + public CompletableFuture> inlayHint(InlayHintParams params) { + var documentContext = context.getDocument(params.getTextDocument().getUri()); + if (documentContext == null) { + return CompletableFuture.completedFuture(Collections.emptyList()); + } + + return CompletableFuture.supplyAsync( + () -> inlayHintProvider.getInlayHint(documentContext, params), + executorService + ); } @Override @@ -367,7 +433,10 @@ public CompletableFuture> documentLink(DocumentLinkParams par return CompletableFuture.completedFuture(null); } - return CompletableFuture.supplyAsync(() -> documentLinkProvider.getDocumentLinks(documentContext)); + return CompletableFuture.supplyAsync( + () -> documentLinkProvider.getDocumentLinks(documentContext), + executorService + ); } @Override @@ -384,7 +453,7 @@ public CompletableFuture diagnostics(DiagnosticParams params) { if (range != null) { diagnostics = diagnostics.stream() .filter(diagnostic -> Ranges.containsRange(range, diagnostic.getRange())) - .collect(Collectors.toList()); + .toList(); } return new Diagnostics(diagnostics, documentContext.getVersion()); }); @@ -397,8 +466,10 @@ public CompletableFuture - Either3.forFirst(renameProvider.getPrepareRename(documentContext, params))); + return CompletableFuture.supplyAsync( + () -> Either3.forFirst(renameProvider.getPrepareRename(documentContext, params)), + executorService + ); } @Override @@ -408,7 +479,10 @@ public CompletableFuture rename(RenameParams params) { return CompletableFuture.completedFuture(null); } - return CompletableFuture.supplyAsync(() -> renameProvider.getRename(documentContext, params)); + return CompletableFuture.supplyAsync( + () -> renameProvider.getRename(documentContext, params), + executorService + ); } public void reset() { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLWorkspaceService.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLWorkspaceService.java index 3b56b944cf8..6231d1bb4d6 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLWorkspaceService.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLWorkspaceService.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,33 +22,49 @@ package com.github._1c_syntax.bsl.languageserver; import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; +import com.github._1c_syntax.bsl.languageserver.providers.CommandProvider; import com.github._1c_syntax.bsl.languageserver.providers.SymbolProvider; +import jakarta.annotation.PreDestroy; import lombok.RequiredArgsConstructor; import org.apache.commons.beanutils.PropertyUtils; import org.eclipse.lsp4j.DidChangeConfigurationParams; import org.eclipse.lsp4j.DidChangeWatchedFilesParams; +import org.eclipse.lsp4j.ExecuteCommandParams; import org.eclipse.lsp4j.SymbolInformation; import org.eclipse.lsp4j.WorkspaceSymbol; import org.eclipse.lsp4j.WorkspaceSymbolParams; import org.eclipse.lsp4j.jsonrpc.messages.Either; import org.eclipse.lsp4j.services.WorkspaceService; +import org.springframework.scheduling.concurrent.CustomizableThreadFactory; import org.springframework.stereotype.Component; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; @Component @RequiredArgsConstructor public class BSLWorkspaceService implements WorkspaceService { private final LanguageServerConfiguration configuration; + private final CommandProvider commandProvider; private final SymbolProvider symbolProvider; + private final ExecutorService executorService = Executors.newCachedThreadPool(new CustomizableThreadFactory("workspace-service-")); + + @PreDestroy + private void onDestroy() { + executorService.shutdown(); + } + @Override - @SuppressWarnings("deprecation") public CompletableFuture,List>> symbol(WorkspaceSymbolParams params) { - return CompletableFuture.supplyAsync(() -> Either.forRight(symbolProvider.getSymbols(params))); + return CompletableFuture.supplyAsync( + () -> Either.forRight(symbolProvider.getSymbols(params)), + executorService + ); } @Override @@ -64,4 +80,14 @@ public void didChangeConfiguration(DidChangeConfigurationParams params) { public void didChangeWatchedFiles(DidChangeWatchedFilesParams params) { // no-op } + + @Override + public CompletableFuture executeCommand(ExecuteCommandParams params) { + var arguments = commandProvider.extractArguments(params); + + return CompletableFuture.supplyAsync( + () -> commandProvider.executeCommand(arguments), + executorService + ); + } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/ClientCapabilitiesHolder.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/ClientCapabilitiesHolder.java index c8d45f6feba..ac9c3fba311 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/ClientCapabilitiesHolder.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/ClientCapabilitiesHolder.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/LanguageClientHolder.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/LanguageClientHolder.java index 02f194aab59..231b5750201 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/LanguageClientHolder.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/LanguageClientHolder.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,12 +21,12 @@ */ package com.github._1c_syntax.bsl.languageserver; +import edu.umd.cs.findbugs.annotations.Nullable; import lombok.NoArgsConstructor; import org.eclipse.lsp4j.services.LanguageClient; import org.eclipse.lsp4j.services.LanguageClientAware; import org.springframework.stereotype.Component; -import javax.annotation.CheckForNull; import java.util.Optional; import java.util.function.Consumer; @@ -38,7 +38,7 @@ @NoArgsConstructor public class LanguageClientHolder implements LanguageClientAware { - @CheckForNull + @Nullable private LanguageClient client; /** diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/ParentProcessWatcher.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/ParentProcessWatcher.java index b7f419bf099..590564563d8 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/ParentProcessWatcher.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/ParentProcessWatcher.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/WorkDoneProgressHelper.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/WorkDoneProgressHelper.java index bab2ddc4fda..700dc1d9692 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/WorkDoneProgressHelper.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/WorkDoneProgressHelper.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/AspectJConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/AspectJConfiguration.java index d4328b4face..361025d103a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/AspectJConfiguration.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/AspectJConfiguration.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/EventPublisherAspect.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/EventPublisherAspect.java index 88dfaf7dd87..33d34866eda 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/EventPublisherAspect.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/EventPublisherAspect.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,6 +28,7 @@ import com.github._1c_syntax.bsl.languageserver.context.events.DocumentContextContentChangedEvent; import com.github._1c_syntax.bsl.languageserver.context.events.ServerContextPopulatedEvent; import com.github._1c_syntax.bsl.languageserver.events.LanguageServerInitializeRequestReceivedEvent; +import jakarta.annotation.PreDestroy; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.JoinPoint; @@ -39,7 +40,6 @@ import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; -import javax.annotation.PreDestroy; import java.io.File; import java.util.Collection; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/MeasuresAspect.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/MeasuresAspect.java index f348cfc273f..26e5a7087e1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/MeasuresAspect.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/MeasuresAspect.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -25,9 +25,9 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.context.ServerContext; import com.github._1c_syntax.bsl.languageserver.diagnostics.BSLDiagnostic; +import jakarta.annotation.PreDestroy; import lombok.NoArgsConstructor; import lombok.Setter; -import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterReturning; @@ -36,12 +36,10 @@ import org.aspectj.lang.annotation.Before; import org.springframework.beans.factory.annotation.Autowired; -import javax.annotation.PreDestroy; import java.io.File; import java.util.Collection; @Aspect -@Slf4j @NoArgsConstructor public class MeasuresAspect { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/Pointcuts.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/Pointcuts.java index fe2f8527fb1..9dadfab75e8 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/Pointcuts.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/Pointcuts.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect.java index 3785c1a35a9..3ee2e200ca9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,13 +21,22 @@ */ package com.github._1c_syntax.bsl.languageserver.aop; +import com.github._1c_syntax.bsl.languageserver.LanguageClientHolder; +import com.github._1c_syntax.bsl.languageserver.utils.Resources; +import edu.umd.cs.findbugs.annotations.CheckForNull; import io.sentry.Sentry; +import io.sentry.protocol.SentryId; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; import lombok.NoArgsConstructor; +import lombok.Setter; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; +import org.eclipse.lsp4j.MessageParams; +import org.eclipse.lsp4j.MessageType; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.concurrent.CustomizableThreadFactory; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -41,9 +50,16 @@ public class SentryAspect { private ExecutorService executorService; + @Setter(onMethod = @__({@Autowired})) + @CheckForNull + private LanguageClientHolder languageClientHolder; + + @Setter(onMethod = @__({@Autowired})) + private Resources resources; + @PostConstruct private void init() { - executorService = Executors.newCachedThreadPool(); + executorService = Executors.newCachedThreadPool(new CustomizableThreadFactory("sentry-")); } @PreDestroy @@ -53,7 +69,7 @@ private void onDestroy() { @AfterThrowing(value = "Pointcuts.isBSLDiagnostic() && Pointcuts.isGetDiagnosticsCall()", throwing = "ex") public void logThrowingBSLDiagnosticGetDiagnostics(Throwable ex) { - CompletableFuture.runAsync(() -> Sentry.captureException(ex), executorService); + logException(ex); } @AfterThrowing(value = @@ -61,7 +77,24 @@ public void logThrowingBSLDiagnosticGetDiagnostics(Throwable ex) { throwing = "ex" ) public void logThrowingLSPCall(Throwable ex) { - CompletableFuture.runAsync(() -> Sentry.captureException(ex), executorService); + logException(ex); + } + + private void logException(Throwable ex) { + CompletableFuture.runAsync(() -> { + SentryId sentryId = Sentry.captureException(ex); + if (sentryId.equals(SentryId.EMPTY_ID)) { + return; + } + if (languageClientHolder == null) { + return; + } + var messageType = MessageType.Info; + var message = resources.getResourceString(getClass(), "logMessage", sentryId); + var messageParams = new MessageParams(messageType, message); + + languageClientHolder.execIfConnected(languageClient -> languageClient.showMessage(messageParams)); + }, executorService); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/ConditionalOnMeasuresEnabled.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/ConditionalOnMeasuresEnabled.java index 1cfe1d46e3a..fcd6fa1e643 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/ConditionalOnMeasuresEnabled.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/ConditionalOnMeasuresEnabled.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/DocumentContextLazyDataMeasurer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/DocumentContextLazyDataMeasurer.java index 87abe20fb16..29ff969bd01 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/DocumentContextLazyDataMeasurer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/DocumentContextLazyDataMeasurer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/MeasureCollector.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/MeasureCollector.java index d3740e34037..bb95db6a6c7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/MeasureCollector.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/MeasureCollector.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/package-info.java index c046b455dd8..f0ce3a62ba1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,7 +22,8 @@ /** * Выполнение замеров производительности. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.aop.measures; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/package-info.java index b952bfe26a3..01290e3e887 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,7 +22,8 @@ /** * Слой работы в парадигме аспектно-ориентированного программирования. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.aop; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/sentry/PermissionFilterBeforeSendCallback.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/sentry/PermissionFilterBeforeSendCallback.java index 9f57bef9767..ebe7161a946 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/sentry/PermissionFilterBeforeSendCallback.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/sentry/PermissionFilterBeforeSendCallback.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -27,6 +27,7 @@ import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.bsl.languageserver.configuration.SendErrorsMode; import com.github._1c_syntax.bsl.languageserver.utils.Resources; +import edu.umd.cs.findbugs.annotations.Nullable; import io.sentry.Hint; import io.sentry.SentryEvent; import io.sentry.SentryOptions.BeforeSendCallback; @@ -37,10 +38,8 @@ import org.eclipse.lsp4j.ServerInfo; import org.eclipse.lsp4j.ShowMessageRequestParams; import org.eclipse.lsp4j.services.LanguageClient; -import org.jetbrains.annotations.NotNull; import org.springframework.stereotype.Component; -import javax.annotation.CheckForNull; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; @@ -71,7 +70,7 @@ public class PermissionFilterBeforeSendCallback implements BeforeSendCallback { private final AtomicBoolean questionWasSend = new AtomicBoolean(false); @Override - public SentryEvent execute(@NotNull SentryEvent event, @NotNull Hint hint) { + public SentryEvent execute(SentryEvent event, Hint hint) { if (sendToSentry()) { return event; } @@ -132,7 +131,7 @@ private CompletableFuture askUserForPermission(LanguageClient return languageClient.showMessageRequest(requestParams); } - @CheckForNull + @Nullable private MessageActionItem waitForPermission(CompletableFuture sendQuestion) { try { return sendQuestion.get(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/sentry/SentryScopeConfigurer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/sentry/SentryScopeConfigurer.java index 6ebcf061aa7..268a6dab05e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/sentry/SentryScopeConfigurer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/sentry/SentryScopeConfigurer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,17 +21,18 @@ */ package com.github._1c_syntax.bsl.languageserver.aop.sentry; -import io.sentry.Scope; +import io.sentry.IScope; import io.sentry.Sentry; import io.sentry.protocol.User; +import jakarta.annotation.Nullable; +import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import org.eclipse.lsp4j.ServerInfo; -import org.jetbrains.annotations.NotNull; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.context.annotation.DependsOn; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; +import java.net.InetAddress; +import java.net.UnknownHostException; import java.util.UUID; /** @@ -41,21 +42,47 @@ */ @Component @RequiredArgsConstructor -@ConditionalOnBean(name = "sentryHub") -@DependsOn("sentryHub") public class SentryScopeConfigurer { private final ServerInfo serverInfo; + private final PermissionFilterBeforeSendCallback beforeSendCallback; + + @Value("${sentry.dsn:}") + private final String dsn; + + @Value("${sentry.environment:dummy}") + private final String environment; @PostConstruct public void init() { - Sentry.configureScope((@NotNull Scope scope) -> { + if (dsn != null && !dsn.isEmpty()) { + Sentry.init(options -> { + options.setDsn(dsn); + options.setEnvironment(environment); + options.setRelease(serverInfo.getVersion()); + options.setAttachServerName(false); + options.setServerName(getServerName()); + options.setBeforeSend(beforeSendCallback); + options.addInAppInclude("com.github._1c_syntax.bsl.languageserver"); + }); + } + + Sentry.configureScope((IScope scope) -> { var user = new User(); user.setId(UUID.randomUUID().toString()); scope.setUser(user); - - scope.setTag("server.version", serverInfo.getVersion()); }); } + @Nullable + private String getServerName() { + try { + String hostName = InetAddress.getLocalHost().getHostName(); + return UUID.nameUUIDFromBytes(hostName.getBytes()).toString(); + } catch (UnknownHostException e) { + // ignore + return null; + } + } + } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/sentry/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/sentry/package-info.java index 0bd3708c131..03468a09970 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/sentry/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/aop/sentry/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,7 +22,8 @@ /** * Отправка аналитики в Sentry. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.aop.sentry; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/AbstractCfgVisitor.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/AbstractCfgVisitor.java index 34615caf55c..56c486fee8f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/AbstractCfgVisitor.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/AbstractCfgVisitor.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/BasicBlockVertex.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/BasicBlockVertex.java index d47eb56be47..30cfb745c1b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/BasicBlockVertex.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/BasicBlockVertex.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/BranchingVertex.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/BranchingVertex.java index b642356c0da..95dc2312ef4 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/BranchingVertex.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/BranchingVertex.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/CfgBuildingParseTreeVisitor.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/CfgBuildingParseTreeVisitor.java index 3e80e310029..b496f7725e0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/CfgBuildingParseTreeVisitor.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/CfgBuildingParseTreeVisitor.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,7 +29,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Map; -import java.util.stream.Collectors; public class CfgBuildingParseTreeVisitor extends BSLParserBaseVisitor { @@ -148,12 +147,12 @@ public ParseTree visitIfStatement(BSLParser.IfStatementContext ctx) { while (!currentLevelBlock.getBuildParts().isEmpty()) { var blockTail = currentLevelBlock.getBuildParts().pop(); - if (hasNoSignificantEdges(blockTail) && blockTail instanceof BasicBlockVertex) { - // это мертвый код. Он может быть пустым блоком - // тогда он не нужен сам по себе - var basicBlock = (BasicBlockVertex) blockTail; - if (basicBlock.statements().isEmpty()) - continue; + // это мертвый код. Он может быть пустым блоком + // тогда он не нужен сам по себе + if (hasNoSignificantEdges(blockTail) + && blockTail instanceof BasicBlockVertex basicBlock + && basicBlock.statements().isEmpty()) { + continue; } graph.addEdge(blockTail, upperBlock.end()); } @@ -163,7 +162,9 @@ public ParseTree visitIfStatement(BSLParser.IfStatementContext ctx) { private boolean hasNoSignificantEdges(CfgVertex blockTail) { var edges = graph.incomingEdgesOf(blockTail); - return edges.isEmpty() || (adjacentDeadCodeEnabled && edges.stream().allMatch(x -> x.getType() == CfgEdgeType.ADJACENT_CODE)); + return edges.isEmpty() + || (adjacentDeadCodeEnabled + && edges.stream().allMatch(x -> x.getType() == CfgEdgeType.ADJACENT_CODE)); } @Override @@ -372,8 +373,9 @@ public ParseTree visitPreproc_if(BSLParser.Preproc_ifContext ctx) { return ctx; } - if (!isStatementLevelPreproc(ctx)) + if (!isStatementLevelPreproc(ctx)) { return super.visitPreproc_if(ctx); + } var node = new PreprocessorConditionVertex(ctx); graph.addVertex(node); @@ -477,14 +479,15 @@ public ParseTree visitPreproc_endif(BSLParser.Preproc_endifContext ctx) { // присоединяем все прямые выходы из тел условий while (!mainIf.getBuildParts().isEmpty()) { var blockTail = mainIf.getBuildParts().pop(); - if (hasNoSignificantEdges(blockTail) && blockTail instanceof BasicBlockVertex) { - // это мертвый код. Он может быть пустым блоком - // тогда он не нужен сам по себе - var basicBlock = (BasicBlockVertex) blockTail; - if (basicBlock.statements().isEmpty()) { - graph.removeVertex(basicBlock); - continue; - } + + // это мертвый код. Он может быть пустым блоком + // тогда он не нужен сам по себе + if (hasNoSignificantEdges(blockTail) + && blockTail instanceof BasicBlockVertex basicBlock + && basicBlock.statements().isEmpty()) { + + graph.removeVertex(basicBlock); + continue; } graph.addVertex(blockTail); graph.addEdge(blockTail, upperBlock.end()); @@ -493,15 +496,15 @@ public ParseTree visitPreproc_endif(BSLParser.Preproc_endifContext ctx) { return ctx; } - private boolean isStatementLevelPreproc(BSLParserRuleContext ctx) { + private static boolean isStatementLevelPreproc(BSLParserRuleContext ctx) { return ctx.getParent().getParent().getRuleIndex() == BSLParser.RULE_statement; } private PreprocessorConditionVertex popPreprocCondition() { var node = blocks.getCurrentBlock().getBuildParts().peek(); - if (node instanceof PreprocessorConditionVertex) { + if (node instanceof PreprocessorConditionVertex preprocessorConditionVertex) { blocks.getCurrentBlock().getBuildParts().pop(); - return (PreprocessorConditionVertex) node; + return preprocessorConditionVertex; } return null; } @@ -545,12 +548,11 @@ private void buildLoopSubgraph(BSLParser.CodeBlockContext ctx, LoopVertex loopSt private void connectGraphTail(StatementsBlockWriter.StatementsBlockRecord currentBlock, CfgVertex vertex) { - if (!(currentBlock.end() instanceof BasicBlockVertex)) { + if (!(currentBlock.end() instanceof BasicBlockVertex currentTail)) { graph.addEdge(currentBlock.end(), vertex); return; } - var currentTail = (BasicBlockVertex) currentBlock.end(); if (currentTail.statements().isEmpty()) { // перевести все связи на новую вершину var incoming = graph.incomingEdgesOf(currentTail); @@ -575,17 +577,17 @@ private void connectGraphTail(StatementsBlockWriter.StatementsBlockRecord curren private void removeOrphanedNodes() { var orphans = graph.vertexSet().stream() .filter(vertex -> !(vertex instanceof ExitVertex)) - .filter(vertex -> { + .filter((CfgVertex vertex) -> { var edges = new ArrayList<>(graph.edgesOf(vertex)); - return edges.isEmpty() || - adjacentDeadCodeEnabled && - edges.size() == 1 - && edges.get(0).getType() == CfgEdgeType.ADJACENT_CODE - && graph.getEdgeTarget(edges.get(0)) == vertex; + return edges.isEmpty() + || (adjacentDeadCodeEnabled + && edges.size() == 1 + && edges.get(0).getType() == CfgEdgeType.ADJACENT_CODE + && graph.getEdgeTarget(edges.get(0)) == vertex); }) - .collect(Collectors.toList()); + .toList(); // в одном стриме бывает ConcurrentModificationException // делаем через другую коллекцию diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/CfgEdge.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/CfgEdge.java index 6d5fdbc99ed..08484543f06 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/CfgEdge.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/CfgEdge.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/CfgEdgeType.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/CfgEdgeType.java index c49463879d7..82aa274e61c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/CfgEdgeType.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/CfgEdgeType.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/CfgVertex.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/CfgVertex.java index 2139783b75f..a408a75dad9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/CfgVertex.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/CfgVertex.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ConditionalVertex.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ConditionalVertex.java index bdfe509815e..126dec69b10 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ConditionalVertex.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ConditionalVertex.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,6 +24,7 @@ import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import lombok.EqualsAndHashCode; + import java.util.Optional; @EqualsAndHashCode(callSuper = true) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ControlFlowGraph.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ControlFlowGraph.java index 5acf940e461..05352436c87 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ControlFlowGraph.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ControlFlowGraph.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -25,13 +25,12 @@ import lombok.Setter; import org.jgrapht.graph.DefaultDirectedGraph; +@Getter public class ControlFlowGraph extends DefaultDirectedGraph { - @Getter @Setter private CfgVertex entryPoint; - @Getter private ExitVertex exitPoint; ControlFlowGraph() { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ControlFlowGraphWalker.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ControlFlowGraphWalker.java index e449f9f133c..7cac19a5e2c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ControlFlowGraphWalker.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ControlFlowGraphWalker.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ExitVertex.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ExitVertex.java index d20feaa347a..d511c00347f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ExitVertex.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ExitVertex.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ForLoopVertex.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ForLoopVertex.java index d94208bf401..4de8c2d30e9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ForLoopVertex.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ForLoopVertex.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ForeachLoopVertex.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ForeachLoopVertex.java index a2d3f66f1f7..24935f6935a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ForeachLoopVertex.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/ForeachLoopVertex.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/LabelVertex.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/LabelVertex.java index ab572962488..3f57dd21e6e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/LabelVertex.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/LabelVertex.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/LoopVertex.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/LoopVertex.java index b1e910cc051..5109173bcb1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/LoopVertex.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/LoopVertex.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/PreprocessorConditionVertex.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/PreprocessorConditionVertex.java index 8228aad54ec..57d5a2a6575 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/PreprocessorConditionVertex.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/PreprocessorConditionVertex.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/PreprocessorConstraints.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/PreprocessorConstraints.java index a8bb99362e9..f98b28838fb 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/PreprocessorConstraints.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/PreprocessorConstraints.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/StatementsBlockWriter.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/StatementsBlockWriter.java index 5dee8b62855..9a3e3271852 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/StatementsBlockWriter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/StatementsBlockWriter.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,6 +22,7 @@ package com.github._1c_syntax.bsl.languageserver.cfg; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; +import lombok.Getter; import java.util.ArrayDeque; import java.util.Deque; @@ -42,6 +43,8 @@ static class StatementsBlockRecord { private BasicBlockVertex statements = new BasicBlockVertex(); private final Deque buildStack = new ArrayDeque<>(); + + @Getter private final JumpInformationRecord jumpContext; public StatementsBlockRecord() { @@ -62,10 +65,6 @@ public Deque getBuildParts() { return buildStack; } - public JumpInformationRecord getJumpContext() { - return jumpContext; - } - public void split() { if (subgraphBegin instanceof BasicBlockVertex && subgraphBegin == subgraphEnd) { subgraphBegin = statements; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/TryExceptVertex.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/TryExceptVertex.java index 5cf5be89c23..a96476f6f52 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/TryExceptVertex.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/TryExceptVertex.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/WhileLoopVertex.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/WhileLoopVertex.java index 3e664eeb305..bfaf7dc7afc 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/WhileLoopVertex.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cfg/WhileLoopVertex.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java index a68ac359a6d..b748bdff8e3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/AnalyzeCommand.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,13 +22,12 @@ package com.github._1c_syntax.bsl.languageserver.cli; import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; -import com.github._1c_syntax.bsl.languageserver.context.MetricStorage; import com.github._1c_syntax.bsl.languageserver.context.ServerContext; import com.github._1c_syntax.bsl.languageserver.reporters.ReportersAggregator; import com.github._1c_syntax.bsl.languageserver.reporters.data.AnalysisInfo; import com.github._1c_syntax.bsl.languageserver.reporters.data.FileInfo; +import com.github._1c_syntax.bsl.mdo.MD; import com.github._1c_syntax.bsl.types.MdoReference; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; import com.github._1c_syntax.utils.Absolute; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; @@ -37,7 +36,6 @@ import me.tongfei.progressbar.ProgressBarBuilder; import me.tongfei.progressbar.ProgressBarStyle; import org.apache.commons.io.FileUtils; -import org.eclipse.lsp4j.Diagnostic; import org.springframework.stereotype.Component; import picocli.CommandLine.Command; @@ -82,7 +80,7 @@ aliases = {"-a", "--analyze"}, description = "Run analysis and get diagnostic info", usageHelpAutoWidth = true, - footer = "@|green Copyright(c) 2018-2022|@") + footer = "@|green Copyright(c) 2018-2025|@") @Component @RequiredArgsConstructor public class AnalyzeCommand implements Callable { @@ -205,10 +203,10 @@ private FileInfo getFileInfoFromFile(Path srcDir, File file) { context.rebuildDocument(documentContext); var filePath = srcDir.relativize(Absolute.path(file)); - List diagnostics = documentContext.getDiagnostics(); - MetricStorage metrics = documentContext.getMetrics(); + var diagnostics = documentContext.getDiagnostics(); + var metrics = documentContext.getMetrics(); var mdoRef = documentContext.getMdObject() - .map(AbstractMDObjectBase::getMdoReference) + .map(MD::getMdoReference) .map(MdoReference::getMdoRef) .orElse(""); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java index eba3610162c..f7308bead2e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/FormatCommand.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -68,7 +68,7 @@ aliases = {"-f", "--format"}, description = "Format files in source directory", usageHelpAutoWidth = true, - footer = "@|green Copyright(c) 2018-2022|@") + footer = "@|green Copyright(c) 2018-2025|@") @Component @RequiredArgsConstructor public class FormatCommand implements Callable { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java index 868d56b7041..009fbdbabe7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/LanguageServerStartCommand.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,7 +23,6 @@ import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import org.eclipse.lsp4j.jsonrpc.Launcher; import org.eclipse.lsp4j.services.LanguageClient; import org.eclipse.lsp4j.services.LanguageClientAware; @@ -47,13 +46,12 @@ * Выводимая информация: * Данный режим используется для взаимодействия с клиентом по протоколу LSP. */ -@Slf4j @Command( name = "lsp", aliases = {"--lsp"}, description = "LSP server mode (default)", usageHelpAutoWidth = true, - footer = "@|green Copyright(c) 2018-2022|@") + footer = "@|green Copyright(c) 2018-2025|@") @Component @RequiredArgsConstructor public class LanguageServerStartCommand implements Callable { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java index 91bc28fcb33..58e74f6d3ab 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommand.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,7 +22,6 @@ package com.github._1c_syntax.bsl.languageserver.cli; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import org.eclipse.lsp4j.ServerInfo; import org.springframework.stereotype.Component; import picocli.CommandLine.Command; @@ -34,13 +33,12 @@ * Ключ команды: * -v, (--version) */ -@Slf4j @Command( name = "version", aliases = {"-v", "--version"}, description = "Print version", usageHelpAutoWidth = true, - footer = "@|green Copyright(c) 2018-2022|@") + footer = "@|green Copyright(c) 2018-2025|@") @Component @RequiredArgsConstructor public class VersionCommand implements Callable { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/WebsocketCommand.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/WebsocketCommand.java index 0c8d2d05849..1fd3f093f4a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/WebsocketCommand.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/WebsocketCommand.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,7 +23,6 @@ import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import java.io.File; @@ -48,13 +47,12 @@ * Данный режим используется для взаимодействия с клиентом по протоколу LSP через websocket. * */ -@Slf4j @Command( name = "websocket", aliases = {"-w", "--websocket"}, description = "Websocket server mode", usageHelpAutoWidth = true, - footer = "@|green Copyright(c) 2018-2022|@") + footer = "@|green Copyright(c) 2018-2025|@") @Component @RequiredArgsConstructor public class WebsocketCommand implements Callable { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/lsp/FileAwarePrintWriter.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/lsp/FileAwarePrintWriter.java index 011b239957e..b3bfb596f59 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/lsp/FileAwarePrintWriter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/lsp/FileAwarePrintWriter.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,12 +22,12 @@ package com.github._1c_syntax.bsl.languageserver.cli.lsp; import com.github._1c_syntax.bsl.languageserver.configuration.events.LanguageServerConfigurationChangedEvent; +import edu.umd.cs.findbugs.annotations.Nullable; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; -import javax.annotation.CheckForNull; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; @@ -59,42 +59,39 @@ public FileAwarePrintWriter() { /** * @param file Файл, в который отныне нужно перенаправлять вывод PrintWriter */ - public void setFile(@CheckForNull File file) { - - // sync on non-private field, cause this#lock is supposed to be used as lock-object. See field description. - synchronized (lock) { - if (Objects.equals(file, this.file)) { - return; - } - - this.file = file; - - if (file == null) { - closeOutputStream(); - return; - } - - if (file.isDirectory()) { - LOGGER.error("Trace log setting must lead to file, not directory! {}", file.getAbsolutePath()); - return; - } - - FileOutputStream fileOutputStream; - try { - // stream is not closed, cause it used as output stream in writer. See this#out field. - fileOutputStream = new FileOutputStream(file); - } catch (FileNotFoundException e) { - LOGGER.error("Can't create LSP trace file", e); - return; - } + public synchronized void setFile(@Nullable File file) { + if (Objects.equals(file, this.file)) { + return; + } + + this.file = file; + + if (file == null) { closeOutputStream(); + return; + } - this.out = new BufferedWriter(new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8)); - this.lock = this.out; - this.isEmpty = false; + if (file.isDirectory()) { + LOGGER.error("Trace log setting must lead to file, not directory! {}", file.getAbsolutePath()); + return; + } + + FileOutputStream fileOutputStream; + try { + // stream is not closed, cause it used as output stream in writer. See this#out field. + fileOutputStream = new FileOutputStream(file); + } catch (FileNotFoundException e) { + LOGGER.error("Can't create LSP trace file", e); + return; } + closeOutputStream(); + + this.out = new BufferedWriter(new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8)); + this.lock = this.out; + this.isEmpty = false; + } @Override diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/lsp/LanguageServerLauncherConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/lsp/LanguageServerLauncherConfiguration.java index 6993b6e7feb..57a5803df57 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/lsp/LanguageServerLauncherConfiguration.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/lsp/LanguageServerLauncherConfiguration.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,7 +21,6 @@ */ package com.github._1c_syntax.bsl.languageserver.cli.lsp; -import lombok.extern.slf4j.Slf4j; import org.eclipse.lsp4j.jsonrpc.Launcher; import org.eclipse.lsp4j.launch.LSPLauncher; import org.eclipse.lsp4j.services.LanguageClient; @@ -36,7 +35,6 @@ * Конфигурация для создания объектов из lsp4j-слоя. */ @Configuration -@Slf4j public class LanguageServerLauncherConfiguration { @Bean diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/lsp/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/lsp/package-info.java index 10c444cef37..59ef3545b08 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/lsp/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/lsp/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,7 +23,8 @@ * Классы для конфигурирования и запуска команды * {@link com.github._1c_syntax.bsl.languageserver.cli.LanguageServerStartCommand} */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.cli.lsp; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/package-info.java index 3a54e1dce8a..bddaa4259c3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/cli/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/AbstractQuickFixSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/AbstractQuickFixSupplier.java index d9c5ad6c281..b4d2d728a6c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/AbstractQuickFixSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/AbstractQuickFixSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/CodeActionSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/CodeActionSupplier.java index 980cb6a39c6..80e6f4f5487 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/CodeActionSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/CodeActionSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/DisableDiagnosticTriggeringSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/DisableDiagnosticTriggeringSupplier.java index 78358797006..4bec9fa4d0a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/DisableDiagnosticTriggeringSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/DisableDiagnosticTriggeringSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -34,7 +34,6 @@ import org.eclipse.lsp4j.Range; import org.eclipse.lsp4j.TextEdit; import org.eclipse.lsp4j.WorkspaceEdit; -import org.jetbrains.annotations.NotNull; import org.springframework.stereotype.Component; import java.util.ArrayList; @@ -205,7 +204,6 @@ private List createInFileTextEdits(String diagnosticName) { return Collections.singletonList(textEdit); } - @NotNull private CodeAction createCodeAction(String title, List edits, DocumentContext documentContext) { Map> changes = Map.of(documentContext.getUri().toString(), edits); WorkspaceEdit edit = new WorkspaceEdit(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/ExtractStructureConstructorSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/ExtractStructureConstructorSupplier.java new file mode 100644 index 00000000000..68de04ed21a --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/ExtractStructureConstructorSupplier.java @@ -0,0 +1,166 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.codeactions; + +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.utils.DiagnosticHelper; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.languageserver.utils.Resources; +import com.github._1c_syntax.bsl.languageserver.utils.Strings; +import com.github._1c_syntax.bsl.languageserver.utils.Trees; +import com.github._1c_syntax.bsl.parser.BSLLexer; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; +import lombok.RequiredArgsConstructor; +import org.antlr.v4.runtime.tree.TerminalNode; +import org.eclipse.lsp4j.CodeAction; +import org.eclipse.lsp4j.CodeActionKind; +import org.eclipse.lsp4j.CodeActionParams; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.TextEdit; +import org.eclipse.lsp4j.WorkspaceEdit; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.function.Predicate; + +@Component +@RequiredArgsConstructor +public class ExtractStructureConstructorSupplier implements CodeActionSupplier { + + private final LanguageServerConfiguration configuration; + + @Override + public List getCodeActions(CodeActionParams params, DocumentContext documentContext) { + + var start = params.getRange().getStart(); + if (start == null) { + return Collections.emptyList(); + } + + var parseTree = documentContext.getAst(); + + var maybeDoCall = Trees.findTerminalNodeContainsPosition(parseTree, start) + .map(TerminalNode::getParent) + .filter(BSLParser.TypeNameContext.class::isInstance) + .map(BSLParser.TypeNameContext.class::cast) + .filter(DiagnosticHelper::isStructureType) + .map(BSLParserRuleContext::getParent) + .map(BSLParser.NewExpressionContext.class::cast) + .map(BSLParser.NewExpressionContext::doCall); + + if (maybeDoCall.isEmpty()) { + return Collections.emptyList(); + } + + var parameters = maybeDoCall + .map(BSLParser.DoCallContext::callParamList) + .map(callParamListContext -> callParamListContext.children) + .orElse(Collections.emptyList()) + .stream() + .filter(Predicate.not(TerminalNode.class::isInstance)) + .map(BSLParser.CallParamContext.class::cast) + .toList(); + + if (parameters.isEmpty()) { + return Collections.emptyList(); + } + + var firstParam = parameters.get(0); + if (firstParam.getTokens().isEmpty()) { + return Collections.emptyList(); + } + + var firstToken = firstParam.getTokens().get(0); + if (firstToken.getType() != BSLLexer.STRING) { + return Collections.emptyList(); + } + + var doCall = maybeDoCall.get(); + var assignment = (BSLParser.AssignmentContext) Trees.getAncestorByRuleIndex(doCall, BSLParser.RULE_assignment); + if (assignment == null || isParentAssignment(doCall, assignment)) { + return Collections.emptyList(); + } + + var lValue = assignment.lValue(); + if (lValue == null) { + return Collections.emptyList(); + } + + var lValueName = lValue.getText(); + var insert = Resources.getResourceString(configuration.getLanguage(), getClass(), "insert"); + + var keys = Strings.trimQuotes(firstToken.getText()).split(","); + var workspaceEdit = new WorkspaceEdit(); + var changes = new ArrayList(); + + var constructorEdit = new TextEdit(Ranges.create(doCall), "()"); + changes.add(constructorEdit); + + var indentSize = Ranges.create(lValue).getStart().getCharacter(); + + var rparenRange = Ranges.create(doCall.RPAREN()); + var constructorLine = rparenRange.getEnd().getLine(); + var position = new Position(constructorLine + 1, 0); + var range = new Range(position, position); + + var indent = documentContext.getContentList()[constructorLine].substring(0, indentSize); + + for (var i = 0; i < keys.length; i++) { + var key = keys[i].trim(); + var value = ""; + var separator = ""; + if (parameters.size() > i + 1) { + value = parameters.get(i + 1).getText(); + separator = ", "; + } + + var newText = String.format("%s%s.%s(\"%s\"%s%s);\n", indent, lValueName, insert, key, separator, value); + var textEdit = new TextEdit(range, newText); + changes.add(textEdit); + } + + workspaceEdit.setChanges(Map.of(documentContext.getUri().toString(), changes)); + + var codeAction = new CodeAction(); + codeAction.setEdit(workspaceEdit); + codeAction.setKind(CodeActionKind.Refactor); + codeAction.setIsPreferred(Boolean.TRUE); + codeAction.setTitle(Resources.getResourceString(configuration.getLanguage(), getClass(), "title")); + + return Collections.singletonList(codeAction); + + } + + private static boolean isParentAssignment(BSLParser.DoCallContext doCall, BSLParser.AssignmentContext assignment) { + return assignment.expression().member().stream() + .map(BSLParser.MemberContext::complexIdentifier) + .map(BSLParser.ComplexIdentifierContext::newExpression) + .filter(newExpressionContext -> newExpressionContext == doCall.getParent()) + .findAny().isEmpty(); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/FixAllCodeActionSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/FixAllCodeActionSupplier.java index 6c53bf4d736..a7fee6212df 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/FixAllCodeActionSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/FixAllCodeActionSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/GenerateStandardRegionsSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/GenerateStandardRegionsSupplier.java index 893aafca9c4..93942932156 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/GenerateStandardRegionsSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/GenerateStandardRegionsSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -37,7 +37,6 @@ import org.eclipse.lsp4j.Range; import org.eclipse.lsp4j.TextEdit; import org.eclipse.lsp4j.WorkspaceEdit; -import org.jetbrains.annotations.NotNull; import org.springframework.stereotype.Component; import java.util.ArrayList; @@ -130,7 +129,6 @@ private ScriptVariant getRegionsLanguage(DocumentContext documentContext, FileTy return regionsLanguage; } - @NotNull private ScriptVariant getScriptVariantFromConfigLanguage() { ScriptVariant regionsLanguage; if (languageServerConfiguration.getLanguage() == Language.EN) { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixCodeActionSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixCodeActionSupplier.java index a9ee156443b..278b27560ab 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixCodeActionSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixCodeActionSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixSupplier.java index 324e009ebc5..e93a36493db 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/package-info.java index d876adbc51f..28544a9a450 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codeactions/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/AbstractMethodComplexityCodeLensSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/AbstractMethodComplexityCodeLensSupplier.java index 7e9d5ac6fda..6884f5a945a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/AbstractMethodComplexityCodeLensSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/AbstractMethodComplexityCodeLensSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,6 +21,8 @@ */ package com.github._1c_syntax.bsl.languageserver.codelenses; +import com.github._1c_syntax.bsl.languageserver.commands.complexity.AbstractToggleComplexityInlayHintsCommandSupplier; +import com.github._1c_syntax.bsl.languageserver.commands.complexity.ToggleComplexityInlayHintsCommandArguments; 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; @@ -30,7 +32,6 @@ import lombok.ToString; import lombok.Value; import org.eclipse.lsp4j.CodeLens; -import org.eclipse.lsp4j.Command; import org.eclipse.lsp4j.jsonrpc.messages.Either; import java.beans.ConstructorProperties; @@ -52,13 +53,14 @@ public abstract class AbstractMethodComplexityCodeLensSupplier private static final int DEFAULT_COMPLEXITY_THRESHOLD = -1; protected final LanguageServerConfiguration configuration; + private final AbstractToggleComplexityInlayHintsCommandSupplier commandSupplier; @Override public List getCodeLenses(DocumentContext documentContext) { var complexityThreshold = getComplexityThreshold(); var methodsComplexity = getMethodsComplexity(documentContext); return documentContext.getSymbolTree().getMethods().stream() - .filter(methodSymbol -> methodsComplexity.get(methodSymbol) >= complexityThreshold) + .filter(methodSymbol -> methodsComplexity.getOrDefault(methodSymbol, complexityThreshold - 1) >= complexityThreshold) .map(methodSymbol -> toCodeLens(methodSymbol, documentContext)) .collect(Collectors.toList()); } @@ -69,8 +71,14 @@ public CodeLens resolve(DocumentContext documentContext, CodeLens unresolved, Co var methodsComplexity = getMethodsComplexity(documentContext); documentContext.getSymbolTree().getMethodSymbol(methodName).ifPresent((MethodSymbol methodSymbol) -> { int complexity = methodsComplexity.get(methodSymbol); + var title = Resources.getResourceString(configuration.getLanguage(), getClass(), TITLE_KEY, complexity); - var command = new Command(title, ""); + var arguments = new ToggleComplexityInlayHintsCommandArguments( + commandSupplier.getId(), + data + ); + + var command = commandSupplier.createCommand(title, arguments); unresolved.setCommand(command); }); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/AbstractRunTestsCodeLensSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/AbstractRunTestsCodeLensSupplier.java new file mode 100644 index 00000000000..983efcea4ec --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/AbstractRunTestsCodeLensSupplier.java @@ -0,0 +1,131 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.codelenses; + +import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; +import com.github._1c_syntax.bsl.languageserver.configuration.events.LanguageServerConfigurationChangedEvent; +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.FileType; +import com.github._1c_syntax.bsl.languageserver.events.LanguageServerInitializeRequestReceivedEvent; +import com.github._1c_syntax.utils.Absolute; +import jakarta.annotation.Nullable; +import lombok.RequiredArgsConstructor; +import org.eclipse.lsp4j.ClientInfo; +import org.eclipse.lsp4j.InitializeParams; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cache.annotation.CacheConfig; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.context.event.EventListener; + +import java.net.URI; +import java.nio.file.Path; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +@RequiredArgsConstructor +@CacheConfig(cacheNames = "testSources") +public abstract class AbstractRunTestsCodeLensSupplier + implements CodeLensSupplier { + + protected final LanguageServerConfiguration configuration; + + private boolean clientIsSupported; + + /** + * Обработчик события {@link LanguageServerInitializeRequestReceivedEvent}. + *

+ * Анализирует тип подключенного клиента и управляет применимостью линзы. + * + * @param event Событие + */ + @EventListener + @CacheEvict(allEntries = true) + public void handleEvent(LanguageServerInitializeRequestReceivedEvent event) { + var clientName = Optional.of(event) + .map(LanguageServerInitializeRequestReceivedEvent::getParams) + .map(InitializeParams::getClientInfo) + .map(ClientInfo::getName) + .orElse(""); + clientIsSupported = "Visual Studio Code".equals(clientName); + } + + /** + * Обработчик события {@link LanguageServerConfigurationChangedEvent}. + *

+ * Сбрасывает кеш при изменении конфигурации. + * + * @param event Событие + */ + @EventListener + @CacheEvict(allEntries = true) + public void handleLanguageServerConfigurationChange(LanguageServerConfigurationChangedEvent event) { + // No-op. Служит для сброса кеша при изменении конфигурации + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isApplicable(DocumentContext documentContext) { + var uri = documentContext.getUri(); + var testSources = getSelf().getTestSources(documentContext.getServerContext().getConfigurationRoot()); + + return clientIsSupported + && documentContext.getFileType() == FileType.OS + && testSources.stream().anyMatch(testSource -> isInside(uri, testSource)); + } + + /** + * Получить self-injected экземпляр себя для работы механизмов кэширования. + * + * @return Управляемый Spring'ом экземпляр себя + */ + protected abstract AbstractRunTestsCodeLensSupplier getSelf(); + + /** + * Получить список каталогов с тестами с учетом корня рабочей области. + *

+ * public для работы @Cachable. + * + * @param configurationRoot Корень конфигурации + * @return Список исходных файлов тестов + */ + @Cacheable + public Set getTestSources(@Nullable Path configurationRoot) { + var configurationRootString = Optional.ofNullable(configurationRoot) + .map(Path::toString) + .orElse(""); + + return configuration.getCodeLensOptions().getTestRunnerAdapterOptions().getTestSources() + .stream() + .map(testDir -> Path.of(configurationRootString, testDir)) + .map(path -> Absolute.path(path).toUri()) + .collect(Collectors.toSet()); + } + + private static boolean isInside(URI childURI, URI parentURI) { + return !parentURI.relativize(childURI).isAbsolute(); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CodeLensData.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CodeLensData.java index 9baab40a82f..f32f001ee72 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CodeLensData.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CodeLensData.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CodeLensSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CodeLensSupplier.java index d249f68cc0c..44842fa3bef 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CodeLensSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CodeLensSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -46,6 +46,8 @@ */ public interface CodeLensSupplier { + String CODE_LENS_SUPPLIER_SUFFIX = "CodeLensSupplier"; + /** * Идентификатор сапплаера. Если линза содержит поле {@link CodeLens#getData()}, * идентификатор в данных линзы должен совпадать с данным идентификатором. @@ -54,8 +56,8 @@ public interface CodeLensSupplier { */ default String getId() { String simpleName = getClass().getSimpleName(); - if (simpleName.endsWith("CodeLensSupplier")) { - simpleName = simpleName.substring(0, simpleName.length() - "CodeLensSupplier".length()); + if (simpleName.endsWith(CODE_LENS_SUPPLIER_SUFFIX)) { + simpleName = simpleName.substring(0, simpleName.length() - CODE_LENS_SUPPLIER_SUFFIX.length()); simpleName = Introspector.decapitalize(simpleName); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CognitiveComplexityCodeLensSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CognitiveComplexityCodeLensSupplier.java index 851525faa7b..bbe60e7bb47 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CognitiveComplexityCodeLensSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CognitiveComplexityCodeLensSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,6 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.codelenses; +import com.github._1c_syntax.bsl.languageserver.commands.ToggleCognitiveComplexityInlayHintsCommandSupplier; 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; @@ -34,8 +35,11 @@ @Component public class CognitiveComplexityCodeLensSupplier extends AbstractMethodComplexityCodeLensSupplier { - public CognitiveComplexityCodeLensSupplier(LanguageServerConfiguration configuration) { - super(configuration); + public CognitiveComplexityCodeLensSupplier( + LanguageServerConfiguration configuration, + ToggleCognitiveComplexityInlayHintsCommandSupplier commandSupplier + ) { + super(configuration, commandSupplier); } @Override diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CyclomaticComplexityCodeLensSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CyclomaticComplexityCodeLensSupplier.java index 0356d9aa740..7c28e0911fc 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CyclomaticComplexityCodeLensSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CyclomaticComplexityCodeLensSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,6 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.codelenses; +import com.github._1c_syntax.bsl.languageserver.commands.ToggleCyclomaticComplexityInlayHintsCommandSupplier; 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; @@ -34,8 +35,11 @@ @Component public class CyclomaticComplexityCodeLensSupplier extends AbstractMethodComplexityCodeLensSupplier { - public CyclomaticComplexityCodeLensSupplier(LanguageServerConfiguration configuration) { - super(configuration); + public CyclomaticComplexityCodeLensSupplier( + LanguageServerConfiguration configuration, + ToggleCyclomaticComplexityInlayHintsCommandSupplier commandSupplier + ) { + super(configuration, commandSupplier); } @Override diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/DefaultCodeLensData.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/DefaultCodeLensData.java index 1976dc1d253..6a4a2fd1126 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/DefaultCodeLensData.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/DefaultCodeLensData.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,7 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.codelenses; -import com.github._1c_syntax.bsl.languageserver.codelenses.databind.URITypeAdapter; +import com.github._1c_syntax.bsl.languageserver.databind.URITypeAdapter; import com.google.gson.annotations.JsonAdapter; import lombok.Value; import lombok.experimental.NonFinal; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/RunAllTestsCodeLensSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/RunAllTestsCodeLensSupplier.java new file mode 100644 index 00000000000..48d4c5d1434 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/RunAllTestsCodeLensSupplier.java @@ -0,0 +1,133 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.codelenses; + +import com.github._1c_syntax.bsl.languageserver.codelenses.testrunner.TestRunnerAdapter; +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 com.github._1c_syntax.bsl.languageserver.utils.Resources; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.lsp4j.CodeLens; +import org.eclipse.lsp4j.Command; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +import java.nio.file.Paths; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * Поставщик линзы для запуска всех тестов в текущем файле. + */ +@Component +@Slf4j +public class RunAllTestsCodeLensSupplier + extends AbstractRunTestsCodeLensSupplier { + + private static final String COMMAND_ID = "language-1c-bsl.languageServer.runAllTests"; + + private final TestRunnerAdapter testRunnerAdapter; + private final Resources resources; + + // Self-injection для работы кэша в базовом классе. + @Autowired + @Lazy + @Getter + private RunAllTestsCodeLensSupplier self; + + public RunAllTestsCodeLensSupplier( + LanguageServerConfiguration configuration, + TestRunnerAdapter testRunnerAdapter, + Resources resources + ) { + super(configuration); + this.testRunnerAdapter = testRunnerAdapter; + this.resources = resources; + } + + /** + * {@inheritDoc} + */ + @Override + public List getCodeLenses(DocumentContext documentContext) { + + var testIds = testRunnerAdapter.getTestIds(documentContext); + + if (testIds.isEmpty()) { + return Collections.emptyList(); + } + + var methods = documentContext.getSymbolTree().getMethods(); + if (methods.isEmpty()) { + return Collections.emptyList(); + } + + var firstMethod = methods.get(0); + + return List.of(toCodeLens(firstMethod, documentContext)); + } + + /** + * {@inheritDoc} + */ + @Override + public CodeLens resolve(DocumentContext documentContext, CodeLens unresolved, DefaultCodeLensData data) { + var path = Paths.get(documentContext.getUri()); + + var options = configuration.getCodeLensOptions().getTestRunnerAdapterOptions(); + var executable = options.getExecutableForCurrentOS(); + String runText = executable + " " + options.getRunAllTestsArguments(); + runText = String.format(runText, path); + + var command = new Command(); + command.setTitle(resources.getResourceString(getClass(), "runAllTests")); + command.setCommand(COMMAND_ID); + command.setArguments(List.of(Map.of("text", runText))); + + unresolved.setCommand(command); + + return unresolved; + } + + /** + * {@inheritDoc} + */ + @Override + public Class getCodeLensDataClass() { + return DefaultCodeLensData.class; + } + + private CodeLens toCodeLens(MethodSymbol method, DocumentContext documentContext) { + + var codeLensData = new DefaultCodeLensData(documentContext.getUri(), getId()); + + var codeLens = new CodeLens(method.getSubNameRange()); + codeLens.setData(codeLensData); + + return codeLens; + } + +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/RunTestCodeLensSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/RunTestCodeLensSupplier.java new file mode 100644 index 00000000000..e084375c203 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/RunTestCodeLensSupplier.java @@ -0,0 +1,163 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.codelenses; + +import com.github._1c_syntax.bsl.languageserver.codelenses.testrunner.TestRunnerAdapter; +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.FileType; +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import com.github._1c_syntax.bsl.languageserver.utils.Resources; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.ToString; +import lombok.Value; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.lsp4j.CodeLens; +import org.eclipse.lsp4j.Command; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +import java.beans.ConstructorProperties; +import java.net.URI; +import java.nio.file.Paths; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * Поставщик линз для запуска теста по конкретному тестовому методу. + */ +@Component +@Slf4j +public class RunTestCodeLensSupplier + extends AbstractRunTestsCodeLensSupplier { + + private static final String COMMAND_ID = "language-1c-bsl.languageServer.runTest"; + + private final TestRunnerAdapter testRunnerAdapter; + private final Resources resources; + + // Self-injection для работы кэша в базовом классе. + @Autowired + @Lazy + @Getter + private RunTestCodeLensSupplier self; + + public RunTestCodeLensSupplier( + LanguageServerConfiguration configuration, + TestRunnerAdapter testRunnerAdapter, + Resources resources + ) { + super(configuration); + this.testRunnerAdapter = testRunnerAdapter; + this.resources = resources; + } + + /** + * {@inheritDoc} + */ + @Override + public List getCodeLenses(DocumentContext documentContext) { + + if (documentContext.getFileType() == FileType.BSL) { + return Collections.emptyList(); + } + + var testIds = testRunnerAdapter.getTestIds(documentContext); + var symbolTree = documentContext.getSymbolTree(); + + return testIds.stream() + .map(symbolTree::getMethodSymbol) + .flatMap(Optional::stream) + .map(methodSymbol -> toCodeLens(methodSymbol, documentContext)) + .toList(); + } + + /** + * {@inheritDoc} + */ + @Override + public Class getCodeLensDataClass() { + return RunTestCodeLensData.class; + } + + /** + * {@inheritDoc} + */ + @Override + public CodeLens resolve(DocumentContext documentContext, CodeLens unresolved, RunTestCodeLensData data) { + + var path = Paths.get(documentContext.getUri()); + var testId = data.getTestId(); + + var options = configuration.getCodeLensOptions().getTestRunnerAdapterOptions(); + var executable = options.getExecutableForCurrentOS(); + String runText = executable + " " + options.getRunTestArguments(); + runText = String.format(runText, path, testId); + + var command = new Command(); + command.setTitle(resources.getResourceString(getClass(), "runTest")); + command.setCommand(COMMAND_ID); + command.setArguments(List.of(Map.of("text", runText))); + + unresolved.setCommand(command); + + return unresolved; + } + + private CodeLens toCodeLens(MethodSymbol method, DocumentContext documentContext) { + var testId = method.getName(); + var codeLensData = new RunTestCodeLensData(documentContext.getUri(), getId(), testId); + + var codeLens = new CodeLens(method.getSubNameRange()); + codeLens.setData(codeLensData); + + return codeLens; + } + + /** + * DTO для хранения данных линз о сложности методов в документе. + */ + @Value + @EqualsAndHashCode(callSuper = true) + @ToString(callSuper = true) + public static class RunTestCodeLensData extends DefaultCodeLensData { + /** + * Имя метода. + */ + String testId; + + /** + * @param uri URI документа. + * @param id Идентификатор линзы. + * @param testId Идентификатор теста. + */ + @ConstructorProperties({"uri", "id", "testId"}) + public RunTestCodeLensData(URI uri, String id, String testId) { + super(uri, id); + this.testId = testId; + } + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/databind/CodeLensDataObjectMapper.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/databind/CodeLensDataObjectMapper.java deleted file mode 100644 index 7f1ecd561db..00000000000 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/databind/CodeLensDataObjectMapper.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * This file is a part of BSL Language Server. - * - * Copyright (c) 2018-2022 - * Alexey Sosnoviy , Nikita Fedkin 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.codelenses.databind; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.jsontype.NamedType; -import com.github._1c_syntax.bsl.languageserver.codelenses.CodeLensData; -import com.github._1c_syntax.bsl.languageserver.codelenses.CodeLensSupplier; -import org.springframework.stereotype.Component; - -import java.util.List; - -/** - * Преднастроенный экземпляр {@link ObjectMapper} для десериализации {@link CodeLensData}. - */ -@Component -public class CodeLensDataObjectMapper extends ObjectMapper { - - private static final long serialVersionUID = 8904131809077953315L; - - public CodeLensDataObjectMapper(List> codeLensResolvers) { - super(); - - codeLensResolvers.stream() - .map(CodeLensDataObjectMapper::toNamedType) - .forEach(this::registerSubtypes); - } - - private static NamedType toNamedType(CodeLensSupplier codeLensSupplier) { - return new NamedType(codeLensSupplier.getCodeLensDataClass(), codeLensSupplier.getId()); - } -} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/infrastructure/CodeLensesConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/infrastructure/CodeLensesConfiguration.java index ba1c22f0579..abdbe59a0d5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/infrastructure/CodeLensesConfiguration.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/infrastructure/CodeLensesConfiguration.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/infrastructure/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/infrastructure/package-info.java index ef3110f6ce2..c5b8c6fb6d5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/infrastructure/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/infrastructure/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,7 +23,8 @@ * Spring-специфичные классы для настройки внутренней инфраструктуры * пакета {@link com.github._1c_syntax.bsl.languageserver.codelenses}. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.codelenses.infrastructure; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/package-info.java index 7c51585d1a6..6236a336560 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,7 +23,8 @@ * Пакет предназначен для реализации различных видов линз ("code lenses"), * используемых {@link com.github._1c_syntax.bsl.languageserver.providers.CodeLensProvider}. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.codelenses; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/testrunner/TestRunnerAdapter.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/testrunner/TestRunnerAdapter.java new file mode 100644 index 00000000000..1e5d2b6c592 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/testrunner/TestRunnerAdapter.java @@ -0,0 +1,161 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.codelenses.testrunner; + +import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; +import com.github._1c_syntax.bsl.languageserver.configuration.events.LanguageServerConfigurationChangedEvent; +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.annotations.Annotation; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.exec.CommandLine; +import org.apache.commons.exec.DefaultExecuteResultHandler; +import org.apache.commons.exec.DefaultExecutor; +import org.apache.commons.exec.ExecuteWatchdog; +import org.apache.commons.exec.PumpStreamHandler; +import org.apache.commons.io.output.ByteArrayOutputStream; +import org.apache.commons.lang3.SystemUtils; +import org.springframework.cache.annotation.CacheConfig; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Paths; +import java.time.Duration; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Расчетчик списка тестов в документе. + * Физически выполняет команды по получению идентификаторов тестов на основании конфигурации. + */ +@Component +@RequiredArgsConstructor +@Slf4j +@CacheConfig(cacheNames = "testIds") +public class TestRunnerAdapter { + + private static final Pattern NEW_LINE_PATTERN = Pattern.compile("\r?\n"); + + private final LanguageServerConfiguration configuration; + + /** + * Обработчик события {@link LanguageServerConfigurationChangedEvent}. + *

+ * Очищает кэш при изменении конфигурации. + * + * @param event Событие + */ + @EventListener + @CacheEvict(allEntries = true) + public void handleEvent(LanguageServerConfigurationChangedEvent event) { + // No-op. Служит для сброса кеша при изменении конфигурации + } + + /** + * Получить идентификаторы тестов, содержащихся в файле. + * + * @param documentContext Контекст документа с тестами. + * @return Список идентификаторов тестов. + */ + @Cacheable + public List getTestIds(DocumentContext documentContext) { + var options = configuration.getCodeLensOptions().getTestRunnerAdapterOptions(); + + if (options.isGetTestsByTestRunner()) { + return computeTestIdsByTestRunner(documentContext); + } + + return computeTestIdsByLanguageServer(documentContext); + } + + private List computeTestIdsByTestRunner(DocumentContext documentContext) { + var options = configuration.getCodeLensOptions().getTestRunnerAdapterOptions(); + + var executable = SystemUtils.IS_OS_WINDOWS ? options.getExecutableWin() : options.getExecutable(); + var path = Paths.get(documentContext.getUri()).toString(); + var arguments = String.format(options.getGetTestsArguments(), path); + + var getTestsCommand = new CommandLine(executable).addArguments(arguments, false); + + var timeout = 10_000L; + var watchdog = ExecuteWatchdog.builder().setTimeout(Duration.ofMillis(timeout)).get(); + + var outputStream = new ByteArrayOutputStream(); + var streamHandler = new PumpStreamHandler(outputStream); + + var resultHandler = new DefaultExecuteResultHandler(); + + var executor = DefaultExecutor.builder().get(); + executor.setWatchdog(watchdog); + executor.setStreamHandler(streamHandler); + + try { + executor.execute(getTestsCommand, resultHandler); + } catch (IOException e) { + LOGGER.error("Can't execute testrunner getTests command", e); + return Collections.emptyList(); + } + try { + resultHandler.waitFor(); + } catch (InterruptedException e) { + LOGGER.error("Can't wait for testrunner getTests command", e); + Thread.currentThread().interrupt(); + return Collections.emptyList(); + } + + var getTestsRegex = Pattern.compile(options.getGetTestsResultPattern()); + + Charset charset; + if (SystemUtils.IS_OS_WINDOWS) { + charset = Charset.forName("cp866"); + } else { + charset = Charset.defaultCharset(); + } + var output = outputStream.toString(charset); + + return Arrays.stream(NEW_LINE_PATTERN.split(output)) + .map(getTestsRegex::matcher) + .filter(Matcher::matches) + .map(matcher -> matcher.group(1)) + .toList(); + } + + private List computeTestIdsByLanguageServer(DocumentContext documentContext) { + var annotations = configuration.getCodeLensOptions().getTestRunnerAdapterOptions().getAnnotations(); + return documentContext.getSymbolTree() + .getMethods() + .stream() + .filter(methodSymbol -> methodSymbol.getAnnotations().stream() + .map(Annotation::getName) + .anyMatch(annotations::contains)) + .map(MethodSymbol::getName) + .toList(); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/databind/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/testrunner/package-info.java similarity index 71% rename from src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/databind/package-info.java rename to src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/testrunner/package-info.java index d1478cbc737..75fa5e6d12f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/databind/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/testrunner/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -20,10 +20,10 @@ * License along with BSL Language Server. */ /** - * Сериализация и десериализация классов пакета - * {@link com.github._1c_syntax.bsl.languageserver.codelenses}. + * Запуск инструментов тестирования. */ -@ParametersAreNonnullByDefault -package com.github._1c_syntax.bsl.languageserver.codelenses.databind; +@DefaultAnnotation(NonNull.class) +package com.github._1c_syntax.bsl.languageserver.codelenses.testrunner; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/BSLColor.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/BSLColor.java index 6043d6b6b9c..139356c565a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/BSLColor.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/BSLColor.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/ColorInformationSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/ColorInformationSupplier.java index b6fd5dd1068..8f5526a4a04 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/ColorInformationSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/ColorInformationSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/ColorPresentationSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/ColorPresentationSupplier.java index a906bb5a747..cd7c376c2dd 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/ColorPresentationSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/ColorPresentationSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/ConstructorColorInformationSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/ConstructorColorInformationSupplier.java index 5f1df21f905..4afd6e6db8c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/ConstructorColorInformationSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/ConstructorColorInformationSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,6 +24,7 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import com.github._1c_syntax.bsl.languageserver.utils.Trees; +import com.github._1c_syntax.bsl.languageserver.utils.bsl.Constructors; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.utils.CaseInsensitivePattern; import org.antlr.v4.runtime.Token; @@ -46,7 +47,6 @@ @Component public class ConstructorColorInformationSupplier implements ColorInformationSupplier { - private static final Pattern QUOTE_PATTERN = Pattern.compile("\""); private static final Pattern COLOR_PATTERN = CaseInsensitivePattern.compile("^(?:Цвет|Color)$"); @Override @@ -58,23 +58,11 @@ public List getColorInformation(DocumentContext documentContex return newExpressions.stream() .map(BSLParser.NewExpressionContext.class::cast) - .filter(newExpression -> COLOR_PATTERN.matcher(typeName(newExpression)).matches()) + .filter(newExpression -> Constructors.typeName(newExpression).filter(name -> COLOR_PATTERN.matcher(name).matches()).isPresent()) .map(ConstructorColorInformationSupplier::toColorInformation) .collect(Collectors.toList()); } - private static String typeName(BSLParser.NewExpressionContext ctx) { - if (ctx.typeName() != null) { - return ctx.typeName().getText(); - } - - if (ctx.doCall() == null || ctx.doCall().callParamList().isEmpty()) { - return ""; - } - - return QUOTE_PATTERN.matcher(ctx.doCall().callParamList().callParam(0).getText()).replaceAll(""); - } - private static ColorInformation toColorInformation(BSLParser.NewExpressionContext ctx) { byte redPosition; byte greenPosition; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/ConstructorColorPresentationSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/ConstructorColorPresentationSupplier.java index cd00ab01206..5810f53018f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/ConstructorColorPresentationSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/ConstructorColorPresentationSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/WebColor.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/WebColor.java index 83e77b94b1b..7d0177dbb29 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/WebColor.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/WebColor.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/WebColorInformationSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/WebColorInformationSupplier.java index ecea3472797..7c6e9249ad0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/WebColorInformationSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/WebColorInformationSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/WebColorPresentationSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/WebColorPresentationSupplier.java index ca0abb91481..517ff9413f2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/WebColorPresentationSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/WebColorPresentationSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/package-info.java index 122ecf253ab..d4d36609839 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/color/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,7 +23,8 @@ * Пакет предназначен для реализации различных видов представления цвета ("documentColor" и "colorPresentation"), * используемых {@link com.github._1c_syntax.bsl.languageserver.providers.ColorProvider}. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.color; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/CommandArguments.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/CommandArguments.java new file mode 100644 index 00000000000..b7aaa9999d7 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/CommandArguments.java @@ -0,0 +1,54 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.commands; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonTypeInfo; + +import java.net.URI; + +import static com.fasterxml.jackson.annotation.JsonTypeInfo.As.EXISTING_PROPERTY; +import static com.fasterxml.jackson.annotation.JsonTypeInfo.Id.NAME; + +/** + * Интерфейс DTO для хранения промежуточных данных команд между созданием команды и ее выполнением. + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonTypeInfo(use = NAME, include = EXISTING_PROPERTY, property = "id", visible = true) +public interface CommandArguments { + /** + * URI документа, с которым связана команда. + * + * @return URI документа, с которым связана команда. + */ + URI getUri(); + + /** + * Идентификатор команды. + *

+ * Должен совпадать с {@link CommandSupplier#getId()} сапплаера, + * создающего команду. + * + * @return Идентификатор команды. + */ + String getId(); +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/CommandSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/CommandSupplier.java new file mode 100644 index 00000000000..8f2bae8f88b --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/CommandSupplier.java @@ -0,0 +1,106 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.commands; + +import org.eclipse.lsp4j.Command; + +import java.beans.Introspector; +import java.util.List; +import java.util.Optional; + +/** + * Базовый интерфейс для наполнения {@link com.github._1c_syntax.bsl.languageserver.providers.CommandProvider} + * данными о доступных в документе командах. + *

+ * Конкретный сапплаер может расширить состав данных, передаваемых в аргументах команды, доопределив дата-класс, + * наследующий {@link CommandArguments}, и указав его тип в качестве типа-параметра класса. + * + * @param Конкретный тип для аргументов команды. + */ + +public interface CommandSupplier { + + String COMMAND_SUPPLIER_SUFFIX = "CommandSupplier"; + + /** + * Идентификатор сапплаера. + *

+ * Идентификатор в аргументах команды должен совпадать с данным идентификатором. + * + * @return Идентификатор сапплаера. + */ + default String getId() { + String simpleName = getClass().getSimpleName(); + if (simpleName.endsWith(COMMAND_SUPPLIER_SUFFIX)) { + simpleName = simpleName.substring(0, simpleName.length() - COMMAND_SUPPLIER_SUFFIX.length()); + simpleName = Introspector.decapitalize(simpleName); + } + + return simpleName; + } + + /** + * Создать DTO команды. + * + * @param title Заголовок команды. + * @param arguments Аргументы команды. + * @return Команда с заполненными заголовком и идентификатором команды. + */ + default Command createCommand(String title, T arguments) { + return new Command(title, getId(), List.of(arguments)); + } + + /** + * Получить класс для аргументов команды. + * + * @return Конкретный класс для аргументов команды. + */ + Class getCommandArgumentsClass(); + + /** + * Выполнить серверную команду. + * + * @param arguments Аргументы команды. + * + * @return Результат выполнения команды. + */ + Optional execute(T arguments); + + /** + * Флаг, показывающий необходимость обновить inlay hints после выполнения команды. + * + * @return Флаг, показывающий необходимость обновить inlay hints после выполнения команды. + */ + default boolean needRefreshInlayHintsAfterExecuteCommand() { + return false; + } + + /** + * Флаг, показывающий необходимость обновить линзы после выполнения команды. + * + * @return Флаг, показывающий необходимость обновить линзы после выполнения команды. + */ + default boolean needRefreshCodeLensesAfterExecuteCommand() { + return false; + } + +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/DefaultCommandArguments.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/DefaultCommandArguments.java new file mode 100644 index 00000000000..e7bf4bb8609 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/DefaultCommandArguments.java @@ -0,0 +1,40 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.commands; + +import com.github._1c_syntax.bsl.languageserver.databind.URITypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import lombok.Value; +import lombok.experimental.NonFinal; + +import java.net.URI; + +/** + * DTO для хранения промежуточных данных команд между созданием команды и ее выполнением. + */ +@Value +@NonFinal +public class DefaultCommandArguments implements CommandArguments { + @JsonAdapter(URITypeAdapter.class) + URI uri; + String id; +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/ToggleCognitiveComplexityInlayHintsCommandSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/ToggleCognitiveComplexityInlayHintsCommandSupplier.java new file mode 100644 index 00000000000..9899f17261a --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/ToggleCognitiveComplexityInlayHintsCommandSupplier.java @@ -0,0 +1,40 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.commands; + +import com.github._1c_syntax.bsl.languageserver.commands.complexity.AbstractToggleComplexityInlayHintsCommandSupplier; +import com.github._1c_syntax.bsl.languageserver.inlayhints.CognitiveComplexityInlayHintSupplier; +import org.springframework.stereotype.Component; + +/** + * Поставщик команды переключения подсказок когнитивной сложности. + */ +@Component +public class ToggleCognitiveComplexityInlayHintsCommandSupplier + extends AbstractToggleComplexityInlayHintsCommandSupplier { + + public ToggleCognitiveComplexityInlayHintsCommandSupplier( + CognitiveComplexityInlayHintSupplier complexityInlayHintSupplier + ) { + super(complexityInlayHintSupplier); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/ToggleCyclomaticComplexityInlayHintsCommandSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/ToggleCyclomaticComplexityInlayHintsCommandSupplier.java new file mode 100644 index 00000000000..563eba66652 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/ToggleCyclomaticComplexityInlayHintsCommandSupplier.java @@ -0,0 +1,40 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.commands; + +import com.github._1c_syntax.bsl.languageserver.commands.complexity.AbstractToggleComplexityInlayHintsCommandSupplier; +import com.github._1c_syntax.bsl.languageserver.inlayhints.CyclomaticComplexityInlayHintSupplier; +import org.springframework.stereotype.Component; + +/** + * Поставщик команды переключения подсказок цикломатической сложности. + */ +@Component +public class ToggleCyclomaticComplexityInlayHintsCommandSupplier + extends AbstractToggleComplexityInlayHintsCommandSupplier { + + public ToggleCyclomaticComplexityInlayHintsCommandSupplier( + CyclomaticComplexityInlayHintSupplier complexityInlayHintSupplier + ) { + super(complexityInlayHintSupplier); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/complexity/AbstractToggleComplexityInlayHintsCommandSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/complexity/AbstractToggleComplexityInlayHintsCommandSupplier.java new file mode 100644 index 00000000000..766a7782653 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/complexity/AbstractToggleComplexityInlayHintsCommandSupplier.java @@ -0,0 +1,66 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.commands.complexity; + +import com.github._1c_syntax.bsl.languageserver.commands.CommandSupplier; +import com.github._1c_syntax.bsl.languageserver.inlayhints.AbstractComplexityInlayHintSupplier; +import lombok.RequiredArgsConstructor; + +import java.util.Optional; + +/** + * Базовый класс для поставщиков команды переключения подсказок сложности. + */ +@RequiredArgsConstructor +public abstract class AbstractToggleComplexityInlayHintsCommandSupplier + implements CommandSupplier { + + private final AbstractComplexityInlayHintSupplier complexityInlayHintSupplier; + + /** + * Получение класса аргументов команды. + * + * @return Класс аргументов команды. + */ + @Override + public Class getCommandArgumentsClass() { + return ToggleComplexityInlayHintsCommandArguments.class; + } + + /** + * {@inheritDoc} + */ + @Override + public Optional execute(ToggleComplexityInlayHintsCommandArguments arguments) { + complexityInlayHintSupplier.toggleHints(arguments.getUri(), arguments.getMethodName()); + return Optional.empty(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean needRefreshInlayHintsAfterExecuteCommand() { + return true; + } + +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/complexity/ToggleComplexityInlayHintsCommandArguments.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/complexity/ToggleComplexityInlayHintsCommandArguments.java new file mode 100644 index 00000000000..8c8a3424a18 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/complexity/ToggleComplexityInlayHintsCommandArguments.java @@ -0,0 +1,57 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.commands.complexity; + +import com.github._1c_syntax.bsl.languageserver.codelenses.AbstractMethodComplexityCodeLensSupplier; +import com.github._1c_syntax.bsl.languageserver.commands.DefaultCommandArguments; +import lombok.EqualsAndHashCode; +import lombok.ToString; +import lombok.Value; + +import java.beans.ConstructorProperties; +import java.net.URI; + +/** + * Аргументы команды для переключения отображения сложности метода во всплывающих подсказках. + */ +@Value +@EqualsAndHashCode(callSuper = true) +@ToString(callSuper = true) +public class ToggleComplexityInlayHintsCommandArguments extends DefaultCommandArguments { + /** + * Имя метода. + */ + String methodName; + + @ConstructorProperties({"uri", "id", "methodName"}) + public ToggleComplexityInlayHintsCommandArguments(URI uri, String id, String methodName) { + super(uri, id); + this.methodName = methodName; + } + + public ToggleComplexityInlayHintsCommandArguments( + String id, + AbstractMethodComplexityCodeLensSupplier.ComplexityCodeLensData data + ) { + this(data.getUri(), id, data.getMethodName()); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/complexity/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/complexity/package-info.java new file mode 100644 index 00000000000..79cc8eb144e --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/complexity/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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. + */ +/** + * Служебные классы команд, связанные с показом сложности методов. + */ +@DefaultAnnotation(NonNull.class) +package com.github._1c_syntax.bsl.languageserver.commands.complexity; + +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/infrastructure/CommandsConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/infrastructure/CommandsConfiguration.java new file mode 100644 index 00000000000..4c01dc50994 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/infrastructure/CommandsConfiguration.java @@ -0,0 +1,57 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.commands.infrastructure; + +import com.github._1c_syntax.bsl.languageserver.commands.CommandArguments; +import com.github._1c_syntax.bsl.languageserver.commands.CommandSupplier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.Collection; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * Spring-конфигурация для определения бинов + * пакета {@link com.github._1c_syntax.bsl.languageserver.commands}. + */ +@Configuration +public class CommandsConfiguration { + + /** + * Получить список сапплаеров команд в разрезе их идентификаторов. + * + * @param commandSuppliers Плоский список сапплаеров. + * @return Список сапплаеров линз в разрезе их идентификаторов. + */ + @Bean + @SuppressWarnings("unchecked") + public Map> commandSuppliersById( + Collection> commandSuppliers + ) { + return commandSuppliers.stream() + .map(commandSupplier -> (CommandSupplier) commandSupplier) + .collect(Collectors.toMap(CommandSupplier::getId, Function.identity())); + } + +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/infrastructure/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/infrastructure/package-info.java new file mode 100644 index 00000000000..aaa02aa0906 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/infrastructure/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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. + */ +/** + * Spring-специфичные классы для настройки внутренней инфраструктуры + * пакета {@link com.github._1c_syntax.bsl.languageserver.commands}. + */ +@DefaultAnnotation(NonNull.class) +package com.github._1c_syntax.bsl.languageserver.commands.infrastructure; + +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/package-info.java new file mode 100644 index 00000000000..c496e37738e --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/commands/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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. + */ +/** + * Пакет предназначен для реализации команд, + * используемых {@link com.github._1c_syntax.bsl.languageserver.providers.CommandProvider}. + */ +@DefaultAnnotation(NonNull.class) +package com.github._1c_syntax.bsl.languageserver.commands; + +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/Language.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/Language.java index e9fd22b2a80..34499babde5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/Language.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/Language.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,6 +29,7 @@ * Язык для сообщений, ресурсов и прочих взаимодействий между * BSL Language Server и пользователем. */ +@Getter public enum Language { /** @@ -49,13 +50,11 @@ public enum Language { /** * Код языка в соответствии с {@link java.util.Locale#getLanguage()}. */ - @Getter private final String languageCode; /** * Локаль языка. */ - @Getter private final Locale locale; /** diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java index e1e9f171168..ab8b70cc372 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfiguration.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -30,10 +30,15 @@ import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.DiagnosticsOptions; import com.github._1c_syntax.bsl.languageserver.configuration.documentlink.DocumentLinkOptions; import com.github._1c_syntax.bsl.languageserver.configuration.formating.FormattingOptions; +import com.github._1c_syntax.bsl.languageserver.configuration.inlayhints.InlayHintOptions; import com.github._1c_syntax.utils.Absolute; +import edu.umd.cs.findbugs.annotations.Nullable; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import jakarta.annotation.PostConstruct; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Data; +import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.SneakyThrows; @@ -44,8 +49,6 @@ import org.springframework.context.annotation.Role; import org.springframework.stereotype.Component; -import javax.annotation.Nullable; -import javax.annotation.PostConstruct; import java.io.File; import java.io.IOException; import java.nio.file.Files; @@ -54,7 +57,6 @@ import java.util.List; import java.util.Optional; import java.util.regex.Pattern; -import java.util.stream.Collectors; import java.util.stream.Stream; import static com.fasterxml.jackson.databind.MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS; @@ -90,6 +92,10 @@ public class LanguageServerConfiguration { @Setter(value = AccessLevel.NONE) private DocumentLinkOptions documentLinkOptions = new DocumentLinkOptions(); + @JsonProperty("inlayHint") + @Setter(value = AccessLevel.NONE) + private InlayHintOptions inlayHintOptions = new InlayHintOptions(); + @JsonProperty("formatting") @Setter(value = AccessLevel.NONE) private FormattingOptions formattingOptions = new FormattingOptions(); @@ -110,10 +116,14 @@ public class LanguageServerConfiguration { private File configurationFile; @Value("${app.configuration.path:.bsl-language-server.json}") + @Getter(value=AccessLevel.NONE) + @Setter(value=AccessLevel.NONE) @JsonIgnore private String configurationFilePath; @Value(("${app.globalConfiguration.path:${user.home}/.bsl-language-server.json}")) + @Getter(value=AccessLevel.NONE) + @Setter(value=AccessLevel.NONE) @JsonIgnore private String globalConfigPath; @@ -141,7 +151,7 @@ public void reset() { public static Path getCustomConfigurationRoot(LanguageServerConfiguration configuration, Path srcDir) { Path rootPath = null; - Path pathFromConfiguration = configuration.getConfigurationRoot(); + var pathFromConfiguration = configuration.getConfigurationRoot(); if (pathFromConfiguration == null) { rootPath = Absolute.path(srcDir); @@ -155,7 +165,7 @@ public static Path getCustomConfigurationRoot(LanguageServerConfiguration config } if (rootPath != null) { - File fileConfiguration = getConfigurationFile(rootPath); + var fileConfiguration = getConfigurationFile(rootPath); if (fileConfiguration != null) { if (fileConfiguration.getAbsolutePath().endsWith(".mdo")) { rootPath = Optional.of(fileConfiguration.toPath()) @@ -172,15 +182,18 @@ public static Path getCustomConfigurationRoot(LanguageServerConfiguration config } return rootPath; - } + @SuppressFBWarnings( + value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", + justification = "False positive" + ) private static File getConfigurationFile(Path rootPath) { File configurationFile = null; List listPath = new ArrayList<>(); try (Stream stream = Files.find(rootPath, 50, (path, basicFileAttributes) -> basicFileAttributes.isRegularFile() && searchConfiguration.matcher(path.getFileName().toString()).find())) { - listPath = stream.collect(Collectors.toList()); + listPath = stream.toList(); } catch (IOException e) { LOGGER.error("Error on read configuration file", e); } @@ -209,7 +222,6 @@ private void loadConfigurationFile(File configurationFile) { } this.configurationFile = configurationFile; - copyPropertiesFrom(configuration); } @@ -217,10 +229,10 @@ private void loadConfigurationFile(File configurationFile) { private void copyPropertiesFrom(LanguageServerConfiguration configuration) { // todo: refactor PropertyUtils.copyProperties(this, configuration); + PropertyUtils.copyProperties(this.inlayHintOptions, configuration.inlayHintOptions); PropertyUtils.copyProperties(this.codeLensOptions, configuration.codeLensOptions); PropertyUtils.copyProperties(this.diagnosticsOptions, configuration.diagnosticsOptions); PropertyUtils.copyProperties(this.documentLinkOptions, configuration.documentLinkOptions); PropertyUtils.copyProperties(this.formattingOptions, configuration.formattingOptions); } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/SendErrorsMode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/SendErrorsMode.java index 52bee5e3af6..76e21a37521 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/SendErrorsMode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/SendErrorsMode.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/CodeLensOptions.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/CodeLensOptions.java index f00115a4472..7f6d07a6e5d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/CodeLensOptions.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/CodeLensOptions.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,6 +23,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.github._1c_syntax.bsl.languageserver.configuration.databind.ParametersDeserializer; import lombok.AllArgsConstructor; @@ -47,4 +48,10 @@ public class CodeLensOptions { */ @JsonDeserialize(using = ParametersDeserializer.class) private Map>> parameters = new HashMap<>(); + + /** + * Параметры запускателя тестового фреймворка. + */ + @JsonProperty("testRunner") + private TestRunnerAdapterOptions testRunnerAdapterOptions = new TestRunnerAdapterOptions(); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/TestRunnerAdapterOptions.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/TestRunnerAdapterOptions.java new file mode 100644 index 00000000000..85bd30c0986 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/TestRunnerAdapterOptions.java @@ -0,0 +1,106 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.configuration.codelens; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.github._1c_syntax.bsl.languageserver.configuration.databind.AnnotationsDeserializer; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.apache.commons.lang3.SystemUtils; + +import java.util.Collections; +import java.util.Set; +import java.util.TreeSet; + +/** + * Параметры запускателя тестового фреймворка. + */ +@Data +@AllArgsConstructor(onConstructor = @__({@JsonCreator(mode = JsonCreator.Mode.DISABLED)})) +@NoArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class TestRunnerAdapterOptions { + + public static final Set DEFAULT_ANNOTATIONS = getDefaultAnnotations(); + + /** + * Каталоги с исходными файлами тестов. + */ + private Set testSources = Set.of("tests"); + + /** + * Имена аннотаций, маркирующих тесты. + *

+ * Используется при получении списка тестов средствами сервера. + */ + @JsonDeserialize(using = AnnotationsDeserializer.class) + private Set annotations = DEFAULT_ANNOTATIONS; + + /** + * Имя исполняемого файла тестового фреймворка (linux и macOS). + */ + private String executable = "1testrunner"; + /** + * Имя исполняемого файла тестового фреймворка (windows). + */ + private String executableWin = "1testrunner.bat"; + /** + * Флаг, указывающий на необходимость получения списка тестов через исполняемый файл тестового фреймворка. + */ + private boolean getTestsByTestRunner = true; + /** + * Аргументы для получения списка тестов. + */ + private String getTestsArguments = "-show %s"; + /** + * Регулярное выражение для получения списка тестов. + */ + private String getTestsResultPattern = "^[^<]*Имя\\sтеста\\s<([^>]+)>.*"; + /** + * Аргументы для запуска одного теста. + */ + private String runTestArguments = "-run %s %s"; + /** + * Аргументы для запуска всех тестов. + */ + private String runAllTestsArguments = "-run %s"; + + /** + * Получить имя исполняемого файла тестового фреймворка для текущей ОС. + * + * @return Имя исполняемого файла тестового фреймворка для текущей ОС. + */ + public String getExecutableForCurrentOS() { + return SystemUtils.IS_OS_WINDOWS ? executableWin : executable; + } + + private static Set getDefaultAnnotations() { + Set annotations = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); + annotations.add("Test"); + annotations.add("Тест"); + + return Collections.unmodifiableSet(annotations); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/package-info.java index 95b81b3cf76..3956b2aa599 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/codelens/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/databind/AnnotationsDeserializer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/databind/AnnotationsDeserializer.java new file mode 100644 index 00000000000..2788f534829 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/databind/AnnotationsDeserializer.java @@ -0,0 +1,62 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.configuration.databind; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; + +import java.io.IOException; +import java.util.Set; +import java.util.TreeSet; + +import static com.github._1c_syntax.bsl.languageserver.configuration.codelens.TestRunnerAdapterOptions.DEFAULT_ANNOTATIONS; + +/** + * Служебный класс-десериализатор для регистронезависимого списка имен аннотаций. + */ +@Slf4j +public class AnnotationsDeserializer extends JsonDeserializer> { + + @Override + public Set deserialize( + JsonParser p, + DeserializationContext context + ) throws IOException { + + JsonNode annotations = p.getCodec().readTree(p); + + if (annotations == null) { + return DEFAULT_ANNOTATIONS; + } + + Set annotationsSet = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); + var objectMapper = (ObjectMapper) p.getCodec(); + objectMapper.readerForUpdating(annotationsSet).readValue(annotations); + + return annotationsSet; + } + +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/databind/ParametersDeserializer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/databind/ParametersDeserializer.java index 68c249e0bb7..bd1e8937cd6 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/databind/ParametersDeserializer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/databind/ParametersDeserializer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/databind/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/databind/package-info.java index 4ff5332e5bc..a4bb7fa6fe1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/databind/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/databind/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,7 +23,8 @@ * Сериализация и десериализация верхнеуровневых или общих частей * {@link com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration}. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.configuration.databind; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/ComputeTrigger.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/ComputeTrigger.java index f27527cc606..676a3439c0c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/ComputeTrigger.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/ComputeTrigger.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java index 7f644124ca6..e2d9cc8731d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/DiagnosticsOptions.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java index 4c2b7a94c2a..12cfd09ca0d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/Mode.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/SkipSupport.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/SkipSupport.java index 55d4aba7ea1..a6279c4601c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/SkipSupport.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/SkipSupport.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/SubsystemFilter.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/SubsystemFilter.java index 95247601054..997c3bdd1a6 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/SubsystemFilter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/SubsystemFilter.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/package-info.java index 83abd02302a..22d2b5b05e6 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/diagnostics/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/DocumentLinkOptions.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/DocumentLinkOptions.java index 6d4ef5b66af..8ee145bd794 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/DocumentLinkOptions.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/DocumentLinkOptions.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/package-info.java index 179198bcdbf..863a8c4fd63 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/documentlink/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/events/LanguageServerConfigurationChangedEvent.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/events/LanguageServerConfigurationChangedEvent.java index 42a2245f7ac..ae4fb59574b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/events/LanguageServerConfigurationChangedEvent.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/events/LanguageServerConfigurationChangedEvent.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/events/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/events/package-info.java index 2721bb795c3..4cf58ecd361 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/events/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/events/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,7 +22,8 @@ /** * События пакета com.github._1c_syntax.bsl.languageserver.configuration. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.configuration.events; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/formating/FormattingOptions.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/formating/FormattingOptions.java index 25ee969c4bf..aebb2d2fa8f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/formating/FormattingOptions.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/formating/FormattingOptions.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/formating/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/formating/package-info.java index de7689a5aae..84b784bf8fd 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/formating/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/formating/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/inlayhints/InlayHintOptions.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/inlayhints/InlayHintOptions.java new file mode 100644 index 00000000000..84d0bda3a78 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/inlayhints/InlayHintOptions.java @@ -0,0 +1,50 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.configuration.inlayhints; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.github._1c_syntax.bsl.languageserver.configuration.databind.ParametersDeserializer; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.eclipse.lsp4j.jsonrpc.messages.Either; + +import java.util.HashMap; +import java.util.Map; + +/** + * Корневой класс для настройки {@link com.github._1c_syntax.bsl.languageserver.providers.InlayHintProvider} + */ +@Data +@AllArgsConstructor(onConstructor = @__({@JsonCreator(mode = JsonCreator.Mode.DISABLED)})) +@NoArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class InlayHintOptions { + + /** + * Параметры сапплаеров inlay hints. + */ + @JsonDeserialize(using = ParametersDeserializer.class) + private Map>> parameters = new HashMap<>(); +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/inlayhints/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/inlayhints/package-info.java new file mode 100644 index 00000000000..a925f04ec6a --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/inlayhints/package-info.java @@ -0,0 +1,29 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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. + */ +/** + * Пакет содержит настройки {@link com.github._1c_syntax.bsl.languageserver.providers.InlayHintProvider} + */ +@DefaultAnnotation(NonNull.class) +package com.github._1c_syntax.bsl.languageserver.configuration.inlayhints; + +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/package-info.java index 9fbcd048625..5b06520021a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/watcher/ConfigurationFileChangeListener.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/watcher/ConfigurationFileChangeListener.java index e02b5c6844e..f812629d677 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/watcher/ConfigurationFileChangeListener.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/watcher/ConfigurationFileChangeListener.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/watcher/ConfigurationFileSystemWatcher.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/watcher/ConfigurationFileSystemWatcher.java index 5b1a2fed865..fa03a1aeeee 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/watcher/ConfigurationFileSystemWatcher.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/watcher/ConfigurationFileSystemWatcher.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -25,6 +25,8 @@ import com.github._1c_syntax.bsl.languageserver.configuration.events.LanguageServerConfigurationChangedEvent; import com.github._1c_syntax.utils.Absolute; import com.sun.nio.file.SensitivityWatchEventModifier; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.Synchronized; @@ -33,8 +35,6 @@ import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; @@ -56,6 +56,7 @@ @Component @Slf4j @RequiredArgsConstructor +@SuppressWarnings("removal") // SensitivityWatchEventModifier is deprecated in jdk21 public class ConfigurationFileSystemWatcher { private final LanguageServerConfiguration configuration; @@ -117,6 +118,10 @@ public void handleEvent(LanguageServerConfigurationChangedEvent event) { private void registerWatchService(File configurationFile) { Path configurationDir = Absolute.path(configurationFile).getParent(); + if (configurationDir == null) { + return; + } + if (configurationDir.equals(registeredPath)) { return; } @@ -127,6 +132,8 @@ private void registerWatchService(File configurationFile) { registeredPath = configurationDir; + // TODO: SensitivityWatchEventModifier is deprecated in java 21 and marked for removal. + // We need to drop usage of it here when we change our baseline to jdk 21 watchKey = registeredPath.register( watchService, new WatchEvent.Kind[]{ diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/watcher/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/watcher/package-info.java index bb55781ed62..2e778112c2c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/watcher/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/configuration/watcher/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,7 +23,8 @@ * В пакете содержатся классы, относящиеся к отслеживанию факта изменения (удаление, создание, редактирование) файла * конфигурации ({@link com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration}). */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.configuration.watcher; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java index 3f936c90aa0..26a112d8448 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContext.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -33,18 +33,22 @@ import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; import com.github._1c_syntax.bsl.languageserver.context.symbol.SymbolTree; import com.github._1c_syntax.bsl.languageserver.utils.Trees; +import com.github._1c_syntax.bsl.mdo.MD; import com.github._1c_syntax.bsl.mdo.support.ScriptVariant; import com.github._1c_syntax.bsl.parser.BSLLexer; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLTokenizer; import com.github._1c_syntax.bsl.parser.SDBLTokenizer; -import com.github._1c_syntax.bsl.supconf.SupportConfiguration; import com.github._1c_syntax.bsl.support.SupportVariant; import com.github._1c_syntax.bsl.types.ConfigurationSource; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; import com.github._1c_syntax.utils.Lazy; +import edu.umd.cs.findbugs.annotations.NonNull; +import edu.umd.cs.findbugs.annotations.Nullable; +import jakarta.annotation.PostConstruct; +import lombok.EqualsAndHashCode; import lombok.Getter; +import lombok.Locked; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @@ -59,20 +63,17 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; -import javax.annotation.Nullable; -import javax.annotation.PostConstruct; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Collections; +import java.util.Comparator; import java.util.List; import java.util.Locale; -import java.util.Map; import java.util.Optional; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Pattern; -import java.util.stream.Collectors; import static java.util.Objects.requireNonNull; import static org.antlr.v4.runtime.Token.DEFAULT_CHANNEL; @@ -81,16 +82,20 @@ @Scope("prototype") @RequiredArgsConstructor @Slf4j -public class DocumentContext { +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +public class DocumentContext implements Comparable { private static final Pattern CONTENT_SPLIT_PATTERN = Pattern.compile("\r?\n|\r"); @Getter + @EqualsAndHashCode.Include private final URI uri; @Nullable private String content; + @Getter + @EqualsAndHashCode.Include private int version; @Setter(onMethod = @__({@Autowired})) @@ -107,9 +112,9 @@ public class DocumentContext { @Getter private FileType fileType; - @Getter + @Getter(onMethod = @__({@Locked("computeLock")})) private BSLTokenizer tokenizer; - @Getter + @Getter(onMethod = @__({@Locked("computeLock")})) private SymbolTree symbolTree; @Getter @@ -120,8 +125,6 @@ public class DocumentContext { private final Lazy contentList = new Lazy<>(this::computeContentList, computeLock); private final Lazy moduleType = new Lazy<>(this::computeModuleType, computeLock); - private final Lazy> supportVariants - = new Lazy<>(this::computeSupportVariants, computeLock); private final Lazy cognitiveComplexityData = new Lazy<>(this::computeCognitiveComplexity, computeLock); private final Lazy cyclomaticComplexityData @@ -142,35 +145,40 @@ public ServerContext getServerContext() { return context; } + @Locked("computeLock") public String getContent() { requireNonNull(content); return content; } + @Locked("computeLock") public String[] getContentList() { return contentList.getOrCompute(); } + @Locked("computeLock") public BSLParser.FileContext getAst() { requireNonNull(content); return tokenizer.getAst(); } + @Locked("computeLock") public List getTokens() { requireNonNull(content); return tokenizer.getTokens(); } public List getTokensFromDefaultChannel() { - return getTokens().stream().filter(token -> token.getChannel() == DEFAULT_CHANNEL).collect(Collectors.toList()); + return getTokens().stream().filter(token -> token.getChannel() == DEFAULT_CHANNEL).toList(); } public List getComments() { return getTokens().stream() .filter(token -> token.getType() == BSLLexer.LINE_COMMENT) - .collect(Collectors.toList()); + .toList(); } + @Locked("computeLock") public String getText(Range range) { Position start = range.getStart(); Position end = range.getEnd(); @@ -240,13 +248,12 @@ public ModuleType getModuleType() { return moduleType.getOrCompute(); } - public Map getSupportVariants() { - return supportVariants.getOrCompute(); + public SupportVariant getSupportVariant() { + return getMdObject().map(MD::getSupportVariant).orElse(SupportVariant.NONE); } - public Optional getMdObject() { - return Optional - .ofNullable((AbstractMDObjectBase) getServerContext().getConfiguration().getModulesByObject().get(getUri())); + public Optional getMdObject() { + return getServerContext().getConfiguration().findChild(getUri()); } public List getQueries() { @@ -274,24 +281,28 @@ public void unfreezeComputedData() { protected void rebuild(String content, int version) { computeLock.lock(); - boolean versionMatches = version == this.version && version != 0; + try { - if (versionMatches && (this.content != null)) { - clearDependantData(); - computeLock.unlock(); - return; - } + boolean versionMatches = version == this.version && version != 0; - if (!isComputedDataFrozen) { - clearSecondaryData(); - } + if (versionMatches && (this.content != null)) { + clearDependantData(); + return; + } - this.content = content; - tokenizer = new BSLTokenizer(content); - this.version = version; - symbolTree = computeSymbolTree(); + if (!isComputedDataFrozen) { + clearSecondaryData(); + } + + this.content = content; + tokenizer = new BSLTokenizer(content); + this.version = version; + symbolTree = computeSymbolTree(); + + } finally { + computeLock.unlock(); + } - computeLock.unlock(); } protected void rebuild() { @@ -306,29 +317,35 @@ protected void rebuild() { protected void clearSecondaryData() { computeLock.lock(); - content = null; - contentList.clear(); - tokenizer = null; - queries.clear(); - clearDependantData(); - - if (!isComputedDataFrozen) { - cognitiveComplexityData.clear(); - cyclomaticComplexityData.clear(); - metrics.clear(); - diagnosticIgnoranceData.clear(); + try { + + content = null; + contentList.clear(); + tokenizer = null; + queries.clear(); + clearDependantData(); + + if (!isComputedDataFrozen) { + cognitiveComplexityData.clear(); + cyclomaticComplexityData.clear(); + metrics.clear(); + diagnosticIgnoranceData.clear(); + } + } finally { + computeLock.unlock(); } - computeLock.unlock(); } private void clearDependantData() { computeLock.lock(); diagnosticsLock.lock(); - diagnostics.clear(); - - diagnosticsLock.unlock(); - computeLock.unlock(); + try { + diagnostics.clear(); + } finally { + diagnosticsLock.unlock(); + computeLock.unlock(); + } } private static FileType computeFileType(URI uri) { @@ -359,11 +376,7 @@ private SymbolTree computeSymbolTree() { private ModuleType computeModuleType() { - return context.getConfiguration().getModuleType(uri); - } - - private Map computeSupportVariants() { - return context.getConfiguration().getModuleSupport(uri); + return context.getConfiguration().getModuleTypeByURI(uri); } private ComplexityData computeCognitiveComplexity() { @@ -427,4 +440,10 @@ private List computeQueries() { return (new QueryComputer(this)).compute(); } + @Override + public int compareTo(@NonNull DocumentContext other) { + return Comparator.comparing(DocumentContext::getUri) + .thenComparing(DocumentContext::getVersion) + .compare(this, other); + } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/FileType.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/FileType.java index f4253e641d4..bdf1753fd48 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/FileType.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/FileType.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/MetricStorage.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/MetricStorage.java index 9c6b69307d1..d4a1f85bd51 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/MetricStorage.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/MetricStorage.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java index 0ff492bc08a..1473e115340 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContext.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,11 +24,15 @@ import com.github._1c_syntax.bsl.languageserver.WorkDoneProgressHelper; import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.bsl.languageserver.utils.MdoRefBuilder; +import com.github._1c_syntax.bsl.languageserver.utils.NamedForkJoinWorkerThreadFactory; import com.github._1c_syntax.bsl.languageserver.utils.Resources; +import com.github._1c_syntax.bsl.mdclasses.CF; +import com.github._1c_syntax.bsl.mdclasses.MDClasses; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.Configuration; import com.github._1c_syntax.utils.Absolute; import com.github._1c_syntax.utils.Lazy; +import edu.umd.cs.findbugs.annotations.Nullable; +import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @@ -36,7 +40,6 @@ import org.springframework.beans.factory.ObjectProvider; import org.springframework.stereotype.Component; -import javax.annotation.CheckForNull; import java.io.File; import java.net.URI; import java.nio.file.Path; @@ -62,9 +65,10 @@ public class ServerContext { private final LanguageServerConfiguration languageServerConfiguration; private final Map documents = Collections.synchronizedMap(new HashMap<>()); - private final Lazy configurationMetadata = new Lazy<>(this::computeConfigurationMetadata); - @CheckForNull + private final Lazy configurationMetadata = new Lazy<>(this::computeConfigurationMetadata); + @Nullable @Setter + @Getter private Path configurationRoot; private final Map mdoRefs = Collections.synchronizedMap(new HashMap<>()); private final Map> documentsByMDORef @@ -103,21 +107,25 @@ public void populateContext(List files) { LOGGER.debug("Populating context..."); contextLock.writeLock().lock(); - files.parallelStream().forEach((File file) -> { + try { - workDoneProgressReporter.tick(); + files.parallelStream().forEach((File file) -> { - var uri = file.toURI(); - var documentContext = getDocument(uri); - if (documentContext == null) { - documentContext = createDocumentContext(uri); - rebuildDocument(documentContext); - documentContext.freezeComputedData(); - tryClearDocument(documentContext); - } - }); + workDoneProgressReporter.tick(); - contextLock.writeLock().unlock(); + var uri = file.toURI(); + var documentContext = getDocument(uri); + if (documentContext == null) { + documentContext = createDocumentContext(uri); + rebuildDocument(documentContext); + documentContext.freezeComputedData(); + tryClearDocument(documentContext); + } + }); + + } finally { + contextLock.writeLock().unlock(); + } workDoneProgressReporter.endProgress(getMessage("populateContextPopulated")); LOGGER.debug("Context populated."); @@ -127,7 +135,7 @@ public Map getDocuments() { return Collections.unmodifiableMap(documents); } - @CheckForNull + @Nullable public DocumentContext getDocument(String uri) { return getDocument(URI.create(uri)); } @@ -140,7 +148,7 @@ public Optional getDocument(String mdoRef, ModuleType moduleTyp return Optional.empty(); } - @CheckForNull + @Nullable public DocumentContext getDocument(URI uri) { return documents.get(Absolute.uri(uri)); } @@ -253,7 +261,7 @@ public void closeDocument(DocumentContext documentContext) { documentContext.clearSecondaryData(); } - public Configuration getConfiguration() { + public CF getConfiguration() { return configurationMetadata.getOrCompute(); } @@ -268,24 +276,26 @@ private DocumentContext createDocumentContext(URI uri) { return documentContext; } - private Configuration computeConfigurationMetadata() { + private CF computeConfigurationMetadata() { if (configurationRoot == null) { - return Configuration.create(); + return (CF) MDClasses.createConfiguration(); } var progress = workDoneProgressHelper.createProgress(0, ""); progress.beginProgress(getMessage("computeConfigurationMetadata")); - Configuration configuration; - var executorService = new ForkJoinPool(ForkJoinPool.getCommonPoolParallelism()); + var factory = new NamedForkJoinWorkerThreadFactory("compute-configuration-"); + var executorService = new ForkJoinPool(ForkJoinPool.getCommonPoolParallelism(), factory, null, true); + + CF configuration; try { - configuration = executorService.submit(() -> Configuration.create(configurationRoot)).get(); + configuration = (CF) executorService.submit(() -> MDClasses.createConfiguration(configurationRoot)).get(); } catch (ExecutionException e) { LOGGER.error("Can't parse configuration metadata. Execution exception.", e); - configuration = Configuration.create(); + configuration = (CF) MDClasses.createConfiguration(); } catch (InterruptedException e) { LOGGER.error("Can't parse configuration metadata. Interrupted exception.", e); - configuration = Configuration.create(); + configuration = (CF) MDClasses.createConfiguration(); Thread.currentThread().interrupt(); } finally { executorService.shutdown(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CognitiveComplexityComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CognitiveComplexityComputer.java index f4f1ef52ec8..6a4087f201d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CognitiveComplexityComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CognitiveComplexityComputer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,6 +29,7 @@ import com.github._1c_syntax.bsl.parser.BSLParserBaseListener; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import com.github._1c_syntax.utils.StringInterner; +import jakarta.annotation.PostConstruct; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; import lombok.Setter; @@ -40,7 +41,6 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -97,7 +97,7 @@ public ComplexityData compute() { methodsComplexity.clear(); ignoredContexts.clear(); - ParseTreeWalker walker = new ParseTreeWalker(); + var walker = new ParseTreeWalker(); walker.walk(this, documentContext.getAst()); return new ComplexityData( @@ -265,7 +265,7 @@ public void enterGotoStatement(BSLParser.GotoStatementContext ctx) { @Override public void enterGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { - BSLParser.MethodNameContext methodNameContext = ctx.methodName(); + var methodNameContext = ctx.methodName(); if (methodNameContext != null && currentMethod != null) { String calledMethodName = methodNameContext.getText(); if (currentMethod.getName().equalsIgnoreCase(calledMethodName)) { @@ -286,7 +286,7 @@ public void enterExpression(BSLParser.ExpressionContext ctx) { final List flattenExpression = flattenExpression(ctx); int emptyTokenType = -1; - AtomicInteger lastOperationType = new AtomicInteger(emptyTokenType); + var lastOperationType = new AtomicInteger(emptyTokenType); flattenExpression.forEach((Token token) -> { int currentOperationType = token.getType(); @@ -309,15 +309,14 @@ private List flattenExpression(BSLParser.ExpressionContext ctx) { final List children = Trees.getChildren(ctx); for (Tree tree : children) { - if (!(tree instanceof BSLParserRuleContext)) { + if (!(tree instanceof BSLParserRuleContext parserRule)) { continue; } - BSLParserRuleContext parserRule = ((BSLParserRuleContext) tree); - if (parserRule instanceof BSLParser.MemberContext) { - flattenMember(result, (BSLParser.MemberContext) parserRule); - } else if (parserRule instanceof BSLParser.OperationContext) { - flattenOperation(result, (BSLParser.OperationContext) parserRule); + if (parserRule instanceof BSLParser.MemberContext memberContext) { + flattenMember(result, memberContext); + } else if (parserRule instanceof BSLParser.OperationContext operationContext) { + flattenOperation(result, operationContext); } } @@ -339,7 +338,7 @@ private void flattenMember(List result, BSLParser.MemberContext member) { final BSLParser.UnaryModifierContext unaryModifier = member.unaryModifier(); if (unaryModifier != null && unaryModifier.NOT_KEYWORD() != null) { - final CommonToken splitter = new CommonToken(-1); + final var splitter = new CommonToken(-1); result.add(splitter); result.addAll(nestedTokens); result.add(splitter); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ComplexityData.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ComplexityData.java index 2678b4a408b..b06da7c0624 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ComplexityData.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ComplexityData.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ComplexitySecondaryLocation.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ComplexitySecondaryLocation.java index d6782987054..b2a9bc1b11e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ComplexitySecondaryLocation.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ComplexitySecondaryLocation.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/Computer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/Computer.java index d1e897d01a5..29b041675c0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/Computer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/Computer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CyclomaticComplexityComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CyclomaticComplexityComputer.java index ae93698686f..78606dac397 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CyclomaticComplexityComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CyclomaticComplexityComputer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,6 +29,7 @@ import com.github._1c_syntax.bsl.parser.BSLParserBaseListener; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import com.github._1c_syntax.utils.StringInterner; +import jakarta.annotation.PostConstruct; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; import lombok.Setter; @@ -41,7 +42,6 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -201,7 +201,7 @@ public void enterExceptCodeBlock(BSLParser.ExceptCodeBlockContext ctx) { @Override public void enterGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { - BSLParser.MethodNameContext methodNameContext = ctx.methodName(); + var methodNameContext = ctx.methodName(); if (methodNameContext != null && currentMethod != null) { String calledMethodName = methodNameContext.getText(); if (currentMethod.getName().equalsIgnoreCase(calledMethodName)) { @@ -234,15 +234,14 @@ private static List flattenExpression(BSLParser.ExpressionContext ctx) { final List children = Trees.getChildren(ctx); for (Tree tree : children) { - if (!(tree instanceof BSLParserRuleContext)) { + if (!(tree instanceof BSLParserRuleContext parserRule)) { continue; } - BSLParserRuleContext parserRule = ((BSLParserRuleContext) tree); - if (parserRule instanceof BSLParser.MemberContext) { - flattenMember(result, (BSLParser.MemberContext) parserRule); - } else if (parserRule instanceof BSLParser.OperationContext) { - flattenOperation(result, (BSLParser.OperationContext) parserRule); + if (parserRule instanceof BSLParser.MemberContext memberContext) { + flattenMember(result, memberContext); + } else if (parserRule instanceof BSLParser.OperationContext operationContext) { + flattenOperation(result, operationContext); } } @@ -264,7 +263,7 @@ private static void flattenMember(List result, BSLParser.MemberContext me final BSLParser.UnaryModifierContext unaryModifier = member.unaryModifier(); if (unaryModifier != null && unaryModifier.NOT_KEYWORD() != null) { - final CommonToken splitter = new CommonToken(-1); + final var splitter = new CommonToken(-1); result.add(splitter); result.addAll(nestedTokens); result.add(splitter); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/DiagnosticComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/DiagnosticComputer.java index b38162add0a..5d52f23d94b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/DiagnosticComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/DiagnosticComputer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,23 +23,45 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.diagnostics.BSLDiagnostic; -import lombok.RequiredArgsConstructor; +import com.github._1c_syntax.bsl.languageserver.utils.NamedForkJoinWorkerThreadFactory; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; import lombok.extern.slf4j.Slf4j; import org.eclipse.lsp4j.Diagnostic; import org.springframework.beans.factory.annotation.Lookup; import org.springframework.stereotype.Component; import java.util.List; -import java.util.stream.Collectors; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ForkJoinPool; +import java.util.function.Predicate; import java.util.stream.Stream; @Component -@RequiredArgsConstructor @Slf4j public abstract class DiagnosticComputer { + private ExecutorService executorService; + + @PostConstruct + private void init() { + var factory = new NamedForkJoinWorkerThreadFactory("diagnostic-computer-"); + executorService = new ForkJoinPool(ForkJoinPool.getCommonPoolParallelism(), factory, null, true); + } + + @PreDestroy + private void onDestroy() { + executorService.shutdown(); + } + public List compute(DocumentContext documentContext) { + return CompletableFuture + .supplyAsync(() -> internalCompute(documentContext), executorService) + .join(); + } + private List internalCompute(DocumentContext documentContext) { DiagnosticIgnoranceComputer.Data diagnosticIgnorance = documentContext.getDiagnosticIgnorance(); return diagnostics(documentContext).parallelStream() @@ -47,7 +69,7 @@ public List compute(DocumentContext documentContext) { try { return diagnostic.getDiagnostics(documentContext).stream(); } catch (RuntimeException e) { - String message = String.format( + var message = String.format( "Diagnostic computation error.%nFile: %s%nDiagnostic: %s", documentContext.getUri(), diagnostic.getInfo().getCode() @@ -57,9 +79,8 @@ public List compute(DocumentContext documentContext) { return Stream.empty(); } }) - .filter((Diagnostic diagnostic) -> - !diagnosticIgnorance.diagnosticShouldBeIgnored(diagnostic)) - .collect(Collectors.toList()); + .filter(Predicate.not(diagnosticIgnorance::diagnosticShouldBeIgnored)) + .toList(); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/DiagnosticIgnoranceComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/DiagnosticIgnoranceComputer.java index f491af56693..9d34fb2c19c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/DiagnosticIgnoranceComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/DiagnosticIgnoranceComputer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,12 +28,12 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCode; import com.github._1c_syntax.bsl.parser.BSLLexer; import com.github._1c_syntax.utils.CaseInsensitivePattern; +import edu.umd.cs.findbugs.annotations.Nullable; import lombok.AllArgsConstructor; import org.antlr.v4.runtime.Token; import org.apache.commons.lang3.Range; import org.eclipse.lsp4j.Diagnostic; -import javax.annotation.CheckForNull; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; @@ -181,7 +181,7 @@ private boolean checkTrailingComment(Set codeLines, Token comment) { return true; } - @CheckForNull + @Nullable private DiagnosticCode checkIgnoreOff( Pattern ignoreOff, Token comment @@ -227,7 +227,7 @@ private boolean checkIgnoreOn( private void addIgnoredRange(DiagnosticCode diagnosticKey, int ignoreRangeStart, int ignoreRangeEnd) { // convert antlr4 line numbers (1..n) to lsp (0..n) - Range ignoreRange = Range.between(ignoreRangeStart - 1, ignoreRangeEnd - 1); + Range ignoreRange = Range.of(ignoreRangeStart - 1, ignoreRangeEnd - 1); final List> ranges = diagnosticIgnorance.computeIfAbsent(diagnosticKey, s -> new ArrayList<>()); ranges.add(ignoreRange); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java index 94014d30a10..66af30c50e5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -36,13 +36,13 @@ import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserBaseVisitor; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; +import edu.umd.cs.findbugs.annotations.Nullable; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; import org.eclipse.lsp4j.Range; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -89,15 +89,20 @@ public ParseTree visitFunction(BSLParser.FunctionContext ctx) { return ctx; } + if (!declaration.annotation().isEmpty()) { + startNode = declaration.annotation().get(0).AMPERSAND(); + } + MethodSymbol methodSymbol = createMethodSymbol( startNode, stopNode, + declaration.FUNCTION_KEYWORD().getSymbol(), declaration.subName().getStart(), declaration.paramList(), true, declaration.EXPORT_KEYWORD() != null, getCompilerDirective(declaration.compilerDirective()), - getAnnotations(declaration.annotation())); + createAnnotations(declaration.annotation())); methods.add(methodSymbol); @@ -119,15 +124,20 @@ public ParseTree visitProcedure(BSLParser.ProcedureContext ctx) { return ctx; } + if (!declaration.annotation().isEmpty()) { + startNode = declaration.annotation().get(0).AMPERSAND(); + } + MethodSymbol methodSymbol = createMethodSymbol( startNode, stopNode, + declaration.PROCEDURE_KEYWORD().getSymbol(), declaration.subName().getStart(), declaration.paramList(), false, declaration.EXPORT_KEYWORD() != null, getCompilerDirective(declaration.compilerDirective()), - getAnnotations(declaration.annotation()) + createAnnotations(declaration.annotation()) ); methods.add(methodSymbol); @@ -182,6 +192,7 @@ private static Optional getCompilerDirective( private MethodSymbol createMethodSymbol( TerminalNode startNode, TerminalNode stopNode, + Token startOfMethod, Token subName, BSLParser.ParamListContext paramList, boolean function, @@ -189,7 +200,8 @@ private MethodSymbol createMethodSymbol( Optional compilerDirective, List annotations ) { - Optional description = createDescription(startNode.getSymbol()); + Optional description = createDescription(startOfMethod) + .or(() -> createDescription(startNode.getSymbol())); boolean deprecated = description .map(MethodDescription::isDeprecated) .orElse(false); @@ -233,10 +245,11 @@ private static List createParameters( .name(parameterName) .byValue(param.VAL_KEYWORD() != null) .defaultValue(getDefaultValue(param)) + .annotations(createAnnotations(param.annotation())) .range(getParameterRange(param)) .description(getParameterDescription(parameterName, description)) .build(); - }).collect(Collectors.toList()); + }).toList(); } private static ParameterDefinition.DefaultValue getDefaultValue(BSLParser.ParamContext param) { @@ -310,10 +323,10 @@ private static Optional getParameterDescription( } - private static List getAnnotations(List annotationContext) { - return annotationContext.stream() + private static List createAnnotations(List annotationContexts) { + return annotationContexts.stream() .map(MethodSymbolComputer::createAnnotation) - .collect(Collectors.toList()); + .toList(); } private static Annotation createAnnotation(BSLParser.AnnotationContext annotation) { @@ -334,7 +347,7 @@ private static List getAnnotationParameter( return annotationParamsContext.annotationParam().stream() .map(MethodSymbolComputer::getAnnotationParam) - .collect(Collectors.toList()); + .toList(); } private static AnnotationParameterDefinition getAnnotationParam(BSLParser.AnnotationParamContext o) { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ModuleSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ModuleSymbolComputer.java index e97141d44d8..eead7c8c435 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ModuleSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ModuleSymbolComputer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/QueryComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/QueryComputer.java index 460ed79c4db..00c9fe2059e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/QueryComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/QueryComputer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,7 +28,6 @@ import com.github._1c_syntax.utils.CaseInsensitivePattern; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.ParseTree; -import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; @@ -143,7 +142,6 @@ public ParseTree visitString(BSLParser.StringContext ctx) { return ctx; } - @NotNull private static String getString(int startLine, Token token) { var string = addEmptyLines(startLine, token) + " ".repeat(token.getCharPositionInLine()); if (token.getText().startsWith("|")) { @@ -156,7 +154,7 @@ private static String getString(int startLine, Token token) { private static String trimLastQuote(String text) { var quoteCount = text.length() - text.replace("\"", "").length(); - if (quoteCount % 2 == 1) { + if (quoteCount % 2 != 0) { String newString; var quotePosition = text.lastIndexOf("\""); newString = text.substring(0, quotePosition) + " "; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/RegionSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/RegionSymbolComputer.java index 2b29e1183e3..54b827e7902 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/RegionSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/RegionSymbolComputer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/SymbolTreeComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/SymbolTreeComputer.java index fa26b19a0bc..08dfbf7fe8c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/SymbolTreeComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/SymbolTreeComputer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java index 20693dee0a9..96c84b6640f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolComputer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -184,6 +184,10 @@ public ParseTree visitForStatement(BSLParser.ForStatementContext ctx) { @Override public ParseTree visitForEachStatement(BSLParser.ForEachStatementContext ctx) { + if (ctx.IDENTIFIER() == null) { + return super.visitForEachStatement(ctx); + } + if ( currentMethodVariables.containsKey(ctx.IDENTIFIER().getText()) || moduleVariables.containsKey(ctx.IDENTIFIER().getText()) @@ -229,6 +233,30 @@ private Optional createDescription(BSLParser.LValueContext ); } + private Optional createDescription(BSLParser.ForEachStatementContext ctx) { + var trailingComments = Trees.getTrailingComment(documentContext.getTokens(), ctx.IDENTIFIER().getSymbol()); + + if (trailingComments.isEmpty()) { + return Optional.empty(); + } + + return Optional.of( + new VariableDescription(Collections.emptyList(), trailingComments) + ); + } + + private Optional createDescription(BSLParser.ForStatementContext ctx) { + var trailingComments = Trees.getTrailingComment(documentContext.getTokens(), ctx.IDENTIFIER().getSymbol()); + + if (trailingComments.isEmpty()) { + return Optional.empty(); + } + + return Optional.of( + new VariableDescription(Collections.emptyList(), trailingComments) + ); + } + private Optional createDescription(BSLParserRuleContext ctx) { List tokens = documentContext.getTokens(); List comments = new ArrayList<>(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/package-info.java index 3c1f963026b..e72d3136779 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/computer/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/events/DocumentContextContentChangedEvent.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/events/DocumentContextContentChangedEvent.java index 6db49adbc8d..473d527eb5a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/events/DocumentContextContentChangedEvent.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/events/DocumentContextContentChangedEvent.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/events/ServerContextPopulatedEvent.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/events/ServerContextPopulatedEvent.java index 02a7fdd2a27..4eb7770a5bf 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/events/ServerContextPopulatedEvent.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/events/ServerContextPopulatedEvent.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/events/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/events/package-info.java index 6970ddd91cc..e17d96a1781 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/events/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/events/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,7 +22,8 @@ /** * События пакета com.github._1c_syntax.bsl.languageserver.configuration. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.context.events; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/package-info.java index b22c38f6367..cd303b7a239 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -19,7 +19,8 @@ * You should have received a copy of the GNU Lesser General Public * License along with BSL Language Server. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.context; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/AbstractVariableSymbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/AbstractVariableSymbol.java index ab0a15b8764..b7a43dc11cf 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/AbstractVariableSymbol.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/AbstractVariableSymbol.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -46,7 +46,7 @@ @NonFinal @Builder(builderClassName = "Builder") @EqualsAndHashCode(onlyExplicitlyIncluded = true) -@ToString(exclude = {"children", "parent"}) +@ToString(exclude = {"parent"}) public abstract class AbstractVariableSymbol implements VariableSymbol { /** @@ -74,12 +74,6 @@ public abstract class AbstractVariableSymbol implements VariableSymbol { @NonFinal Optional parent; - /** - * Список "детей" символа - символов, которые располагаются внутри данного символа. - */ - @Getter - List children; - /** * Тип переменной. */ @@ -95,6 +89,11 @@ public abstract class AbstractVariableSymbol implements VariableSymbol { */ Optional description; + @Override + public List getChildren() { + return Collections.emptyList(); + } + @Override public SymbolKind getSymbolKind() { return SymbolKind.Variable; @@ -129,10 +128,6 @@ public static class Builder { @Accessors(fluent = true, chain = true) Optional parent = Optional.empty(); - @Setter - @Accessors(fluent = true, chain = true) - List children = Collections.emptyList(); - private int startLine; private int startCharacter; private int endLine; @@ -179,7 +174,6 @@ public VariableSymbol build() { scope, owner, parent, - children, (byte) kind.ordinal(), export, description, @@ -197,7 +191,6 @@ public VariableSymbol build() { scope, owner, parent, - children, (byte) kind.ordinal(), export, description, diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/AnnotationParamSymbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/AnnotationParamSymbol.java new file mode 100644 index 00000000000..d7e84011ac9 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/AnnotationParamSymbol.java @@ -0,0 +1,86 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.context.symbol; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.symbol.description.MethodDescription; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Setter; +import lombok.ToString; +import lombok.Value; +import lombok.experimental.NonFinal; +import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.SymbolKind; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +@Value +@Builder +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +@ToString(exclude = {"parent"}) +public class AnnotationParamSymbol implements SourceDefinedSymbol, Describable { + + String name; + + @EqualsAndHashCode.Include + DocumentContext owner; + + Range range; + + @EqualsAndHashCode.Include + Range selectionRange; + + @Setter + @NonFinal + @Builder.Default + Optional parent = Optional.empty(); + + Optional description; + + @Override + public List getChildren() { + return Collections.emptyList(); + } + + public SymbolKind getSymbolKind() { + return SymbolKind.TypeParameter; + } + + @Override + public void accept(SymbolTreeVisitor visitor) { + // no-op + } + + public static AnnotationParamSymbol from(String name, MethodSymbol methodSymbol) { + return AnnotationParamSymbol.builder() + .name(name) + .owner(methodSymbol.getOwner()) + .range(methodSymbol.getRange()) + .selectionRange(methodSymbol.getSelectionRange()) + .description(methodSymbol.getDescription()) + .parent(Optional.of(methodSymbol)) + .build(); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/AnnotationSymbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/AnnotationSymbol.java new file mode 100644 index 00000000000..a1a002e818c --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/AnnotationSymbol.java @@ -0,0 +1,86 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.context.symbol; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.symbol.description.MethodDescription; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Setter; +import lombok.ToString; +import lombok.Value; +import lombok.experimental.NonFinal; +import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.SymbolKind; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +@Value +@Builder +@EqualsAndHashCode(onlyExplicitlyIncluded = true) +@ToString(exclude = {"parent"}) +public class AnnotationSymbol implements SourceDefinedSymbol, Describable { + + String name; + + @EqualsAndHashCode.Include + DocumentContext owner; + + Range range; + + @EqualsAndHashCode.Include + Range selectionRange; + + @Setter + @NonFinal + @Builder.Default + Optional parent = Optional.empty(); + + Optional description; + + @Override + public List getChildren() { + return Collections.emptyList(); + } + + public SymbolKind getSymbolKind() { + return SymbolKind.Interface; + } + + @Override + public void accept(SymbolTreeVisitor visitor) { + // no-op + } + + public static AnnotationSymbol from(String name, MethodSymbol methodSymbol) { + return AnnotationSymbol.builder() + .name(name) + .owner(methodSymbol.getOwner()) + .range(methodSymbol.getRange()) + .selectionRange(methodSymbol.getSelectionRange()) + .description(methodSymbol.getDescription()) + .parent(Optional.of(methodSymbol)) + .build(); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Describable.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Describable.java index a1b67389e44..daaadd7c152 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Describable.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Describable.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Exportable.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Exportable.java index 5b803ad1299..d42ad1d37da 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Exportable.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Exportable.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/IntBasedVariableSymbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/IntBasedVariableSymbol.java index e83fe468c65..4e907f1fed8 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/IntBasedVariableSymbol.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/IntBasedVariableSymbol.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -32,7 +32,6 @@ import lombok.experimental.NonFinal; import org.eclipse.lsp4j.Range; -import java.util.List; import java.util.Optional; /** @@ -65,7 +64,6 @@ public IntBasedVariableSymbol( SourceDefinedSymbol scope, DocumentContext owner, Optional parent, - List children, byte kind, boolean export, Optional description, @@ -77,7 +75,7 @@ public IntBasedVariableSymbol( int variableNameStartCharacter, int variableNameEndCharacter ) { - super(name, scope, owner, parent, children, kind, export, description); + super(name, scope, owner, parent, kind, export, description); this.startLine = startLine; this.startCharacter = startCharacter; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java index e646e09ed84..279200e0d08 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/MethodSymbol.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -38,6 +38,7 @@ import org.eclipse.lsp4j.SymbolKind; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Optional; @@ -87,12 +88,12 @@ public class MethodSymbol implements SourceDefinedSymbol, Exportable, Describabl boolean deprecated; @Builder.Default - List parameters = new ArrayList<>(); + List parameters = Collections.emptyList(); @Builder.Default Optional compilerDirectiveKind = Optional.empty(); @Builder.Default - List annotations = new ArrayList<>(); + List annotations = Collections.emptyList(); @Override public Range getRange() { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/ModuleSymbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/ModuleSymbol.java index a47924a6668..dd98e0764d7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/ModuleSymbol.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/ModuleSymbol.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/ParameterDefinition.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/ParameterDefinition.java index 6a0ace8f760..0a4640ead32 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/ParameterDefinition.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/ParameterDefinition.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,6 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.context.symbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.annotations.Annotation; import com.github._1c_syntax.bsl.languageserver.context.symbol.description.ParameterDescription; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import lombok.AccessLevel; @@ -29,6 +30,8 @@ import lombok.Value; import org.eclipse.lsp4j.Range; +import java.util.Collections; +import java.util.List; import java.util.Optional; /** @@ -58,6 +61,9 @@ public class ParameterDefinition { */ DefaultValue defaultValue; + @Builder.Default + List annotations = Collections.emptyList(); + @Getter(AccessLevel.NONE) int startLine; @Getter(AccessLevel.NONE) @@ -92,12 +98,8 @@ public enum ParameterType { EMPTY } - @Value - public static class DefaultValue { - public static final DefaultValue EMPTY = new DefaultValue(ParameterType.EMPTY, ""); - - ParameterType type; - String value; + public record DefaultValue(ParameterType type, String value) { + public static final DefaultValue EMPTY = new DefaultValue(ParameterType.EMPTY, ""); } public static class ParameterDefinitionBuilder { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/RegionSymbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/RegionSymbol.java index df408fa8d6e..ceb713ca6bb 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/RegionSymbol.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/RegionSymbol.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/ShortBasedVariableSymbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/ShortBasedVariableSymbol.java index e9953be9aff..66331060bc0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/ShortBasedVariableSymbol.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/ShortBasedVariableSymbol.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -32,7 +32,6 @@ import lombok.experimental.NonFinal; import org.eclipse.lsp4j.Range; -import java.util.List; import java.util.Optional; /** @@ -65,7 +64,6 @@ public ShortBasedVariableSymbol( SourceDefinedSymbol scope, DocumentContext owner, Optional parent, - List children, byte kind, boolean export, Optional description, @@ -77,7 +75,7 @@ public ShortBasedVariableSymbol( short variableNameStartCharacter, short variableNameEndCharacter ) { - super(name, scope, owner, parent, children, kind, export, description); + super(name, scope, owner, parent, kind, export, description); this.startLine = startLine; this.startCharacter = startCharacter; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SourceDefinedSymbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SourceDefinedSymbol.java index f9705e7ecfd..dfe7faab85d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SourceDefinedSymbol.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SourceDefinedSymbol.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Symbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Symbol.java index 822f1f07a64..73d4c3a7114 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Symbol.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/Symbol.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java index 4ac695a26ac..3e53018cbec 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTree.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTreeVisitor.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTreeVisitor.java index 920af747708..d92e9dcb0b4 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTreeVisitor.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/SymbolTreeVisitor.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/VariableSymbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/VariableSymbol.java index 3d8e3be6c3c..6bee4f6a7c2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/VariableSymbol.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/VariableSymbol.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/Annotation.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/Annotation.java index 55430b1e4db..3b2ea212538 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/Annotation.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/Annotation.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,7 +24,7 @@ import lombok.Builder; import lombok.Value; -import java.util.ArrayList; +import java.util.Collections; import java.util.List; /** @@ -38,5 +38,5 @@ public class Annotation { AnnotationKind kind; @Builder.Default - List parameters = new ArrayList<>(); + List parameters = Collections.emptyList(); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/AnnotationKind.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/AnnotationKind.java index e58fb0e4ce9..ae3e0a898bf 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/AnnotationKind.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/AnnotationKind.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/AnnotationParameterDefinition.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/AnnotationParameterDefinition.java index 64b83f57604..9c017531776 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/AnnotationParameterDefinition.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/AnnotationParameterDefinition.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/CompilerDirectiveKind.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/CompilerDirectiveKind.java index f3a870cb00c..5746358b1d7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/CompilerDirectiveKind.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/CompilerDirectiveKind.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/package-info.java index 8f9c581ab44..b363ff44efb 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/annotations/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/DescriptionReader.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/DescriptionReader.java index 06ab2f3401e..7e8fb4d5cb1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/DescriptionReader.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/DescriptionReader.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,8 +23,8 @@ import com.github._1c_syntax.bsl.parser.BSLMethodDescriptionParser; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; +import edu.umd.cs.findbugs.annotations.Nullable; import lombok.experimental.UtilityClass; -import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; @@ -236,7 +236,9 @@ private String getDescriptionString(BSLParserRuleContext ctx) { return strings.toString().strip(); } - private List getParametersStrings(List strings) { + private List getParametersStrings( + List strings) { + List result = new ArrayList<>(); var current = new TempParameterData(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/MethodDescription.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/MethodDescription.java index ca2a88039d9..de6406e0a0d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/MethodDescription.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/MethodDescription.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/ParameterDescription.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/ParameterDescription.java index d6789cd62bc..c5744d6bf29 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/ParameterDescription.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/ParameterDescription.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/SourceDefinedSymbolDescription.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/SourceDefinedSymbolDescription.java index 4a06c4ae602..5d68c879eb1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/SourceDefinedSymbolDescription.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/SourceDefinedSymbolDescription.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/TypeDescription.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/TypeDescription.java index 569dc03b1d5..c5aaf5affd3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/TypeDescription.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/TypeDescription.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/package-info.java index 9962f6c4d12..d96c1febe83 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,7 +22,8 @@ /** * Классы для хранения информации, прочитанной из комментариев-описаний */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.context.symbol.description; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/package-info.java index e552f2515da..a3b85b32c15 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/variable/VariableDescription.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/variable/VariableDescription.java index def143b8665..f12bb967f79 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/variable/VariableDescription.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/variable/VariableDescription.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/variable/VariableKind.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/variable/VariableKind.java index dd74055a08a..308c43e48c8 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/variable/VariableKind.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/variable/VariableKind.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/databind/ObjectMapperConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/databind/ObjectMapperConfiguration.java new file mode 100644 index 00000000000..1b0aa9ec303 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/databind/ObjectMapperConfiguration.java @@ -0,0 +1,69 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.databind; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; +import com.fasterxml.jackson.databind.jsontype.NamedType; +import com.github._1c_syntax.bsl.languageserver.codelenses.CodeLensData; +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.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.stream.Collectors; + +@Configuration +public class ObjectMapperConfiguration { + + @Bean + public ObjectMapper objectMapper( + Collection> codeLensResolvers, + Collection> commandSuppliers + ) { + + var namedTypes = new ArrayList(); + codeLensResolvers.stream() + .map(ObjectMapperConfiguration::toNamedType) + .collect(Collectors.toCollection(() -> namedTypes)); + commandSuppliers.stream() + .map(ObjectMapperConfiguration::toNamedType) + .collect(Collectors.toCollection(() -> namedTypes)); + + var objectMapperBuilder = JsonMapper.builder(); + + namedTypes.forEach(objectMapperBuilder::registerSubtypes); + + return objectMapperBuilder.build(); + } + + private static NamedType toNamedType(CodeLensSupplier codeLensSupplier) { + return new NamedType(codeLensSupplier.getCodeLensDataClass(), codeLensSupplier.getId()); + } + + private static NamedType toNamedType(CommandSupplier commandSupplier) { + return new NamedType(commandSupplier.getCommandArgumentsClass(), commandSupplier.getId()); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/databind/URITypeAdapter.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/databind/URITypeAdapter.java similarity index 93% rename from src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/databind/URITypeAdapter.java rename to src/main/java/com/github/_1c_syntax/bsl/languageserver/databind/URITypeAdapter.java index 7ee6244af2f..6502c4f3d24 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/codelenses/databind/URITypeAdapter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/databind/URITypeAdapter.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -19,7 +19,7 @@ * 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.codelenses.databind; +package com.github._1c_syntax.bsl.languageserver.databind; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/databind/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/databind/package-info.java new file mode 100644 index 00000000000..32aae1ca293 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/databind/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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. + */ +/** + * Сериализация и десериализация различных классов проекта. + * {@link com.github._1c_syntax.bsl.languageserver}. + */ +@DefaultAnnotation(NonNull.class) +package com.github._1c_syntax.bsl.languageserver.databind; + +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java index 53fd5aa09d9..619590f5f60 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractCommonModuleNameDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,8 +23,7 @@ import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.utils.CaseInsensitivePattern; import java.util.regex.Matcher; @@ -49,36 +48,36 @@ protected void check() { } documentContext.getMdObject() - .filter(MDCommonModule.class::isInstance) - .map(MDCommonModule.class::cast) + .filter(CommonModule.class::isInstance) + .map(CommonModule.class::cast) .filter(this::flagsCheck) - .map(AbstractMDObjectBase::getName) + .map(CommonModule::getName) .map(pattern::matcher) .filter(this::matchCheck) .ifPresent(commonModule -> diagnosticStorage.addDiagnostic(range)); } - protected abstract boolean flagsCheck(MDCommonModule commonModule); + protected abstract boolean flagsCheck(CommonModule commonModule); protected boolean matchCheck(Matcher matcher) { return !matcher.find(); } - protected boolean isClientServer(MDCommonModule commonModule) { + protected boolean isClientServer(CommonModule commonModule) { return !commonModule.isServerCall() && commonModule.isServer() && commonModule.isExternalConnection() && isClientApplication(commonModule); } - protected boolean isClient(MDCommonModule commonModule) { + protected boolean isClient(CommonModule commonModule) { return !commonModule.isServerCall() && !commonModule.isServer() && !commonModule.isExternalConnection() && isClientApplication(commonModule); } - protected boolean isServerCall(MDCommonModule commonModule) { + protected boolean isServerCall(CommonModule commonModule) { return commonModule.isServerCall() && commonModule.isServer() && !commonModule.isExternalConnection() @@ -86,7 +85,7 @@ protected boolean isServerCall(MDCommonModule commonModule) { && !commonModule.isClientManagedApplication(); } - protected boolean isServer(MDCommonModule commonModule) { + protected boolean isServer(CommonModule commonModule) { return !commonModule.isServerCall() && commonModule.isServer() && commonModule.isExternalConnection() @@ -94,12 +93,12 @@ && isClientOrdinaryAppIfNeed(commonModule) && !commonModule.isClientManagedApplication(); } - private boolean isClientApplication(MDCommonModule commonModule) { + private boolean isClientApplication(CommonModule commonModule) { return isClientOrdinaryAppIfNeed(commonModule) && commonModule.isClientManagedApplication(); } - private boolean isClientOrdinaryAppIfNeed(MDCommonModule commonModule) { + private boolean isClientOrdinaryAppIfNeed(CommonModule commonModule) { return commonModule.isClientOrdinaryApplication() || !serverConfiguration.getDiagnosticsOptions().isOrdinaryAppSupport(); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractDiagnostic.java index 00fbb5359b9..e94746b8693 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractExecuteExternalCodeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractExecuteExternalCodeDiagnostic.java index 53cb8f2610c..f24eff53739 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractExecuteExternalCodeDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractExecuteExternalCodeDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractExpressionTreeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractExpressionTreeDiagnostic.java new file mode 100644 index 00000000000..d175109bc69 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractExpressionTreeDiagnostic.java @@ -0,0 +1,123 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.ExpressionTreeBuildingVisitor; +import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.ExpressionTreeVisitor; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.bsl.parser.BSLParserBaseVisitor; +import lombok.Getter; +import lombok.Setter; +import org.antlr.v4.runtime.tree.ParseTree; +import org.eclipse.lsp4j.Diagnostic; + +import java.util.List; + +/** + * Диагностика, анализирующая выражения BSL и предоставляющая для этого Expression Tree + */ +public abstract class AbstractExpressionTreeDiagnostic extends ExpressionTreeVisitor implements BSLDiagnostic { + @Getter + @Setter + protected DiagnosticInfo info; + protected final DiagnosticStorage diagnosticStorage = new DiagnosticStorage(this); + protected DocumentContext documentContext; + + @Override + public final List getDiagnostics(DocumentContext documentContext) { + this.documentContext = documentContext; + diagnosticStorage.clearDiagnostics(); + + var expressionTreeBuilder = new ExpressionTreeBuilder(); + expressionTreeBuilder.visitFile(documentContext.getAst()); + + return diagnosticStorage.getDiagnostics(); + } + + /** + * При входе в выражение вызывается данный метод. + * Переопределяя его можно оценить - имеет ли смысл строить дерево выражения, или данное выражение не подходит. + * Позволяет сократить время на построение дерева, если это не требуется для данного AST. + * + * @param ctx - выражение, которое в данный момент посещается. + * @return - флаг дальнейшего поведения. + * - если надо прекратить обход в глубину и построить Expression Tree на данном выражении - надо вернуть ACCEPT + * - если надо пройти дальше и посетить дочерние выражения, не затрагивая данное - надо вернуть VISIT_CHILDREN + * - если надо пропустить выражение, не ходить глубже и не строить Expression Tree - надо вернуть SKIP + */ + protected ExpressionVisitorDecision onExpressionEnter(BSLParser.ExpressionContext ctx) { + return ExpressionVisitorDecision.ACCEPT; + } + + /** + * Стратегия по построению дерева выражения на основе выражения AST + */ + protected enum ExpressionVisitorDecision { + + /** + * Не обрабатывать выражение + */ + SKIP, + + /** + * Обработать данное выражение (построить для него ExpressionTree) + */ + ACCEPT, + + /** + * Пропустить данное выражение и обойти вложенные в него выражения + */ + VISIT_CHILDREN + } + + private class ExpressionTreeBuilder extends BSLParserBaseVisitor { + + @Override + public ParseTree visitExpression(BSLParser.ExpressionContext ctx) { + + var treeBuildingVisitor = new ExpressionTreeBuildingVisitor(); + + var result = onExpressionEnter(ctx); + return switch (result) { + case SKIP -> ctx; + case ACCEPT -> processExpression(treeBuildingVisitor, ctx); + case VISIT_CHILDREN -> treeBuildingVisitor.visitChildren(ctx); + }; + } + + private BSLParser.ExpressionContext processExpression( + ExpressionTreeBuildingVisitor treeBuildingVisitor, + BSLParser.ExpressionContext ctx + ) { + treeBuildingVisitor.visitExpression(ctx); + var expressionTree = treeBuildingVisitor.getExpressionTree(); + if (expressionTree != null) { // нашлись выражения в предложенном файле + visitTopLevelExpression(expressionTree); + } + + return ctx; + } + } + +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractFindMethodDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractFindMethodDiagnostic.java index 1866be5b212..36a45cb0941 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractFindMethodDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractFindMethodDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -83,10 +83,10 @@ protected boolean checkMethodCall(BSLParser.MethodCallContext ctx) { */ protected String getMessage(BSLParserRuleContext ctx) { - if (ctx instanceof BSLParser.GlobalMethodCallContext) { - return info.getMessage(((BSLParser.GlobalMethodCallContext) ctx).methodName().getText()); - } else if (ctx instanceof BSLParser.MethodCallContext) { - return info.getMessage(((BSLParser.MethodCallContext) ctx).methodName().getText()); + if (ctx instanceof BSLParser.GlobalMethodCallContext globalMethodCallContext) { + return info.getMessage(globalMethodCallContext.methodName().getText()); + } else if (ctx instanceof BSLParser.MethodCallContext methodCallContext) { + return info.getMessage(methodCallContext.methodName().getText()); } else { return info.getMessage(); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractListenerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractListenerDiagnostic.java index b333d4e855b..96f22b97d29 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractListenerDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractListenerDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractMetadataDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractMetadataDiagnostic.java index f87cc78052a..3f612a83af6 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractMetadataDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractMetadataDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,19 +22,17 @@ package com.github._1c_syntax.bsl.languageserver.diagnostics; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.mdo.MD; +import com.github._1c_syntax.bsl.mdo.ModuleOwner; import com.github._1c_syntax.bsl.types.MDOType; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBSL; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; -import org.checkerframework.checker.nullness.qual.NonNull; import org.eclipse.lsp4j.Range; import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; /** - * Базовый класс для анализа объектов метаданных, когда диагностика региструется на первый токен модуля + * Базовый класс для анализа объектов метаданных, когда диагностика регистрируется на первый токен модуля */ public abstract class AbstractMetadataDiagnostic extends AbstractDiagnostic { @@ -60,7 +58,7 @@ public abstract class AbstractMetadataDiagnostic extends AbstractDiagnostic { */ private Range diagnosticRange; - protected AbstractMetadataDiagnostic(@NonNull List types) { + protected AbstractMetadataDiagnostic(List types) { filterMdoTypes = new ArrayList<>(types); } @@ -105,23 +103,27 @@ protected void addDiagnostic(String message) { diagnosticStorage.addDiagnostic(diagnosticRange, message); } - protected abstract void checkMetadata(AbstractMDObjectBase mdo); + protected abstract void checkMetadata(MD mdo); private void checkMetadataWithModules() { documentContext.getMdObject() .filter(mdo -> filterMdoTypes.contains(mdo.getMdoType())) - .filter(AbstractMDObjectBSL.class::isInstance) + .filter(ModuleOwner.class::isInstance) + .map(ModuleOwner.class::cast) .filter(this::haveMatchingModule) .ifPresent(this::checkMetadata); } - private boolean haveMatchingModule(AbstractMDObjectBase mdo) { - var modules = ((AbstractMDObjectBSL) mdo).getModules().stream() - .filter(mdoModule -> OBJECT_MODULES.contains(mdoModule.getModuleType())) - .collect(Collectors.toList()); + private boolean haveMatchingModule(ModuleOwner mdo) { + // чтобы не анализировать несколько раз и не выдавать одинаковые результаты для разных модулей, + // выберем только один модуль, например модуль менеджера + if (documentContext.getModuleType() == ModuleType.ManagerModule) { + return true; + } - // чтобы не анализировать несколько раз, выберем только один модуль, например модуль менеджера - return modules.size() == 1 || documentContext.getModuleType() == ModuleType.ManagerModule; + return mdo.getModules().stream() + .filter(mdoModule -> OBJECT_MODULES.contains(mdoModule.getModuleType())) + .count() == 1; } /** @@ -134,8 +136,8 @@ private boolean haveMatchingModule(AbstractMDObjectBase mdo) { private void checkMetadataWithoutModules() { documentContext.getServerContext().getConfiguration().getChildren().stream() .filter(mdo -> filterMdoTypes.contains(mdo.getMdoType())) - .filter(mdo -> !(mdo instanceof AbstractMDObjectBSL) - || (((AbstractMDObjectBSL) mdo).getModules().stream() + .filter(mdo -> !(mdo instanceof ModuleOwner moduleOwner) + || (moduleOwner.getModules().stream() .noneMatch(module -> OBJECT_MODULES.contains(module.getModuleType())))) .forEach(this::checkMetadata); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractMultilingualStringDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractMultilingualStringDiagnostic.java index 18c3217c61a..e81bdd34e91 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractMultilingualStringDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractMultilingualStringDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -34,7 +34,7 @@ public abstract class AbstractMultilingualStringDiagnostic extends AbstractVisit @DiagnosticParameter( type = String.class, - defaultValue = "" + DECLARED_LANGUAGES_DEFAULT + defaultValue = DECLARED_LANGUAGES_DEFAULT ) private String declaredLanguages = DECLARED_LANGUAGES_DEFAULT; protected MultilingualStringAnalyser parser = new MultilingualStringAnalyser(DECLARED_LANGUAGES_DEFAULT); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractSDBLListenerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractSDBLListenerDiagnostic.java index 70a020f3f56..f518004c196 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractSDBLListenerDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractSDBLListenerDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractSDBLVisitorDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractSDBLVisitorDiagnostic.java index f5f1b7b196b..58f9ce8e6ff 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractSDBLVisitorDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractSDBLVisitorDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractSymbolTreeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractSymbolTreeDiagnostic.java index 243f5c68aaa..a1d918f283a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractSymbolTreeDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractSymbolTreeDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java index 366128bbeb8..3576fc26723 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractVisitorDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AllFunctionPathMustHaveReturnDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AllFunctionPathMustHaveReturnDiagnostic.java index 6f769661a06..d1b565e8564 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AllFunctionPathMustHaveReturnDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AllFunctionPathMustHaveReturnDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -58,7 +58,6 @@ DiagnosticTag.BADPRACTICE, DiagnosticTag.SUSPICIOUS } - ) public class AllFunctionPathMustHaveReturnDiagnostic extends AbstractVisitorDiagnostic { @@ -114,7 +113,7 @@ private void checkAllPathsHaveReturns(BSLParser.FunctionContext ctx) { .map(graph::getEdgeSource) .map(vertex -> nonExplicitReturnNode(vertex, graph)) .flatMap(Optional::stream) - .collect(Collectors.toList()); + .toList(); if (incomingVertices.isEmpty()) { return; @@ -136,12 +135,12 @@ private void checkAllPathsHaveReturns(BSLParser.FunctionContext ctx) { } private Optional nonExplicitReturnNode(CfgVertex v, ControlFlowGraph graph) { - if (v instanceof BasicBlockVertex) { - return checkBasicBlockExitingNode((BasicBlockVertex) v); - } else if (v instanceof LoopVertex) { - return checkLoopExitingNode((LoopVertex) v); - } else if (v instanceof ConditionalVertex) { - return checkElseIfClauseExitingNode((ConditionalVertex) v, graph); + if (v instanceof BasicBlockVertex basicBlock) { + return checkBasicBlockExitingNode(basicBlock); + } else if (v instanceof LoopVertex loop) { + return checkLoopExitingNode(loop); + } else if (v instanceof ConditionalVertex conditional) { + return checkElseIfClauseExitingNode(conditional, graph); } return v.getAst(); @@ -158,14 +157,14 @@ private Optional checkElseIfClauseExitingNode(ConditionalV } var expression = v.getExpression(); - if (expression.getParent() instanceof BSLParser.ElsifBranchContext && !ignoreMissingElseOnExit) { - return Optional.of((BSLParser.ElsifBranchContext) expression.getParent()); + if (expression.getParent() instanceof BSLParser.ElsifBranchContext elsifBranch && !ignoreMissingElseOnExit) { + return Optional.of(elsifBranch.getParent()); } return Optional.empty(); } - private Optional checkBasicBlockExitingNode(BasicBlockVertex block) { + private static Optional checkBasicBlockExitingNode(BasicBlockVertex block) { if (!block.statements().isEmpty()) { var lastStatement = block.statements().get(block.statements().size() - 1); @@ -178,22 +177,19 @@ private Optional checkBasicBlockExitingNode(BasicBlockVert } private Optional checkLoopExitingNode(LoopVertex v) { - if (v instanceof WhileLoopVertex) { - var whileLoop = (WhileLoopVertex) v; - if (isEndlessLoop(whileLoop)) { - return Optional.empty(); - } + if (v instanceof WhileLoopVertex whileLoop && isEndlessLoop(whileLoop)) { + return Optional.empty(); } if (loopsExecutedAtLeastOnce) { - // из цикла в exit может придти только falseBranch или пустое тело цикла + // из цикла в exit может прийти только falseBranch или пустое тело цикла // и то и другое не нужно нам в рамках диагностики return Optional.empty(); } return v.getAst(); } - private boolean isEndlessLoop(WhileLoopVertex whileLoop) { + private static boolean isEndlessLoop(WhileLoopVertex whileLoop) { var expression = whileLoop.getExpression(); return expression.getChildCount() == 1 && expression.member(0).constValue() != null diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AssignAliasFieldsInQueryDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AssignAliasFieldsInQueryDiagnostic.java index 528a84b8421..ecca3091ea7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AssignAliasFieldsInQueryDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AssignAliasFieldsInQueryDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BSLDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BSLDiagnostic.java index 02edf480147..d239787f66c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BSLDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BSLDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadWordsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadWordsDiagnostic.java index 714b4f05cd6..50f182b495d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadWordsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadWordsDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,16 +22,15 @@ package com.github._1c_syntax.bsl.languageserver.diagnostics; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; -import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticParameter; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; -import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticParameter; - +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import com.github._1c_syntax.utils.CaseInsensitivePattern; import java.util.Map; import java.util.regex.Pattern; -import java.util.regex.Matcher; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, @@ -45,6 +44,7 @@ public class BadWordsDiagnostic extends AbstractDiagnostic { private static final String BAD_WORDS_DEFAULT = ""; + private static final boolean FIND_IN_COMMENTS_DEFAULT = true; @DiagnosticParameter( type = String.class, @@ -52,10 +52,17 @@ public class BadWordsDiagnostic extends AbstractDiagnostic { ) private Pattern badWords = CaseInsensitivePattern.compile(BAD_WORDS_DEFAULT); - @Override + @DiagnosticParameter( + type = Boolean.class, + defaultValue = "" + FIND_IN_COMMENTS_DEFAULT + ) + private boolean findInComments = FIND_IN_COMMENTS_DEFAULT; + + @Override public void configure(Map configuration) { this.badWords = CaseInsensitivePattern.compile( (String) configuration.getOrDefault("badWords", BAD_WORDS_DEFAULT)); + this.findInComments = (boolean) configuration.getOrDefault("findInComments", FIND_IN_COMMENTS_DEFAULT); } @Override @@ -64,13 +71,39 @@ protected void check() { if (badWords.pattern().isBlank()) { return; } + var moduleLines = documentContext.getContentList(); + if (findInComments) { + checkAllLines(moduleLines); + return; + } + checkLinesWithoutComments(moduleLines); + } + + private void checkAllLines(String[] moduleLines) { + for (var i = 0; i < moduleLines.length; i++) { + checkLine(moduleLines, i); + } + } + + private void checkLinesWithoutComments(String[] moduleLines) { + final var nclocData = documentContext.getMetrics().getNclocData(); + for (int i : nclocData) { + final var moduleNumber = i - 1; // т.к. в токенах нумерация строк с 1, а в moduleLines с 0 + checkLine(moduleLines, moduleNumber); + } + } - String[] moduleLines = documentContext.getContentList(); - for (int i = 0; i < moduleLines.length; i++) { - Matcher matcher = badWords.matcher(moduleLines[i]); - while (matcher.find()) { - diagnosticStorage.addDiagnostic(i, matcher.start(), i, matcher.end()); - } + private void checkLine(String[] lines, int lineNumber) { + var moduleLine = lines[lineNumber]; + if (moduleLine.isEmpty()) { + return; + } + var matcher = badWords.matcher(moduleLine); + while (matcher.find()) { + diagnosticStorage.addDiagnostic( + Ranges.create(lineNumber, matcher.start(), lineNumber, matcher.end()), + info.getMessage(matcher.group()) + ); } } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BeginTransactionBeforeTryCatchDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BeginTransactionBeforeTryCatchDiagnostic.java index 97bdbd3a4f2..9451fcef22e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BeginTransactionBeforeTryCatchDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BeginTransactionBeforeTryCatchDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnostic.java index b4568d566dd..38dddebdbf1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,9 +28,9 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.utils.Keywords; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.bsl.mdo.support.ReturnValueReuse; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; import com.github._1c_syntax.utils.CaseInsensitivePattern; import java.util.regex.Pattern; @@ -68,18 +68,14 @@ protected void check() { .forEach(regionSymbol -> diagnosticStorage.addDiagnostic(regionSymbol.getRegionNameRange())); } - private boolean isCashed(DocumentContext documentContext) { + private static boolean isCashed(DocumentContext documentContext) { return documentContext.getMdObject() - .filter(MDCommonModule.class::isInstance) - .map(MDCommonModule.class::cast) - .map(MDCommonModule::getReturnValuesReuse) - .filter(this::isReuseValue) + .filter(CommonModule.class::isInstance) + .map(CommonModule.class::cast) + .map(CommonModule::getReturnValuesReuse) + .filter(value -> value == ReturnValueReuse.DURING_REQUEST + || value == ReturnValueReuse.DURING_SESSION) .isPresent(); } - private Boolean isReuseValue(ReturnValueReuse value) { - return value == ReturnValueReuse.DURING_REQUEST - || value == ReturnValueReuse.DURING_SESSION; - } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CanonicalSpellingKeywordsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CanonicalSpellingKeywordsDiagnostic.java index 14df2376464..07368a4aa12 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CanonicalSpellingKeywordsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CanonicalSpellingKeywordsDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeAfterAsyncCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeAfterAsyncCallDiagnostic.java index cb5cd5b0a56..ce0424bb8d3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeAfterAsyncCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeAfterAsyncCallDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -36,7 +36,6 @@ import java.util.List; import java.util.Optional; import java.util.regex.Pattern; -import java.util.stream.Collectors; import static com.github._1c_syntax.bsl.parser.BSLParser.RULE_codeBlock; import static com.github._1c_syntax.bsl.parser.BSLParser.RULE_statement; @@ -56,7 +55,6 @@ ModuleType.FormModule, ModuleType.ManagedApplicationModule } - ) public class CodeAfterAsyncCallDiagnostic extends AbstractVisitorDiagnostic { private static final Pattern ASYNC_METHODS = CaseInsensitivePattern.compile( @@ -90,7 +88,7 @@ private static boolean checkNextBlocks(BSLParser.StatementContext statement) { final var statements = codeBlock.statement().stream() .filter(statementContext -> statementContext != statement && statementContext.getStart().getLine() > asyncLine) - .collect(Collectors.toList()); + .toList(); final var compoundCtx = statements.stream() .findFirst() .map(BSLParser.StatementContext::compoundStatement); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeBlockBeforeSubDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeBlockBeforeSubDiagnostic.java index 14b3edaab0d..4ae66dbaead 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeBlockBeforeSubDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeBlockBeforeSubDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnostic.java index 270f869f672..7634a715dd4 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CognitiveComplexityDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CognitiveComplexityDiagnostic.java index 97b199f1960..6de336fa234 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CognitiveComplexityDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CognitiveComplexityDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -46,7 +46,8 @@ minutesToFix = 15, tags = { DiagnosticTag.BRAINOVERLOAD - } + }, + extraMinForComplexity = 1 ) public class CognitiveComplexityDiagnostic extends AbstractVisitorDiagnostic { @@ -99,28 +100,6 @@ public ParseTree visitSub(BSLParser.SubContext ctx) { Integer methodComplexity = documentContext.getCognitiveComplexityData().getMethodsComplexity().get(methodSymbol); if (methodComplexity > complexityThreshold) { - - List relatedInformation = new ArrayList<>(); - - relatedInformation.add(RelatedInformation.create( - documentContext.getUri(), - methodSymbol.getSubNameRange(), - info.getMessage(methodSymbol.getName(), methodComplexity, complexityThreshold) - )); - - List secondaryLocations = - documentContext.getCognitiveComplexityData().getMethodsComplexitySecondaryLocations().get(methodSymbol); - - secondaryLocations.stream() - .map((ComplexitySecondaryLocation secondaryLocation) -> - RelatedInformation.create( - documentContext.getUri(), - secondaryLocation.getRange(), - secondaryLocation.getMessage() - ) - ) - .collect(Collectors.toCollection(() -> relatedInformation)); - diagnosticStorage.addDiagnostic( methodSymbol.getSubNameRange(), info.getMessage(methodSymbol.getName(), methodComplexity, complexityThreshold), diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommandModuleExportMethodsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommandModuleExportMethodsDiagnostic.java index 302a00b721b..8ddca5b0112 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommandModuleExportMethodsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommandModuleExportMethodsDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommentedCodeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommentedCodeDiagnostic.java index 6d1f9aa7adc..ed0f1cf42ff 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommentedCodeDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommentedCodeDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -87,7 +87,7 @@ public void configure(Map configuration) { threshold = ((Number) configuration.getOrDefault("threshold", threshold)).floatValue(); codeRecognizer = new CodeRecognizer(threshold, new BSLFootprint()); - String excludePrefixesString = (String) configuration.getOrDefault("exclusionPrefixes", ""); + var excludePrefixesString = (String) configuration.getOrDefault("exclusionPrefixes", ""); exclusionPrefixes = Arrays.stream(excludePrefixesString.split(",")) .map(String::trim) .filter(s -> !s.isEmpty()) @@ -138,11 +138,9 @@ private static List initNewGroup(Token comment) { } private boolean isAdjacent(Token comment, List currentGroup) { - - Token last = currentGroup.get(currentGroup.size() - 1); + var last = currentGroup.get(currentGroup.size() - 1); return last.getLine() + 1 == comment.getLine() && onlyEmptyDelimiters(last.getTokenIndex(), comment.getTokenIndex()); - } private boolean onlyEmptyDelimiters(int firstTokenIndex, int lastTokenIndex) { @@ -165,17 +163,17 @@ private boolean isCommentGroupNotMethodDescription(List commentGroup) { return true; } - final Token first = commentGroup.get(0); - final Token last = commentGroup.get(commentGroup.size() - 1); + final var first = commentGroup.get(0); + final var last = commentGroup.get(commentGroup.size() - 1); return methodDescriptions.stream().noneMatch(methodDescription -> methodDescription.contains(first, last)); } private void checkCommentGroup(List commentGroup) { - Token firstComment = commentGroup.get(0); - Token lastComment = commentGroup.get(commentGroup.size() - 1); + var firstComment = commentGroup.get(0); + var lastComment = commentGroup.get(commentGroup.size() - 1); - for (Token comment : commentGroup) { + for (var comment : commentGroup) { if (isTextParsedAsCode(comment.getText())) { diagnosticStorage.addDiagnostic(firstComment, lastComment); return; @@ -184,9 +182,9 @@ private void checkCommentGroup(List commentGroup) { } private boolean isTextParsedAsCode(String text) { - String uncommented = uncomment(text); + var uncommented = uncomment(text); - for (String prefix : exclusionPrefixes) { + for (var prefix : exclusionPrefixes) { if (uncommented.startsWith(prefix)) { return false; } @@ -195,16 +193,16 @@ private boolean isTextParsedAsCode(String text) { return false; } - BSLTokenizer tokenizer = new BSLTokenizer(uncommented); - final List tokens = tokenizer.getTokens(); + var tokenizer = new BSLTokenizer(uncommented); + final var tokens = tokenizer.getTokens(); // Если меньше двух токенов нет смысла анализировать - это код if (tokens.size() >= MINIMAL_TOKEN_COUNT) { - List tokenTypes = tokens.stream() + var tokenTypes = tokens.stream() .map(Token::getType) .filter(t -> t != BSLParser.WHITE_SPACE) - .collect(Collectors.toList()); + .toList(); // Если два идентификатора идут подряд - это не код for (int i = 0; i < tokenTypes.size() - 1; i++) { @@ -229,10 +227,10 @@ public List getQuickFixes( List diagnostics, CodeActionParams params, DocumentContext documentContext ) { - List textEdits = diagnostics.stream() + var textEdits = diagnostics.stream() .map(Diagnostic::getRange) .map(range -> new TextEdit(range, "")) - .collect(Collectors.toList()); + .toList(); return CodeActionProvider.createCodeActions( textEdits, diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommitTransactionOutsideTryCatchDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommitTransactionOutsideTryCatchDiagnostic.java index 385d7f77adc..458b235cd02 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommitTransactionOutsideTryCatchDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommitTransactionOutsideTryCatchDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic.java index 7566f10df85..e3ac9b5d531 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -26,9 +26,7 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.parser.BSLParser; -import com.github._1c_syntax.mdclasses.Configuration; import org.antlr.v4.runtime.tree.ParseTree; -import org.antlr.v4.runtime.tree.TerminalNode; @DiagnosticMetadata( type = DiagnosticType.ERROR, @@ -43,15 +41,14 @@ public class CommonModuleAssignDiagnostic extends AbstractVisitorDiagnostic { @Override public ParseTree visitLValue(BSLParser.LValueContext ctx) { - TerminalNode identifier = ctx.IDENTIFIER(); + var identifier = ctx.IDENTIFIER(); - if (identifier == null - || ctx.acceptor() != null) { + if (identifier == null || ctx.acceptor() != null) { return ctx; } - Configuration configuration = documentContext.getServerContext().getConfiguration(); - if (configuration.getCommonModule(identifier.getText()).isPresent()) { + var configuration = documentContext.getServerContext().getConfiguration(); + if (configuration.findCommonModule(identifier.getText()).isPresent()) { diagnosticStorage.addDiagnostic(identifier, info.getMessage(identifier.getText())); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic.java index 0a48aefbe73..8ea44f214be 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -27,8 +27,8 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; import java.util.regex.Matcher; @@ -45,9 +45,7 @@ DiagnosticTag.UNPREDICTABLE, DiagnosticTag.DESIGN } - ) - public class CommonModuleInvalidTypeDiagnostic extends AbstractCommonModuleNameDiagnostic { public CommonModuleInvalidTypeDiagnostic(LanguageServerConfiguration serverConfiguration) { @@ -55,7 +53,7 @@ public CommonModuleInvalidTypeDiagnostic(LanguageServerConfiguration serverConfi } @Override - protected boolean flagsCheck(MDCommonModule commonModule) { + protected boolean flagsCheck(CommonModule commonModule) { return !isServer(commonModule) && !isServerCall(commonModule) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleMissingAPIDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleMissingAPIDiagnostic.java index e38a1ae5786..2cc78e88f5d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleMissingAPIDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleMissingAPIDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java index 3ec85d7f004..506ff9de3c2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -27,9 +27,9 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.bsl.mdo.support.ReturnValueReuse; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, @@ -47,7 +47,6 @@ ) public class CommonModuleNameCachedDiagnostic extends AbstractCommonModuleNameDiagnostic { - private static final String REGEXP = "повторноеиспользование|повтисп|cached"; public CommonModuleNameCachedDiagnostic(LanguageServerConfiguration serverConfiguration) { @@ -55,9 +54,8 @@ public CommonModuleNameCachedDiagnostic(LanguageServerConfiguration serverConfig } @Override - protected boolean flagsCheck(MDCommonModule commonModule) { + protected boolean flagsCheck(CommonModule commonModule) { return commonModule.getReturnValuesReuse() == ReturnValueReuse.DURING_REQUEST || commonModule.getReturnValuesReuse() == ReturnValueReuse.DURING_SESSION; } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java index 03482e7ace6..2603085e3c3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -27,8 +27,8 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, @@ -53,10 +53,8 @@ public CommonModuleNameClientDiagnostic(LanguageServerConfiguration serverConfig } @Override - protected boolean flagsCheck(MDCommonModule commonModule) { + protected boolean flagsCheck(CommonModule commonModule) { return !commonModule.isGlobal() && isClient(commonModule); } - - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java index 42a27c2bdea..b0c6da6fcde 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -27,8 +27,8 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, @@ -53,7 +53,7 @@ public CommonModuleNameClientServerDiagnostic(LanguageServerConfiguration server } @Override - protected boolean flagsCheck(MDCommonModule commonModule) { + protected boolean flagsCheck(CommonModule commonModule) { return isClientServer(commonModule); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java index a1eb2991bed..46a1c2f0111 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -27,8 +27,8 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; @DiagnosticMetadata( type = DiagnosticType.SECURITY_HOTSPOT, @@ -53,7 +53,7 @@ public CommonModuleNameFullAccessDiagnostic(LanguageServerConfiguration serverCo } @Override - protected boolean flagsCheck(MDCommonModule commonModule) { + protected boolean flagsCheck(CommonModule commonModule) { return commonModule.isPrivileged(); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java index 16a08af8118..70837a88eae 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -27,8 +27,8 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, @@ -51,7 +51,7 @@ public CommonModuleNameGlobalClientDiagnostic(LanguageServerConfiguration server } @Override - protected boolean flagsCheck(MDCommonModule commonModule) { + protected boolean flagsCheck(CommonModule commonModule) { return commonModule.isGlobal() && isClient(commonModule); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java index 4fb881e7eac..f73ba62ff37 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -27,8 +27,8 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, @@ -53,7 +53,7 @@ public CommonModuleNameGlobalDiagnostic(LanguageServerConfiguration serverConfig } @Override - protected boolean flagsCheck(MDCommonModule commonModule) { + protected boolean flagsCheck(CommonModule commonModule) { return commonModule.isGlobal(); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java index 7e7f663dcfd..2eade626760 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameServerCallDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -27,8 +27,8 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, @@ -53,7 +53,7 @@ public CommonModuleNameServerCallDiagnostic(LanguageServerConfiguration serverCo } @Override - protected boolean flagsCheck(MDCommonModule commonModule) { + protected boolean flagsCheck(CommonModule commonModule) { return isServerCall(commonModule); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic.java index e2c21f44829..ab3e7ca8d5d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,8 +28,8 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; import com.github._1c_syntax.utils.CaseInsensitivePattern; import java.util.Map; @@ -73,7 +73,7 @@ public void configure(Map configuration) { } @Override - protected boolean flagsCheck(MDCommonModule commonModule) { + protected boolean flagsCheck(CommonModule commonModule) { return true; } @@ -81,6 +81,4 @@ protected boolean flagsCheck(MDCommonModule commonModule) { protected boolean matchCheck(Matcher matcher) { return matcher.find(); } - } - diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CompilationDirectiveLostDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CompilationDirectiveLostDiagnostic.java index abdf0ae141d..ff1da5b29c7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CompilationDirectiveLostDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CompilationDirectiveLostDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -26,10 +26,10 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdo.Form; import com.github._1c_syntax.bsl.mdo.support.FormType; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDOForm; import org.antlr.v4.runtime.tree.ParseTree; @DiagnosticMetadata( @@ -53,11 +53,8 @@ public class CompilationDirectiveLostDiagnostic extends AbstractVisitorDiagnosti public ParseTree visitFile(BSLParser.FileContext ctx) { if (documentContext.getModuleType() == ModuleType.FormModule) { var mdo = documentContext.getMdObject(); - if (mdo.isPresent() && mdo.get() instanceof AbstractMDOForm) { - var form = (AbstractMDOForm) mdo.get(); - if (form.getFormType() != FormType.MANAGED) { - return ctx; - } + if (mdo.isPresent() && mdo.get() instanceof Form form && form.getFormType() != FormType.MANAGED) { + return ctx; } } return super.visitFile(ctx); @@ -65,22 +62,17 @@ public ParseTree visitFile(BSLParser.FileContext ctx) { @Override public ParseTree visitProcDeclaration(BSLParser.ProcDeclarationContext ctx) { - if (ctx.compilerDirective().isEmpty()) { diagnosticStorage.addDiagnostic(ctx.subName(), info.getMessage(ctx.subName().getText())); } - return ctx; } @Override public ParseTree visitFuncDeclaration(BSLParser.FuncDeclarationContext ctx) { - if (ctx.compilerDirective().isEmpty()) { diagnosticStorage.addDiagnostic(ctx.subName(), info.getMessage(ctx.subName().getText())); } - return ctx; } } - diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CompilationDirectiveNeedLessDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CompilationDirectiveNeedLessDiagnostic.java index 879830e85cd..a81be343837 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CompilationDirectiveNeedLessDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CompilationDirectiveNeedLessDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnostic.java index 0cfab71c729..94cd37bc67e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CrazyMultilineStringDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CrazyMultilineStringDiagnostic.java index 68b0e07ada8..c06324f8fab 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CrazyMultilineStringDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CrazyMultilineStringDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java index c177079958e..f045510e4f7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -25,16 +25,18 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.bsl.Constructors; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParser.AssignmentContext; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import com.github._1c_syntax.utils.CaseInsensitivePattern; +import edu.umd.cs.findbugs.annotations.Nullable; +import lombok.Getter; import lombok.ToString; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.RuleContext; import org.antlr.v4.runtime.tree.ParseTree; -import javax.annotation.CheckForNull; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; @@ -98,19 +100,7 @@ private static String getTypeFromConstValue(BSLParser.ConstValueContext constVal private static String getTypeFromNewExpressionContext(BSLParser.NewExpressionContext newExpression) { - String typeName = Optional.ofNullable(newExpression.typeName()) - .map(RuleContext::getText) - .or(() -> Optional.ofNullable(newExpression.doCall()) - .map(BSLParser.DoCallContext::callParamList) - .flatMap(callParamListContext -> callParamListContext.callParam().stream().findFirst()) - .map(BSLParser.CallParamContext::expression) - .map(BSLParser.ExpressionContext::member) - .flatMap(memberListContext -> memberListContext.stream().findFirst()) - .map(BSLParser.MemberContext::constValue) - .filter(constValue -> getTypeFromConstValue(constValue).equals(STRING_TYPE)) - .map(RuleContext::getText) - .map(constValueText -> constValueText.substring(1, constValueText.length() - 1)) - ) + String typeName = Constructors.typeName(newExpression) .orElse(UNDEFINED_TYPE); if (QUERY_BUILDER_PATTERN.matcher(typeName).matches()) { @@ -130,10 +120,9 @@ private static String getVariableNameFromCallStatementContext(BSLParser.CallStat private static String getVariableNameFromModifierContext(BSLParser.ModifierContext modifier) { ParserRuleContext parent = modifier.getParent(); - if (parent instanceof BSLParser.ComplexIdentifierContext) { - return getComplexPathName(((BSLParser.ComplexIdentifierContext) parent), modifier); - } else if (parent instanceof BSLParser.CallStatementContext) { - BSLParser.CallStatementContext parentCall = (BSLParser.CallStatementContext) parent; + if (parent instanceof BSLParser.ComplexIdentifierContext complexIdentifierContext) { + return getComplexPathName(complexIdentifierContext, modifier); + } else if (parent instanceof BSLParser.CallStatementContext parentCall) { return parentCall.modifier().stream() .takeWhile(e -> !e.equals(modifier)) @@ -145,7 +134,7 @@ private static String getVariableNameFromModifierContext(BSLParser.ModifierConte private static String getComplexPathName( BSLParser.ComplexIdentifierContext ci, - @CheckForNull BSLParser.ModifierContext to + @Nullable BSLParser.ModifierContext to ) { return ci.modifier().stream() @@ -226,7 +215,7 @@ private Set getTypesFromComplexIdentifier(BSLParser.ComplexIdentifierCon } } - private void visitDescendantCodeBlock(@CheckForNull BSLParser.CodeBlockContext ctx) { + private void visitDescendantCodeBlock(@Nullable BSLParser.CodeBlockContext ctx) { Optional.ofNullable(ctx) .map(e -> e.children) .stream() @@ -246,11 +235,10 @@ public ParseTree visitAccessCall(BSLParser.AccessCallContext ctx) { String variableName = null; BSLParserRuleContext errorContext = null; BSLParserRuleContext parent = ctx.getParent(); - if (parent instanceof BSLParser.CallStatementContext) { + if (parent instanceof BSLParser.CallStatementContext callStatementContext) { errorContext = parent; - variableName = getVariableNameFromCallStatementContext((BSLParser.CallStatementContext) parent); - } else if (parent instanceof BSLParser.ModifierContext) { - BSLParser.ModifierContext callModifier = (BSLParser.ModifierContext) parent; + variableName = getVariableNameFromCallStatementContext(callStatementContext); + } else if (parent instanceof BSLParser.ModifierContext callModifier) { errorContext = callModifier.getParent(); variableName = getVariableNameFromModifierContext(callModifier); } @@ -331,6 +319,7 @@ public void addDeclaration(ParseTree firstDeclaration) { } private static class Scope { + @Getter private final String name; private final HashMap variables = new HashMap<>(); @@ -352,10 +341,6 @@ public void addVariable(VariableDefinition variableDefinition, boolean typesMerg return key; }); } - - public String getName() { - return name; - } } private static class VariableScope extends ArrayDeque { @@ -369,7 +354,7 @@ public boolean codeFlowInCycle() { return flowType == CodeFlowType.CYCLE; } - public Optional getVariableByName(@CheckForNull String variableName) { + public Optional getVariableByName(@Nullable String variableName) { return Optional.ofNullable(current().variables.get(variableName)); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CyclomaticComplexityDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CyclomaticComplexityDiagnostic.java index 2617b20cfd3..1cef0d0f2b7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CyclomaticComplexityDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CyclomaticComplexityDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -46,7 +46,8 @@ minutesToFix = 25, tags = { DiagnosticTag.BRAINOVERLOAD - } + }, + extraMinForComplexity = 1 ) public class CyclomaticComplexityDiagnostic extends AbstractVisitorDiagnostic { private static final int COMPLEXITY_THRESHOLD = 20; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java index 1e5a2eee1b2..ba94092c82c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -34,7 +34,6 @@ import com.github._1c_syntax.utils.CaseInsensitivePattern; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; -import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Optional; @@ -97,7 +96,6 @@ private boolean checkPassed(BSLParser.ProcDeclarationContext ctx) { .isPresent(); } - @NotNull private Optional searchStatementWithCorrectLoadCondition(List context) { return context.stream() .limit(calculateStatementLimit(context.size())) @@ -117,7 +115,6 @@ && foundReturnStatement(context)) .isPresent(); } - @NotNull private Optional methodSymbol(BSLParser.ProcDeclarationContext ctx) { return Optional.of(documentContext.getSymbolTree()) .flatMap(symbolTree -> symbolTree.getMethodSymbol((BSLParser.SubContext) getSubContext(ctx))); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeletingCollectionItemDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeletingCollectionItemDiagnostic.java index 9aa4f57ced5..af89d4a194b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeletingCollectionItemDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeletingCollectionItemDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DenyIncompleteValuesDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DenyIncompleteValuesDiagnostic.java new file mode 100644 index 00000000000..c71a33eed50 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DenyIncompleteValuesDiagnostic.java @@ -0,0 +1,70 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.MdoRefBuilder; +import com.github._1c_syntax.bsl.mdo.MD; +import com.github._1c_syntax.bsl.mdo.Register; +import com.github._1c_syntax.bsl.mdo.children.Dimension; +import com.github._1c_syntax.bsl.types.MDOType; + +import java.util.List; + +@DiagnosticMetadata( + activatedByDefault = false, + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 1, + tags = { + DiagnosticTag.BADPRACTICE + }, + scope = DiagnosticScope.BSL, + canLocateOnProject = true +) +public class DenyIncompleteValuesDiagnostic extends AbstractMetadataDiagnostic { + + public DenyIncompleteValuesDiagnostic() { + super(List.of( + MDOType.INFORMATION_REGISTER, + MDOType.ACCUMULATION_REGISTER, + MDOType.ACCOUNTING_REGISTER, + MDOType.CALCULATION_REGISTER + )); + } + + @Override + protected void checkMetadata(MD mdo) { + if (mdo instanceof Register register) { + register.getDimensions().stream() + .filter(dimension -> !dimension.isDenyIncompleteValues()) + .forEach((Dimension dimension) -> { + var ownerMDOName = MdoRefBuilder.getLocaleOwnerMdoName(documentContext, mdo); + addDiagnostic(info.getMessage(dimension.getName(), ownerMDOName)); + }); + } + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic.java index 5d018afe454..8bb67b78760 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312Diagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic.java index 501fe04f3ed..cb84bad039e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedFindDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedFindDiagnostic.java index 961762338b3..ac772f0d51f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedFindDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedFindDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMessageDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMessageDiagnostic.java index b8d35c5d7f3..cb474d45ca5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMessageDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMessageDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnostic.java index b80dc6b6355..09af0c0227a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,8 +28,8 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; -import com.github._1c_syntax.bsl.languageserver.references.model.Reference; import com.github._1c_syntax.bsl.languageserver.references.ReferenceIndex; +import com.github._1c_syntax.bsl.languageserver.references.model.Reference; import lombok.RequiredArgsConstructor; import org.eclipse.lsp4j.SymbolKind; @@ -56,9 +56,9 @@ public void check() { .filter(reference -> reference.getSymbol().isDeprecated()) .filter(reference -> !reference.getFrom().isDeprecated()) .forEach((Reference reference) -> { - Symbol deprecatedSymbol = reference.getSymbol(); - String deprecationInfo = getDeprecationInfo(deprecatedSymbol); - String message = info.getMessage(deprecatedSymbol.getName(), deprecationInfo); + var deprecatedSymbol = reference.getSymbol(); + var deprecationInfo = getDeprecationInfo(deprecatedSymbol); + var message = info.getMessage(deprecatedSymbol.getName(), deprecationInfo); diagnosticStorage.addDiagnostic(reference.getSelectionRange(), message); }); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java index 7d65aefb66d..73fabc6f0b7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310Diagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java index 5377ab9c45b..31830eb464c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317Diagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedTypeManagedFormDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedTypeManagedFormDiagnostic.java index 6fcc0a21f8b..36d73a5ea2a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedTypeManagedFormDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedTypeManagedFormDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,7 +29,6 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.providers.CodeActionProvider; -import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.utils.CaseInsensitivePattern; import org.antlr.v4.runtime.tree.ParseTree; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java index d0f80bc3245..b23e3903e74 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticStorage.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,6 +24,7 @@ import com.github._1c_syntax.bsl.languageserver.context.symbol.SourceDefinedSymbol; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; +import edu.umd.cs.findbugs.annotations.Nullable; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; @@ -32,7 +33,6 @@ import org.eclipse.lsp4j.DiagnosticRelatedInformation; import org.eclipse.lsp4j.Range; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Queue; @@ -209,10 +209,10 @@ public void addDiagnostic( } public void addDiagnostic(ParseTree tree) { - if (tree instanceof BSLParserRuleContext) { - addDiagnostic((BSLParserRuleContext) tree); - } else if (tree instanceof TerminalNode) { - addDiagnostic((TerminalNode) tree); + if (tree instanceof BSLParserRuleContext parserRuleContext) { + addDiagnostic(parserRuleContext); + } else if (tree instanceof TerminalNode terminalNode) { + addDiagnostic(terminalNode); } else { throw new IllegalArgumentException("Unsupported parameter type " + tree); } @@ -253,5 +253,4 @@ private static Diagnostic createDiagnostic( } return diagnostic; } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DisableSafeModeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DisableSafeModeDiagnostic.java new file mode 100644 index 00000000000..5846126f22f --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DisableSafeModeDiagnostic.java @@ -0,0 +1,83 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.utils.CaseInsensitivePattern; + +import java.util.Optional; +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.VULNERABILITY, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 15, + tags = { + DiagnosticTag.SUSPICIOUS + }, + scope = DiagnosticScope.BSL +) +public class DisableSafeModeDiagnostic extends AbstractFindMethodDiagnostic { + private static final Pattern methodPattern = CaseInsensitivePattern.compile( + "УстановитьБезопасныйРежим|SetSafeMode|УстановитьОтключениеБезопасногоРежима|SetSafeModeDisabled"); + private static final Pattern safeModePattern = CaseInsensitivePattern.compile( + "УстановитьБезопасныйРежим|SetSafeMode"); + + public DisableSafeModeDiagnostic() { + super(methodPattern); + } + + @Override + protected boolean checkGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { + final var result = super.checkGlobalMethodCall(ctx); + if (!result) { + return false; + } + final int enabledValue; + if(safeModePattern.matcher(ctx.methodName().getText()).matches()){ + enabledValue = BSLParser.TRUE; + } else { + enabledValue = BSLParser.FALSE; + } + return !enabledCall(ctx, enabledValue); + } + + private static boolean enabledCall(BSLParser.GlobalMethodCallContext ctx, int enabledValue) { + return Optional.of(ctx) + .map(BSLParser.GlobalMethodCallContext::doCall) + .map(BSLParser.DoCallContext::callParamList) + .map(BSLParser.CallParamListContext::callParam) + .filter(callParamContexts -> callParamContexts.size() == 1) + .map(callParamContexts -> callParamContexts.get(0)) + .map(BSLParser.CallParamContext::expression) + .map(BSLParser.ExpressionContext::member) + .map(memberContexts -> memberContexts.get(0)) + .map(BSLParser.MemberContext::constValue) + .filter(constValueContext -> constValueContext.getToken(enabledValue, 0) != null) + .isPresent(); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java new file mode 100644 index 00000000000..00c222a61d0 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic.java @@ -0,0 +1,115 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.Trees; +import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.BinaryOperationNode; +import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.BslExpression; +import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.BslOperator; +import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.ExpressionNodeType; +import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.UnaryOperationNode; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 3, + tags = { + DiagnosticTag.BRAINOVERLOAD, + DiagnosticTag.BADPRACTICE + } +) +public class DoubleNegativesDiagnostic extends AbstractExpressionTreeDiagnostic { + + @Override + protected void visitBinaryOperation(BinaryOperationNode node) { + + if (node.getOperator() != BslOperator.EQUAL && node.getOperator() != BslOperator.NOT_EQUAL) { + super.visitBinaryOperation(node); + return; + } + + var parent = node.getParent(); + + if (parent == null || !isNegationOperator(parent)) { + super.visitBinaryOperation(node); + return; + } + + if (node.getOperator() == BslOperator.NOT_EQUAL) { + addDiagnostic(node); + } + + super.visitBinaryOperation(node); + } + + @Override + protected void visitUnaryOperation(UnaryOperationNode node) { + if (node.getOperator() == BslOperator.NOT && + node.getParent() != null && + node.getParent().getNodeType() == ExpressionNodeType.UNARY_OP) { + + var unaryParent = node.getParent().cast(); + if (unaryParent.getOperator() == BslOperator.NOT) { + addDiagnostic(node); + } + } + + super.visitUnaryOperation(node); + } + + private static boolean isNegationOperator(BslExpression parent) { + return parent.getNodeType() == ExpressionNodeType.UNARY_OP + && parent.cast().getOperator() == BslOperator.NOT; + } + + private void addDiagnostic(BinaryOperationNode node) { + var startToken = Trees.getTokens(node.getParent().getRepresentingAst()) + .stream() + .findFirst() + .orElseThrow(); + + var endToken = Trees.getTokens(node.getRight().getRepresentingAst()) + .stream() + .reduce((one, two) -> two) + .orElseThrow(); + + diagnosticStorage.addDiagnostic(startToken, endToken); + } + + private void addDiagnostic(UnaryOperationNode node) { + var startToken = Trees.getTokens(node.getParent().getRepresentingAst()) + .stream() + .findFirst() + .orElseThrow(); + + var endToken = Trees.getTokens(node.getOperand().getRepresentingAst()) + .stream() + .reduce((one, two) -> two) + .orElseThrow(); + + diagnosticStorage.addDiagnostic(startToken, endToken); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicateRegionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicateRegionDiagnostic.java index 176317f513b..7a6e3065d27 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicateRegionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicateRegionDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicateStringLiteralDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicateStringLiteralDiagnostic.java index 6577aaaa046..efe87febbad 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicateStringLiteralDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicateStringLiteralDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicatedInsertionIntoCollectionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicatedInsertionIntoCollectionDiagnostic.java new file mode 100644 index 00000000000..aa2699ceb77 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicatedInsertionIntoCollectionDiagnostic.java @@ -0,0 +1,388 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticParameter; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.languageserver.utils.RelatedInformation; +import com.github._1c_syntax.bsl.languageserver.utils.Trees; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.bsl.parser.BSLParser.AssignmentContext; +import com.github._1c_syntax.bsl.parser.BSLParser.CallParamContext; +import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; +import com.github._1c_syntax.utils.CaseInsensitivePattern; +import edu.umd.cs.findbugs.annotations.Nullable; +import lombok.Value; +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.TerminalNode; +import org.apache.commons.collections4.map.CaseInsensitiveMap; +import org.eclipse.lsp4j.Range; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 1, + tags = { + DiagnosticTag.BRAINOVERLOAD, + DiagnosticTag.SUSPICIOUS, + DiagnosticTag.BADPRACTICE + } +) +public class DuplicatedInsertionIntoCollectionDiagnostic extends AbstractVisitorDiagnostic { + private static final Pattern INSERT_ADD_METHOD_PATTERN = + CaseInsensitivePattern.compile("вставить|добавить|insert|add"); + private static final Pattern INSERT_METHOD_PATTERN = CaseInsensitivePattern.compile("вставить|insert"); + private static final Pattern IGNORED_BSL_VALUES_PATTERN = CaseInsensitivePattern.compile( + "неопределено|undefined|0|символы\\.[\\wа-яё]+|chars\\.[\\wа-яё]+"); + + private static final List BREAKERS_INDEXES = Arrays.asList(BSLParser.RULE_returnStatement, + BSLParser.RULE_breakStatement, BSLParser.RULE_continueStatement, BSLParser.RULE_raiseStatement); + private static final List BREAKERS_ROOTS = Arrays.asList(BSLParser.RULE_forEachStatement, + BSLParser.RULE_forStatement, BSLParser.RULE_whileStatement, BSLParser.RULE_tryStatement); + + private static final int LENGTH_OF_EMPTY_STRING_WITH_QUOTES = 2; + private static final boolean IS_ALLOWED_METHOD_ADD = true; + + @DiagnosticParameter( + type = Boolean.class, + defaultValue = "" + IS_ALLOWED_METHOD_ADD + ) + private boolean isAllowedMethodADD = IS_ALLOWED_METHOD_ADD; + private Pattern methodPattern = INSERT_ADD_METHOD_PATTERN; + + // ленивое вычисление всех полей, только в нужный момент + private BSLParser.CodeBlockContext codeBlock; + private Range blockRange; + private List blockAssignments; + private List blockBreakers; + private List blockCallParams; + private List firstParamInnerIdentifiers; + + @Value + private static class GroupingData { + BSLParser.CallStatementContext callStatement; + String collectionName; + String collectionNameWithDot; + String methodName; + String firstParamName; + String firstParamNameWithDot; + CallParamContext firstParamContext; + } + + @Override + public void configure(Map configuration) { + super.configure(configuration); + + if (!isAllowedMethodADD) { + methodPattern = INSERT_METHOD_PATTERN; + } + } + + @Override + public ParseTree visitCodeBlock(BSLParser.CodeBlockContext codeBlock) { + this.codeBlock = codeBlock; + final var possibleDuplicateStatements = getPossibleDuplicates(); + + if (!possibleDuplicateStatements.isEmpty()) { + blockRange = Ranges.create(codeBlock); + explorePossibleDuplicateStatements(possibleDuplicateStatements) + .forEach(this::fireIssue); + } + clearCodeBlockFields(); + return super.visitCodeBlock(codeBlock); + } + + private List getPossibleDuplicates() { + return codeBlock.statement().stream() + .map(BSLParser.StatementContext::callStatement) + .filter(Objects::nonNull) + .filter(callStatement -> callStatement.accessCall() != null) + .map(callStatement -> groupingCalls(callStatement, callStatement.accessCall())) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + private @Nullable GroupingData groupingCalls(BSLParser.CallStatementContext callStatement, + BSLParser.AccessCallContext accessCallContext) { + final var methodCallContext = accessCallContext.methodCall(); + final var callParams = methodCallContext.doCall().callParamList().callParam(); + final var firstParamContext = callParams.get(0); + if (firstParamContext.getChildCount() == 0) { + return null; + } + final var methodName = methodCallContext.methodName().getText(); + if (!isAppropriateMethodCall(methodName)) { + return null; + } + var firstParam = firstParamContext.getText(); + if (isBlankBSLString(firstParam) || isIgnoredBSLValues(firstParam)) { + return null; + } + final TerminalNode identifierContext; + final String parens; + if (callStatement.IDENTIFIER() != null) { + identifierContext = callStatement.IDENTIFIER(); + parens = ""; + } else { + identifierContext = callStatement.globalMethodCall().methodName().IDENTIFIER(); + parens = "()"; + } + final var collectionName = getFullIdentifier(identifierContext.getText().concat(parens), callStatement.modifier()); + + return new GroupingData(callStatement, collectionName, collectionName.concat("."), methodName, + firstParam, firstParam.concat("."), firstParamContext); + } + + private boolean isAppropriateMethodCall(String methodName) { + return methodPattern.matcher(methodName).matches(); + } + + private static boolean isBlankBSLString(String text) { + final var length = text.length(); + + return length >= LENGTH_OF_EMPTY_STRING_WITH_QUOTES && text.charAt(0) == '"' && text.charAt(length - 1) == '"' + && text.substring(1, length - 1).isBlank(); + } + + private static boolean isIgnoredBSLValues(String text) { + return IGNORED_BSL_VALUES_PATTERN.matcher(text).matches(); + } + + private Stream> explorePossibleDuplicateStatements(List statements) { + final var mapOfMapsByIdentifier = statements.stream() + .collect(Collectors.groupingBy( + GroupingData::getCollectionName, + CaseInsensitiveMap::new, + Collectors.groupingBy( + GroupingData::getMethodName, + CaseInsensitiveMap::new, + Collectors.groupingBy( + GroupingData::getFirstParamName, + CaseInsensitiveMap::new, + Collectors.mapping(groupingData -> groupingData, Collectors.toList())) + ) + )); + return mapOfMapsByIdentifier.values().stream() + .flatMap(mapByMethod -> mapByMethod.values().stream()) + .flatMap(mapByFirstParam -> mapByFirstParam.values().stream()) + .filter(duplicates -> duplicates.size() > 1) + .map(this::excludeValidChanges) + .filter(duplicates -> duplicates.size() > 1); + } + + private List excludeValidChanges(List duplicates) { + var result = new ArrayList(); + for (var i = 0; i < duplicates.size(); i++) { + if (!excludeValidElements(duplicates, i, result)) { + break; + } + } + firstParamInnerIdentifiers = null; + return result; + } + + private boolean excludeValidElements(List duplicates, int currIndex, + List listForIssue) { + if (duplicates.size() - currIndex <= 1) { + return false; + } + final var first = duplicates.get(currIndex); + var alreadyAdd = !listForIssue.isEmpty() && listForIssue.get(listForIssue.size() - 1) == first; + for (int i = currIndex + 1; i < duplicates.size(); i++) { + final var next = duplicates.get(i); + if (hasValidChange(first, next)) { + break;// последующие элементы нет смысла проверять, их нужно исключать + } + if (!alreadyAdd) { + alreadyAdd = true; + listForIssue.add(first); + } + listForIssue.add(next); + } + return true; + } + + private boolean hasValidChange(GroupingData first, GroupingData next) { + final var border = Ranges.create(first.callStatement.getStop(), next.callStatement.getStart()); + return hasAssignBetweenCalls(first, border) + || hasBreakersBetweenCalls(border) + || usedAsFunctionParamsBetweenCalls(border, first); + } + + private boolean hasAssignBetweenCalls(GroupingData groupingData, Range border) { + return getAssignments().stream() + .filter(assignmentContext -> Ranges.containsRange(border, Ranges.create(assignmentContext))) + .map(assignmentContext -> assignmentContext.lValue().getText()) + .anyMatch(assignText -> usedIdentifiers(assignText, groupingData)); + } + + private boolean usedIdentifiers(String expression, GroupingData groupingData) { + final var expressionWithDot = expression.concat("."); + if (startWithIgnoreCase(groupingData.collectionNameWithDot, expressionWithDot)) { + return true; + } + return getAllInnerIdentifiersWithDot(groupingData.firstParamContext).stream() + .anyMatch(identifierWithDot -> + startWithIgnoreCase(identifierWithDot, expressionWithDot) + || startWithIgnoreCase(expressionWithDot, identifierWithDot) + ); + } + + private static boolean startWithIgnoreCase(String identifier, String textWithDot) { + return identifier.length() >= textWithDot.length() + && identifier.substring(0, textWithDot.length()).equalsIgnoreCase(textWithDot); + } + + private boolean hasBreakersBetweenCalls(Range border) { + return getBreakers().stream() + .filter(bslParserRuleContext -> Ranges.containsRange(border, Ranges.create(bslParserRuleContext))) + .anyMatch(this::hasBreakerIntoCodeBlock); + } + + private boolean hasBreakerIntoCodeBlock(BSLParserRuleContext breakerContext) { + if (breakerContext.getRuleIndex() == BSLParser.RULE_returnStatement) { + return true; + } + final var rootParent = Trees.getRootParent(breakerContext, BREAKERS_ROOTS); + if (rootParent == null) { + return true; // сюда должны попасть, только если модуль не по грамматике, но иначе ругань на возможный null + } + return !Ranges.containsRange(blockRange, Ranges.create(rootParent)); + } + + private boolean usedAsFunctionParamsBetweenCalls(Range border, GroupingData groupingData) { + return getCallParams().stream() + .filter(callParamContext -> Ranges.containsRange(border, Ranges.create(callParamContext))) + .anyMatch(callParamContext -> usedAsFunctionParams(callParamContext, groupingData)); + } + + private boolean usedAsFunctionParams(CallParamContext callParamContext, GroupingData groupingData) { + return Optional.of(callParamContext) + .map(CallParamContext::expression) + .map(BSLParser.ExpressionContext::member) + .filter(memberContexts -> usedIdentifiers(memberContexts, groupingData)) + .isPresent(); + } + + private boolean usedIdentifiers(List memberContexts, GroupingData groupingData) { + return memberContexts.stream() + .map(BSLParser.MemberContext::complexIdentifier) + .filter(Objects::nonNull) + .filter(complexIdentifierContext -> complexIdentifierContext.IDENTIFIER() != null) + .map(BSLParserRuleContext::getText) + .anyMatch(identifier -> usedIdentifiers(identifier, groupingData)); + } + + private void fireIssue(List duplicates) { + final var dataForIssue = duplicates.get(1); + final var relatedInformationList = duplicates.stream() + .map(GroupingData::getCallStatement) + .map(context -> RelatedInformation.create( + documentContext.getUri(), + Ranges.create(context), + "+1" + )).collect(Collectors.toList()); + final var message = info.getMessage(dataForIssue.firstParamName, dataForIssue.collectionName); + diagnosticStorage.addDiagnostic(dataForIssue.callStatement, message, relatedInformationList); + } + + private List getAssignments() { + if (blockAssignments == null) { + blockAssignments = Trees.findAllRuleNodes(codeBlock, BSLParser.RULE_assignment).stream() + .map(AssignmentContext.class::cast) + .collect(Collectors.toUnmodifiableList()); + } + return blockAssignments; + } + + private List getBreakers() { + if (blockBreakers == null) { + blockBreakers = Trees.findAllRuleNodes(codeBlock, BREAKERS_INDEXES).stream() + .map(BSLParserRuleContext.class::cast) + .collect(Collectors.toUnmodifiableList()); + } + return blockBreakers; + } + + private List getCallParams() { + if (blockCallParams == null) { + blockCallParams = Trees.findAllRuleNodes(codeBlock, BSLParser.RULE_callParam).stream() + .map(CallParamContext.class::cast) + .collect(Collectors.toUnmodifiableList()); + } + return blockCallParams; + } + + private List getAllInnerIdentifiersWithDot(CallParamContext param) { + if (firstParamInnerIdentifiers == null) { + final var identifiers = Trees.findAllRuleNodes(param, BSLParser.RULE_complexIdentifier).stream() + .map(BSLParser.ComplexIdentifierContext.class::cast) + .filter(complexIdentifierContext -> complexIdentifierContext.IDENTIFIER() != null) + .toList(); + final var reducedIdentifiers = new ArrayList(); + for (BSLParser.ComplexIdentifierContext identifier : identifiers) { + final List modifiers = identifier.modifier(); + final var firstIdentifier = identifier.IDENTIFIER().getText(); + var fullIdentifier = getFullIdentifier(firstIdentifier, modifiers); + reducedIdentifiers.add(fullIdentifier); + + var reducedIdentifier = firstIdentifier; + for (var modifier : modifiers) { + var text = modifier.getText(); + reducedIdentifier = reducedIdentifier.concat(".").concat(text); + reducedIdentifiers.add(reducedIdentifier); + } + } + firstParamInnerIdentifiers = reducedIdentifiers; + } + return firstParamInnerIdentifiers; + } + + private void clearCodeBlockFields() { + codeBlock = null; + blockRange = null; + blockAssignments = null; + blockBreakers = null; + blockCallParams = null; + } + + private static String getFullIdentifier(String firstIdentifier, List modifiers) { + return modifiers.stream() + .map(BSLParserRuleContext::getText) + .reduce(firstIdentifier, (x, y) -> x.concat(".").concat(y)) + .replace("..", "."); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyCodeBlockDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyCodeBlockDiagnostic.java index 1b68f1cd8c0..5f612dc574c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyCodeBlockDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyCodeBlockDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -32,10 +32,7 @@ import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; -import org.antlr.v4.runtime.tree.Tree; -import java.util.List; -import java.util.stream.Collectors; import java.util.stream.Stream; @DiagnosticMetadata( @@ -84,10 +81,10 @@ public ParseTree visitCodeBlock(BSLParser.CodeBlockContext ctx) { int lineOfStop = ctx.getStop().getLine(); - List list = Trees.getChildren(ctx.getParent()).stream() + var list = Trees.getChildren(ctx.getParent()).stream() .filter(TerminalNode.class::isInstance) .filter(node -> ((TerminalNode) node).getSymbol().getLine() == lineOfStop) - .collect(Collectors.toList()); + .toList(); if (!list.isEmpty()) { TerminalNode first = (TerminalNode) list.get(0); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java index 4c169169d76..4bb5511a7c7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyStatementDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyStatementDiagnostic.java index d19fcb4621f..f5466e59819 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyStatementDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyStatementDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java index edad334ea7b..568a162acd2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnostic.java index c09aa5c3803..3c770fc65dc 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.java index f4fabb7e0c5..c8c42623920 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -26,9 +26,9 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; import org.antlr.v4.runtime.tree.ParseTree; @DiagnosticMetadata( @@ -50,8 +50,8 @@ public class ExecuteExternalCodeInCommonModuleDiagnostic extends AbstractExecute public ParseTree visitFile(BSLParser.FileContext ctx) { // если модуль не серверный, не внешнее соединение и не обычный клиент, то не проверяем if (documentContext.getMdObject() - .filter(MDCommonModule.class::isInstance) - .map(MDCommonModule.class::cast) + .filter(CommonModule.class::isInstance) + .map(CommonModule.class::cast) .filter(commonModule -> commonModule.isServer() || commonModule.isClientOrdinaryApplication() || commonModule.isExternalConnection()) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExportVariablesDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExportVariablesDiagnostic.java index 6a532816e6a..fccdb27adae 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExportVariablesDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExportVariablesDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExternalAppStartingDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExternalAppStartingDiagnostic.java new file mode 100644 index 00000000000..e200b465983 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExternalAppStartingDiagnostic.java @@ -0,0 +1,80 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticParameter; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.utils.CaseInsensitivePattern; + +import java.util.Map; +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.VULNERABILITY, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 5, + tags = { + DiagnosticTag.SUSPICIOUS + }, + scope = DiagnosticScope.BSL + +) +public class ExternalAppStartingDiagnostic extends AbstractFindMethodDiagnostic { + private static final String DEFAULT_PATTERN_STRING = + "КомандаСистемы|System|ЗапуститьСистему|RunSystem|ЗапуститьПриложение|RunApp" + + "|НачатьЗапускПриложения|BeginRunningApplication" + + "|ЗапуститьПриложениеАсинх|RunAppAsync|ЗапуститьПрограмму|ОткрытьПроводник|ОткрытьФайл"; + private static final String PATTERN_STRING_FOR_NAVI = + "|ПерейтиПоНавигационнойСсылке|GotoURL|ОткрытьНавигационнуюСсылку"; + private static final Pattern DEFAULT_PATTERN = CaseInsensitivePattern.compile(DEFAULT_PATTERN_STRING); + private static final boolean CHECK_GOTO_URL = false; + + @DiagnosticParameter( + type = Boolean.class, + defaultValue = "" + CHECK_GOTO_URL + ) + private boolean checkGotoUrl = CHECK_GOTO_URL; + + @DiagnosticParameter( + type = String.class, + defaultValue = DEFAULT_PATTERN_STRING + ) + private String userPatternString = DEFAULT_PATTERN_STRING; + + public ExternalAppStartingDiagnostic() { + super(DEFAULT_PATTERN); + } + + @Override + public void configure(Map configuration) { + super.configure(configuration); + var pattern = userPatternString; + if (checkGotoUrl){ + pattern += PATTERN_STRING_FOR_NAVI; + } + setMethodPattern(CaseInsensitivePattern.compile(pattern)); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExtraCommasDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExtraCommasDiagnostic.java index 22d73b16bca..4aa560a2ba5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExtraCommasDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExtraCommasDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FieldsFromJoinsWithoutIsNullDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FieldsFromJoinsWithoutIsNullDiagnostic.java index eab40dfe648..1f0e6e38935 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FieldsFromJoinsWithoutIsNullDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FieldsFromJoinsWithoutIsNullDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -30,11 +30,11 @@ import com.github._1c_syntax.bsl.languageserver.utils.Trees; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import com.github._1c_syntax.bsl.parser.SDBLParser; +import edu.umd.cs.findbugs.annotations.Nullable; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; import org.eclipse.lsp4j.DiagnosticRelatedInformation; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FileSystemAccessDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FileSystemAccessDiagnostic.java new file mode 100644 index 00000000000..9998d5c62e1 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FileSystemAccessDiagnostic.java @@ -0,0 +1,121 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticParameter; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.bsl.Constructors; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.utils.CaseInsensitivePattern; +import org.antlr.v4.runtime.tree.ParseTree; + +import java.util.Map; +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.VULNERABILITY, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 3, + tags = { + DiagnosticTag.SUSPICIOUS + }, + scope = DiagnosticScope.BSL, + activatedByDefault = false +) +public class FileSystemAccessDiagnostic extends AbstractFindMethodDiagnostic { + public static final String NEW_EXPRESSION = "File|Файл|xBase|HTMLWriter|ЗаписьHTML|HTMLReader|ЧтениеHTML" + + "|FastInfosetReader|ЧтениеFastInfoset|FastInfosetWriter|ЗаписьFastInfoset|XSLTransform|ПреобразованиеXSL" + + "|ZipFileWriter|ЗаписьZipФайла|ZipFileReader|ЧтениеZipФайла|TextReader|ЧтениеТекста|TextWriter|ЗаписьТекста" + + "|TextExtraction|ИзвлечениеТекста|BinaryData|ДвоичныеДанные|FileStream|ФайловыйПоток" + + "|FileStreamsManager|МенеджерФайловыхПотоков|DataWriter|ЗаписьДанных|DataReader|ЧтениеДанных"; + + public static final String GLOBAL_METHODS = "ЗначениеВФайл|ValueToFile|КопироватьФайл|FileCopy" + + "|ОбъединитьФайлы|MergeFiles|ПереместитьФайл|MoveFile|РазделитьФайл|SplitFile|СоздатьКаталог|CreateDirectory|" + + "УдалитьФайлы|DeleteFiles|КаталогПрограммы|BinDir|КаталогВременныхФайлов|TempFilesDir" + + "|КаталогДокументов|DocumentsDir|РабочийКаталогДанныхПользователя|UserDataWorkDir" + + "|НачатьПодключениеРасширенияРаботыСФайлами|BeginAttachingFileSystemExtension" + + "|НачатьУстановкуРасширенияРаботыСФайлами|BeginInstallFileSystemExtension" + + "|УстановитьРасширениеРаботыСФайлами|InstallFileSystemExtension" + + "|УстановитьРасширениеРаботыСФайламиАсинх|InstallFileSystemExtensionAsync" + + "|ПодключитьРасширениеРаботыСФайламиАсинх|AttachFileSystemExtensionAsync|" + + "КаталогВременныхФайловАсинх|TempFilesDirAsync|КаталогДокументовАсинх|DocumentsDirAsync" + + "|НачатьПолучениеКаталогаВременныхФайлов|BeginGettingTempFilesDir" + + "|НачатьПолучениеКаталогаДокументов|BeginGettingDocumentsDir" + + "|НачатьПолучениеРабочегоКаталогаДанныхПользователя|BeginGettingUserDataWorkDir" + + "|РабочийКаталогДанныхПользователяАсинх|UserDataWorkDirAsync" + + "|КопироватьФайлАсинх|CopyFileAsync|НайтиФайлыАсинх|FindFilesAsync|НачатьКопированиеФайла|BeginCopyingFile" + + "|НачатьПеремещениеФайла|BeginMovingFile|НачатьПоискФайлов|BeginFindingFiles" + + "|НачатьСозданиеДвоичныхДанныхИзФайла|BeginCreateBinaryDataFromFile" + + "|НачатьСозданиеКаталога|BeginCreatingDirectory" + + "|НачатьУдалениеФайлов|BeginDeletingFiles|ПереместитьФайлАсинх|MoveFileAsync" + + "|СоздатьДвоичныеДанныеИзФайлаАсинх|CreateBinaryDataFromFileAsync|СоздатьКаталогАсинх|CreateDirectoryAsync" + + "|УдалитьФайлыАсинх|DeleteFilesAsync"; + private static final Pattern GLOBAL_METHODS_PATTERN = getPattern(GLOBAL_METHODS); + + @DiagnosticParameter( + type = String.class, + defaultValue = GLOBAL_METHODS + ) + private String globalMethods = GLOBAL_METHODS; + + @DiagnosticParameter( + type = String.class, + defaultValue = NEW_EXPRESSION + ) + private String newExpression = NEW_EXPRESSION; + private Pattern newExpressionPattern = getPattern(newExpression); + + public FileSystemAccessDiagnostic() { + super(GLOBAL_METHODS_PATTERN); + } + + private static Pattern getPattern(String newExpression) { + return CaseInsensitivePattern.compile(newExpression); + } + + @Override + public void configure(Map configuration) { + super.configure(configuration); + setMethodPattern(getPattern(globalMethods)); + newExpressionPattern = getPattern(newExpression); + } + + @Override + protected boolean checkMethodCall(BSLParser.MethodCallContext ctx) { + return false; + } + + @Override + public ParseTree visitNewExpression(BSLParser.NewExpressionContext ctx) { + Constructors.typeName(ctx).ifPresent((String typeName) -> { + var matcherTypeName = newExpressionPattern.matcher(typeName); + if (matcherTypeName.matches()) { + diagnosticStorage.addDiagnostic(ctx); + } + }); + return super.visitNewExpression(ctx); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ForbiddenMetadataNameDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ForbiddenMetadataNameDiagnostic.java index fbf8aa9b1f6..991e4003f27 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ForbiddenMetadataNameDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ForbiddenMetadataNameDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,15 +28,14 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdo.AttributeOwner; +import com.github._1c_syntax.bsl.mdo.ChildrenOwner; +import com.github._1c_syntax.bsl.mdo.MD; import com.github._1c_syntax.bsl.types.MdoReference; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectComplex; -import com.github._1c_syntax.mdclasses.mdo.attributes.TabularSection; import com.github._1c_syntax.utils.CaseInsensitivePattern; import lombok.RequiredArgsConstructor; -import java.util.Collection; import java.util.regex.Pattern; @DiagnosticMetadata( @@ -54,7 +53,8 @@ ModuleType.ValueManagerModule, ModuleType.SessionModule }, - scope = DiagnosticScope.BSL + scope = DiagnosticScope.BSL, + canLocateOnProject = true ) @RequiredArgsConstructor public class ForbiddenMetadataNameDiagnostic extends AbstractMetadataDiagnostic { @@ -131,23 +131,15 @@ public class ForbiddenMetadataNameDiagnostic extends AbstractMetadataDiagnostic private final LanguageServerConfiguration serverConfiguration; @Override - protected void checkMetadata(AbstractMDObjectBase mdo) { + protected void checkMetadata(MD mdo) { // проверка имени метаданного checkName(mdo.getName(), mdo.getMdoReference()); - if (mdo instanceof AbstractMDObjectComplex) { - // проверка имен реквизитов и табличных частей - ((AbstractMDObjectComplex) mdo).getAttributes() - .forEach(attribute -> checkName(attribute.getName(), attribute.getMdoReference())); - - // проверка имен реквизитов табличных частей - ((AbstractMDObjectComplex) mdo).getAttributes().stream() - .filter(TabularSection.class::isInstance) - .map(TabularSection.class::cast) - .map(TabularSection::getAttributes) - .flatMap(Collection::stream) - .forEach(attribute -> checkName(attribute.getName(), attribute.getMdoReference())); + // проверка имен реквизитов и табличных частей + if (mdo instanceof AttributeOwner childrenOwner) { + childrenOwner.getPlainStorageFields() + .forEach(child -> checkName(child.getName(), child.getMdoReference())); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FormDataToValueDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FormDataToValueDiagnostic.java index 885c06558dd..33694483626 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FormDataToValueDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FormDataToValueDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FullOuterJoinQueryDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FullOuterJoinQueryDiagnostic.java index f5a8ef4d0c4..c8b31ad8e80 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FullOuterJoinQueryDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FullOuterJoinQueryDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionNameStartsWithGetDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionNameStartsWithGetDiagnostic.java index d333df99711..de2be848c42 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionNameStartsWithGetDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionNameStartsWithGetDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionOutParameterDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionOutParameterDiagnostic.java index 8fda177c080..c659a64838e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionOutParameterDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionOutParameterDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -35,7 +35,6 @@ import java.util.Collection; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -47,7 +46,6 @@ tags = { DiagnosticTag.DESIGN } - ) public class FunctionOutParameterDiagnostic extends AbstractVisitorDiagnostic { @@ -61,14 +59,13 @@ public ParseTree visitFunction(BSLParser.FunctionContext ctx) { .map(MethodSymbol::getParameters) .flatMap(Collection::stream) .filter(param -> !param.isByValue()) - .collect(Collectors.toList()); + .toList(); if (parameters.isEmpty()) { return ctx; } - Map lvalues = Trees - .findAllRuleNodes(ctx.subCodeBlock(), BSLParser.RULE_lValue) + var lvalues = Trees.findAllRuleNodes(ctx.subCodeBlock(), BSLParser.RULE_lValue) .stream() .collect( Collectors.toMap( diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java index 269d1f869d9..b50c1899539 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionShouldHaveReturnDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionShouldHaveReturnDiagnostic.java index e30b305040e..15e2f5caca4 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionShouldHaveReturnDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionShouldHaveReturnDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/GetFormMethodDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/GetFormMethodDiagnostic.java index 5eb29e3a1e0..1c4b33d2198 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/GetFormMethodDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/GetFormMethodDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/GlobalContextMethodCollision8312Diagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/GlobalContextMethodCollision8312Diagnostic.java index 49caddb6404..ea289717518 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/GlobalContextMethodCollision8312Diagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/GlobalContextMethodCollision8312Diagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IdenticalExpressionsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IdenticalExpressionsDiagnostic.java index 34eddd1ef54..7a58d665402 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IdenticalExpressionsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IdenticalExpressionsDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,20 +29,16 @@ import com.github._1c_syntax.bsl.languageserver.providers.FormatProvider; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import com.github._1c_syntax.bsl.languageserver.utils.Trees; -import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.AbstractCallNode; import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.BinaryOperationNode; import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.BslExpression; import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.BslOperator; import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.ExpressionNodeType; -import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.ExpressionParseTreeRewriter; import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.NodeEqualityComparer; -import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.TernaryOperatorNode; import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.TransitiveOperationsIgnoringComparer; import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.UnaryOperationNode; import com.github._1c_syntax.bsl.parser.BSLParser; import lombok.RequiredArgsConstructor; import org.antlr.v4.runtime.Token; -import org.antlr.v4.runtime.tree.ParseTree; import org.eclipse.lsp4j.FormattingOptions; import java.util.ArrayList; @@ -62,7 +58,7 @@ } ) @RequiredArgsConstructor -public class IdenticalExpressionsDiagnostic extends AbstractVisitorDiagnostic { +public class IdenticalExpressionsDiagnostic extends AbstractExpressionTreeDiagnostic { private static final int MIN_EXPRESSION_SIZE = 3; private static final String POPULAR_DIVISORS_DEFAULT_VALUE = "60, 1024"; @@ -73,7 +69,10 @@ public class IdenticalExpressionsDiagnostic extends AbstractVisitorDiagnostic { ) private Set popularDivisors = parseCommaSeparatedSet(POPULAR_DIVISORS_DEFAULT_VALUE); private final FormatProvider formatProvider; - + + private final List binaryOperations = new ArrayList<>(); + private BSLParser.ExpressionContext expressionContext; + private static Set parseCommaSeparatedSet(String values) { if (values.trim().isEmpty()) { return Collections.emptySet(); @@ -95,28 +94,41 @@ public void configure(Map configuration) { } @Override - public ParseTree visitExpression(BSLParser.ExpressionContext ctx) { - - if (sufficientSize(ctx)) { - return ctx; - } - - var tree = ExpressionParseTreeRewriter.buildExpressionTree(ctx); + protected ExpressionVisitorDecision onExpressionEnter(BSLParser.ExpressionContext ctx) { + expressionContext = ctx; + return sufficientSize(ctx)? ExpressionVisitorDecision.SKIP : ExpressionVisitorDecision.ACCEPT; + } - var binariesList = flattenBinaryOperations(tree); - if (binariesList.isEmpty()) { - return ctx; - } + @Override + protected void visitTopLevelExpression(BslExpression node) { + binaryOperations.clear(); + super.visitTopLevelExpression(node); var comparer = new TransitiveOperationsIgnoringComparer(); comparer.logicalOperationsAsTransitive(true); - binariesList + binaryOperations .stream() .filter(x -> checkEquality(comparer, x)) - .forEach(x -> diagnosticStorage.addDiagnostic(ctx, + .forEach(x -> diagnosticStorage.addDiagnostic(expressionContext, info.getMessage(x.getRepresentingAst().getText(), getOperandText(x)))); + } + + @Override + protected void visitBinaryOperation(BinaryOperationNode node) { + var operator = node.getOperator(); + + // разыменования отбросим, хотя comparer их и не зачтет, но для производительности + // лучше выкинем их сразу + if (operator == BslOperator.DEREFERENCE || operator == BslOperator.INDEX_ACCESS) { + return; + } - return ctx; + // одинаковые умножения и сложения - не считаем, см. тесты + if (operator != BslOperator.ADD && operator != BslOperator.MULTIPLY) { + binaryOperations.add(node); + } + + super.visitBinaryOperation(node); } private boolean checkEquality(NodeEqualityComparer comparer, BinaryOperationNode node) { @@ -212,52 +224,6 @@ private static void fillTokens(BslExpression node, List collection) { } } - private static List flattenBinaryOperations(BslExpression tree) { - var list = new ArrayList(); - gatherBinaryOperations(list, tree); - return list; - } - - private static void gatherBinaryOperations(List list, BslExpression tree) { - switch (tree.getNodeType()) { - case CALL: - for (var expr : tree.cast().arguments()) { - gatherBinaryOperations(list, expr); - } - break; - case UNARY_OP: - gatherBinaryOperations(list, tree.cast().getOperand()); - break; - case TERNARY_OP: - var ternary = (TernaryOperatorNode) tree; - gatherBinaryOperations(list, ternary.getCondition()); - gatherBinaryOperations(list, ternary.getTruePart()); - gatherBinaryOperations(list, ternary.getFalsePart()); - break; - case BINARY_OP: - var binary = (BinaryOperationNode) tree; - var operator = binary.getOperator(); - - // разыменования отбросим, хотя comparer их и не зачтет, но для производительности - // лучше выкинем их сразу - if (operator == BslOperator.DEREFERENCE || operator == BslOperator.INDEX_ACCESS) { - return; - } - - // одинаковые умножения и сложения - не считаем, см. тесты - if (operator != BslOperator.ADD && operator != BslOperator.MULTIPLY) { - list.add(binary); - } - - gatherBinaryOperations(list, binary.getLeft()); - gatherBinaryOperations(list, binary.getRight()); - break; - - default: - break; // для спокойствия сонара - } - } - private static boolean isComplementary(BinaryOperationNode binary) { var operator = binary.getOperator(); if ((operator == BslOperator.OR || operator == BslOperator.AND) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfConditionComplexityDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfConditionComplexityDiagnostic.java index d0a3d8d33fb..e6314791db1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfConditionComplexityDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfConditionComplexityDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedCodeBlockDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedCodeBlockDiagnostic.java index 5639e1b8358..c04c05d9d56 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedCodeBlockDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedCodeBlockDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,10 +29,10 @@ import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import com.github._1c_syntax.bsl.languageserver.utils.RelatedInformation; import com.github._1c_syntax.bsl.parser.BSLParser; +import jakarta.annotation.PostConstruct; import org.antlr.v4.runtime.tree.ParseTree; import org.eclipse.lsp4j.DiagnosticRelatedInformation; -import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -72,7 +72,7 @@ public ParseTree visitIfStatement(BSLParser.IfStatementContext ctx) { .collect(Collectors.toCollection(() -> codeBlocks)); - BSLParser.ElseBranchContext elseBranch = ctx.elseBranch(); + var elseBranch = ctx.elseBranch(); if (elseBranch != null) { codeBlocks.add(elseBranch.codeBlock()); } @@ -90,23 +90,21 @@ private void findDuplicatedCodeBlock(List codeBlockC } private void checkCodeBlock(List codeBlockContexts, int i) { - BSLParser.CodeBlockContext currentCodeBlock = codeBlockContexts.get(i); + var currentCodeBlock = codeBlockContexts.get(i); - List identicalCodeBlocks = codeBlockContexts.stream() + var identicalCodeBlocks = codeBlockContexts.stream() .skip(i) .filter(codeBlockContext -> !codeBlockContext.equals(currentCodeBlock) && !(currentCodeBlock.children == null && codeBlockContext.children == null) && DiagnosticHelper.equalNodes(currentCodeBlock, codeBlockContext)) - .collect(Collectors.toList()); + .toList(); if (identicalCodeBlocks.isEmpty()) { return; } - identicalCodeBlocks.stream() - .collect(Collectors.toCollection(() -> checkedBlocks)); - + identicalCodeBlocks.stream().collect(Collectors.toCollection(() -> checkedBlocks)); List relatedInformation = new ArrayList<>(); relatedInformation.add(RelatedInformation.create( diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedConditionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedConditionDiagnostic.java index 26363650c40..7e0a7874ca8 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedConditionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedConditionDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,10 +29,10 @@ import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import com.github._1c_syntax.bsl.languageserver.utils.RelatedInformation; import com.github._1c_syntax.bsl.parser.BSLParser; +import jakarta.annotation.PostConstruct; import org.antlr.v4.runtime.tree.ParseTree; import org.eclipse.lsp4j.DiagnosticRelatedInformation; -import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -85,22 +85,20 @@ private void findDuplicatedExpression(List expressi } private void checkExpression(List expressionContexts, int i) { - BSLParser.ExpressionContext currentExpression = expressionContexts.get(i); + var currentExpression = expressionContexts.get(i); - List identicalExpressions = expressionContexts.stream() + var identicalExpressions = expressionContexts.stream() .skip(i) .filter(expressionContext -> !expressionContext.equals(currentExpression) && DiagnosticHelper.equalNodes(currentExpression, expressionContext)) - .collect(Collectors.toList()); + .toList(); if (identicalExpressions.isEmpty()) { return; } - identicalExpressions.stream() - .collect(Collectors.toCollection(() -> checkedConditions)); - + identicalExpressions.stream().collect(Collectors.toCollection(() -> checkedConditions)); List relatedInformation = new ArrayList<>(); relatedInformation.add(RelatedInformation.create( @@ -121,6 +119,4 @@ private void checkExpression(List expressionContext diagnosticStorage.addDiagnostic(currentExpression, relatedInformation); } - } - diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseIfEndsWithElseDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseIfEndsWithElseDiagnostic.java index 06527306352..8aad571f03f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseIfEndsWithElseDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseIfEndsWithElseDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectLineBreakDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectLineBreakDiagnostic.java index 712d324e9aa..0048638cc22 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectLineBreakDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectLineBreakDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -71,7 +71,7 @@ public class IncorrectLineBreakDiagnostic extends AbstractDiagnostic { @DiagnosticParameter( type = String.class, - defaultValue = "" + DEFAULT_LIST_FOR_CHECK_START + defaultValue = DEFAULT_LIST_FOR_CHECK_START ) private Pattern listOfIncorrectFirstSymbol = createPatternIncorrectStartLine(DEFAULT_LIST_FOR_CHECK_START); @@ -83,7 +83,7 @@ public class IncorrectLineBreakDiagnostic extends AbstractDiagnostic { @DiagnosticParameter( type = String.class, - defaultValue = "" + DEFAULT_LIST_FOR_CHECK_END + defaultValue = DEFAULT_LIST_FOR_CHECK_END ) private Pattern listOfIncorrectLastSymbol = createPatternIncorrectEndLine(DEFAULT_LIST_FOR_CHECK_END); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectUseLikeInQueryDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectUseLikeInQueryDiagnostic.java index dc621404a88..0ae300b88f5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectUseLikeInQueryDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectUseLikeInQueryDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,11 +29,10 @@ import com.github._1c_syntax.bsl.languageserver.utils.Trees; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import com.github._1c_syntax.bsl.parser.SDBLParser; +import edu.umd.cs.findbugs.annotations.Nullable; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; -import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckForNull; import java.util.List; @DiagnosticMetadata( @@ -72,7 +71,7 @@ private void checkRightStatement(BSLParserRuleContext ctx, diagnosticStorage.addDiagnostic(ctx); } - @CheckForNull + @Nullable private static SDBLParser.PrimitiveExpressionContext getPrimitiveExpression(SDBLParser.ExpressionContext ctx) { var primitive = Trees.findAllRuleNodes(ctx, SDBLParser.RULE_primitiveExpression).stream() .filter(SDBLParser.PrimitiveExpressionContext.class::isInstance) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectUseOfStrTemplateDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectUseOfStrTemplateDiagnostic.java index 68a3b3f5c7c..cabca3f7589 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectUseOfStrTemplateDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectUseOfStrTemplateDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,9 +29,8 @@ import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import com.github._1c_syntax.utils.CaseInsensitivePattern; -import org.jetbrains.annotations.NotNull; +import edu.umd.cs.findbugs.annotations.Nullable; -import javax.annotation.Nullable; import java.util.HashSet; import java.util.Objects; import java.util.Optional; @@ -129,7 +128,6 @@ private static Optional getString(Optional c return getStringFromExpression(expressionContext); } - @NotNull private static Optional getStringFromExpression(Optional expressionContext) { final var LENGTH_OF_EMPTY_STRING_FROM_AST = 2; return getConstValue(expressionContext, true) @@ -138,8 +136,7 @@ private static Optional getStringFromExpression(Optional s.length() > LENGTH_OF_EMPTY_STRING_FROM_AST); } - @NotNull - private static Optional getConstValue(Optional expressionContext, + private static Optional getConstValue(Optional expressionContext, boolean isFullSearch) { return expressionContext .map(BSLParser.ExpressionContext::member) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InternetAccessDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InternetAccessDiagnostic.java new file mode 100644 index 00000000000..02a87177aa0 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InternetAccessDiagnostic.java @@ -0,0 +1,61 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.bsl.Constructors; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.utils.CaseInsensitivePattern; +import org.antlr.v4.runtime.tree.ParseTree; + +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.VULNERABILITY, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 60, + tags = { + DiagnosticTag.SUSPICIOUS + }, + activatedByDefault = false +) + +public class InternetAccessDiagnostic extends AbstractVisitorDiagnostic { + private static final Pattern PATTERN_NEW_EXPRESSION = CaseInsensitivePattern.compile( + "FTPСоединение|FTPConnection|HTTPСоединение|HTTPConnection|WSОпределения|WSDefinitions|WSПрокси|WSProxy" + + "|ИнтернетПочтовыйПрофиль|InternetMailProfile|ИнтернетПочта|InternetMail|Почта|Mail|HTTPЗапрос|HTTPRequest|" + + "ИнтернетПрокси|InternetProxy"); + + @Override + public ParseTree visitNewExpression(BSLParser.NewExpressionContext ctx) { + Constructors.typeName(ctx).ifPresent((String typeName) -> { + var matcherTypeName = PATTERN_NEW_EXPRESSION.matcher(typeName); + if (matcherTypeName.matches()) { + diagnosticStorage.addDiagnostic(ctx); + } + }); + return super.visitNewExpression(ctx); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java index 5ed149a3038..341bb84475a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,6 +28,7 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.providers.CodeActionProvider; import com.github._1c_syntax.bsl.parser.BSLLexer; +import jakarta.annotation.PostConstruct; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.Token; import org.eclipse.lsp4j.CodeAction; @@ -35,7 +36,6 @@ import org.eclipse.lsp4j.Diagnostic; import org.eclipse.lsp4j.TextEdit; -import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.List; import java.util.Set; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnostic.java index 80cd94b18df..dc146d99e81 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -30,9 +30,9 @@ import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import com.github._1c_syntax.utils.CaseInsensitivePattern; +import edu.umd.cs.findbugs.annotations.Nullable; import org.antlr.v4.runtime.tree.ParseTree; -import javax.annotation.Nullable; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/JoinWithSubQueryDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/JoinWithSubQueryDiagnostic.java index 4a93d6b573a..2008a90c662 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/JoinWithSubQueryDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/JoinWithSubQueryDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/JoinWithVirtualTableDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/JoinWithVirtualTableDiagnostic.java index da149fd34a6..5bccb424d2d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/JoinWithVirtualTableDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/JoinWithVirtualTableDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LatinAndCyrillicSymbolInWordDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LatinAndCyrillicSymbolInWordDiagnostic.java index 59b5e85a5c2..5b24f741559 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LatinAndCyrillicSymbolInWordDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LatinAndCyrillicSymbolInWordDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -86,7 +86,7 @@ public class LatinAndCyrillicSymbolInWordDiagnostic extends AbstractDiagnostic { @DiagnosticParameter( type = String.class, - defaultValue = "" + DEFAULT_EXCLUDE_WORDS + defaultValue = DEFAULT_EXCLUDE_WORDS ) private Pattern excludeWords = createExcludeWordPattern(DEFAULT_EXCLUDE_WORDS); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LineLengthDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LineLengthDiagnostic.java index be6ca23a349..0fb6dbcf730 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LineLengthDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LineLengthDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LogicalOrInTheWhereSectionOfQueryDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LogicalOrInTheWhereSectionOfQueryDiagnostic.java index 2747f9e4b59..dc684763a2d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LogicalOrInTheWhereSectionOfQueryDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LogicalOrInTheWhereSectionOfQueryDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java index 39ca0097788..24f4760e2b5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,9 +29,7 @@ import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import com.github._1c_syntax.utils.CaseInsensitivePattern; -import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; -import org.antlr.v4.runtime.tree.TerminalNode; import java.util.Arrays; import java.util.HashSet; @@ -60,16 +58,18 @@ public class MagicDateDiagnostic extends AbstractVisitorDiagnostic { ); private static final Pattern paramPattern = CaseInsensitivePattern.compile( - "\"\\d{8}.*" + "\"[0123]{1}\\d{7}\"|\"[0123]{1}\\d{13}\"" ); + private static final Pattern zeroPattern = Pattern.compile("^0+"); private static final Pattern nonNumberPattern = CaseInsensitivePattern.compile( "\\D" ); + public static final int MAX_YEAR_BY_1C = 9999; @DiagnosticParameter( type = String.class, - defaultValue = "" + DEFAULT_AUTHORIZED_DATES + defaultValue = DEFAULT_AUTHORIZED_DATES ) private final Set authorizedDates = new HashSet<>(Arrays.asList(DEFAULT_AUTHORIZED_DATES.split(","))); @@ -84,50 +84,116 @@ public void configure(Map configuration) { } @Override - public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { - Optional.of(ctx) - .filter(it -> methodPattern.matcher(it.methodName().getText()).matches()) - .map(BSLParser.GlobalMethodCallContext::doCall) - .map(BSLParser.DoCallContext::callParamList) - .filter(callParamList -> paramPattern.matcher(callParamList.getText()).matches()) - .ifPresent(this::checkExclAddDiagnostic); - - return super.visitGlobalMethodCall(ctx); + public ParseTree visitConstValue(BSLParser.ConstValueContext ctx) { + var tNode = ctx.DATETIME(); + var sNode = ctx.string(); + if ((tNode != null || sNode != null) && isAccepted(ctx)) { + if (sNode != null && !isValidDate(sNode)) { + return defaultResult(); + } + + final var expressionContext = getExpression(Optional.of(ctx)); + if (!insideSimpleDateAssignment(expressionContext) && !insideReturnSimpleDate(expressionContext) + && !insideAssignmentWithDateMethodForSimpleDate(expressionContext)) { + diagnosticStorage.addDiagnostic(ctx, info.getMessage(ctx.getText())); + } + } + + return defaultResult(); } - @Override - public ParseTree visitConstValue(BSLParser.ConstValueContext ctx) { - TerminalNode tNode = ctx.DATETIME(); - if (tNode != null) { - checkExclAddDiagnostic(ctx); + private static boolean isValidDate(BSLParser.StringContext ctx) { + final var text = ctx.getText(); + if (!paramPattern.matcher(text).matches()) { + return false; } + var strDate = text.substring(1, text.length() - 1); // убрать кавычки + return isValidDate(strDate); + } - return ctx; + private static boolean isValidDate(String strDate) { + var year = parseInt(strDate.substring(0, 4)); + if (year < 1 || year > MAX_YEAR_BY_1C) { + return false; + } + var month = parseInt(strDate.substring(4, 6)); + var day = parseInt(strDate.substring(6, 8)); + if (month < 1 || month > 12 || day < 1 || day > 31) { + return false; + } + if (strDate.length() == 8) { + return true; + } + var hh = parseInt(strDate.substring(8, 10)); + var mm = parseInt(strDate.substring(10, 12)); + var ss = parseInt(strDate.substring(12, 14)); + return hh <= 24 && mm <= 60 && ss <= 60; } - private void checkExclAddDiagnostic(BSLParserRuleContext ctx){ - String checked = ctx.getText(); - if (checked != null && !isExcluded(checked)) { - ParserRuleContext expression; - if (ctx instanceof BSLParser.CallParamListContext){ - expression = ctx.getParent().getParent().getParent().getParent().getParent(); - } else { - expression = ctx.getParent().getParent(); - } - if (expression instanceof BSLParser.ExpressionContext - && (!isAssignExpression((BSLParser.ExpressionContext) expression))) { - diagnosticStorage.addDiagnostic(ctx.stop, info.getMessage(checked)); - } + private static int parseInt(String text) { + String s = zeroPattern.matcher(text).replaceAll(""); + try { + return Integer.parseInt(s); + } catch (NumberFormatException e) { + return 0; } } - private boolean isExcluded(String sIn) { - String s = nonNumberPattern.matcher(sIn).replaceAll(""); + private boolean isAccepted(BSLParser.ConstValueContext ctx) { + String text = ctx.getText(); + return text != null && !text.isEmpty() && !isExcluded(text); + } + + private boolean isExcluded(String text) { + String s = nonNumberPattern.matcher(text).replaceAll(""); return authorizedDates.contains(s); } - private static boolean isAssignExpression(BSLParser.ExpressionContext expression) { - return (expression.getChildCount() <= 1); + private static Optional getExpression(Optional constValue) { + return constValue + .map(BSLParserRuleContext::getParent) + .filter(context -> context.getChildCount() == 1) + .map(BSLParserRuleContext::getParent) + .filter(context -> context.getChildCount() == 1) + .filter(BSLParser.ExpressionContext.class::isInstance) + .map(BSLParser.ExpressionContext.class::cast); + } + + private static boolean insideSimpleDateAssignment(Optional expression) { + return insideContext(expression, BSLParser.AssignmentContext.class); } + private static boolean insideContext(Optional expression, + Class assignmentContextClass) { + return expression + .map(BSLParserRuleContext::getParent) + .filter(assignmentContextClass::isInstance) + .isPresent(); + } + + private static boolean insideReturnSimpleDate(Optional expression) { + return insideContext(expression, BSLParser.ReturnStatementContext.class); + } + + private static boolean insideAssignmentWithDateMethodForSimpleDate(Optional expression) { + return expression + .map(BSLParserRuleContext::getParent) // callParam + .filter(context -> context.getChildCount() == 1) + .map(BSLParserRuleContext::getParent) // callParamList + .filter(context -> context.getChildCount() == 1) + .map(BSLParserRuleContext::getParent) // doCall + .map(BSLParserRuleContext::getParent) // globalCall - метод Дата(ХХХ) + .filter(BSLParser.GlobalMethodCallContext.class::isInstance) + .map(BSLParser.GlobalMethodCallContext.class::cast) + .filter(context -> methodPattern.matcher(context.methodName().getText()).matches()) + .map(BSLParserRuleContext::getParent) // complexId + .filter(context -> context.getChildCount() == 1) + .map(BSLParserRuleContext::getParent) // member + .filter(context -> context.getChildCount() == 1) + .map(BSLParserRuleContext::getParent) // expression + .filter(context -> context.getChildCount() == 1) + .map(BSLParserRuleContext::getParent) + .filter(BSLParser.AssignmentContext.class::isInstance) + .isPresent(); + } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java index d81157a5413..169863fd48d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,13 +28,14 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.utils.DiagnosticHelper; import com.github._1c_syntax.bsl.parser.BSLParser; -import org.antlr.v4.runtime.ParserRuleContext; +import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; +import java.util.Optional; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, @@ -49,10 +50,9 @@ public class MagicNumberDiagnostic extends AbstractVisitorDiagnostic { private static final String DEFAULT_AUTHORIZED_NUMBERS = "-1,0,1"; private static final boolean DEFAULT_ALLOW_MAGIC_NUMBER = true; - @DiagnosticParameter( type = String.class, - defaultValue = "" + DEFAULT_AUTHORIZED_NUMBERS + defaultValue = DEFAULT_AUTHORIZED_NUMBERS ) private final List authorizedNumbers = new ArrayList<>(Arrays.asList(DEFAULT_AUTHORIZED_NUMBERS.split(","))); @@ -75,37 +75,54 @@ public void configure(Map configuration) { } } + private static Optional getExpression(BSLParserRuleContext ctx) { + return Optional.of(ctx) + .filter(context -> context.getChildCount() == 1) + .map(BSLParserRuleContext::getParent) + .filter(context -> context.getChildCount() == 1) + .map(BSLParserRuleContext::getParent) + .filter(BSLParser.ExpressionContext.class::isInstance) + .map(BSLParser.ExpressionContext.class::cast); + } + + private static boolean isNumericExpression(BSLParser.ExpressionContext expression) { + return (expression.getChildCount() <= 1); + } + + private static boolean insideCallParam(BSLParser.ExpressionContext expression) { + return expression.getParent() instanceof BSLParser.CallParamContext; + } + @Override public ParseTree visitNumeric(BSLParser.NumericContext ctx) { String checked = ctx.getText(); - if (checked != null && !isExcluded(checked)) { - ParserRuleContext expression = ctx.getParent().getParent().getParent(); - if (expression instanceof BSLParser.ExpressionContext - && (!isNumericExpression((BSLParser.ExpressionContext) expression) - || mayBeNumberAccess((BSLParser.ExpressionContext) expression))) { + if (checked != null && isAllowed(checked)) { + final var parent = ctx.getParent(); + if (parent.getParent() instanceof BSLParser.DefaultValueContext || isWrongExpression(parent)) { diagnosticStorage.addDiagnostic(ctx.stop, info.getMessage(checked)); } } - - return ctx; + return defaultResult(); } - private boolean isExcluded(String s) { + private boolean isAllowed(String s) { for (String elem : this.authorizedNumbers) { if (s.compareTo(elem) == 0) { - return true; + return false; } } + return true; + } - return false; + private boolean isWrongExpression(BSLParserRuleContext numericContextParent) { + return getExpression(numericContextParent) + .filter((BSLParser.ExpressionContext expression) -> + (!isNumericExpression(expression) || mayBeNumberAccess(expression) || insideCallParam(expression))) + .isPresent(); } private boolean mayBeNumberAccess(BSLParser.ExpressionContext expression) { return !allowMagicIndexes && expression.getParent() instanceof BSLParser.AccessIndexContext; } - - private static boolean isNumericExpression(BSLParser.ExpressionContext expression) { - return (expression.getChildCount() <= 1); - } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MetadataObjectNameLengthDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MetadataObjectNameLengthDiagnostic.java index 662ca2f48f6..0ada0944c3a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MetadataObjectNameLengthDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MetadataObjectNameLengthDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,9 +29,9 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdo.MD; import com.github._1c_syntax.bsl.types.MDOType; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; import java.util.List; @@ -42,14 +42,15 @@ scope = DiagnosticScope.BSL, tags = { DiagnosticTag.STANDARD - } + }, + canLocateOnProject = true ) public class MetadataObjectNameLengthDiagnostic extends AbstractMetadataDiagnostic { - private final LanguageServerConfiguration serverConfiguration; - private static final int MAX_METADATA_OBJECT_NAME_LENGTH = 80; + private final LanguageServerConfiguration serverConfiguration; + @DiagnosticParameter( type = Integer.class, defaultValue = "" + MAX_METADATA_OBJECT_NAME_LENGTH @@ -62,7 +63,7 @@ public class MetadataObjectNameLengthDiagnostic extends AbstractMetadataDiagnost } @Override - protected void checkMetadata(AbstractMDObjectBase mdo) { + protected void checkMetadata(MD mdo) { if (mdo.getName().length() > maxMetadataObjectNameLength) { addAttributeDiagnostic(mdo); } @@ -76,13 +77,12 @@ protected void check() { if (computeDiagnosticRange()) { documentContext.getMdObject().ifPresent(this::checkMetadata); } - } else { super.check(); } } - private void addAttributeDiagnostic(AbstractMDObjectBase attribute) { + private void addAttributeDiagnostic(MD attribute) { String mdoRef; if (serverConfiguration.getLanguage() == Language.RU) { mdoRef = attribute.getMdoReference().getMdoRefRu(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MethodSizeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MethodSizeDiagnostic.java index 0037613cee7..913c3d3df23 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MethodSizeDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MethodSizeDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissedRequiredParameterDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissedRequiredParameterDiagnostic.java new file mode 100644 index 00000000000..38f7da974b8 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissedRequiredParameterDiagnostic.java @@ -0,0 +1,123 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.references.ReferenceIndex; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; +import lombok.RequiredArgsConstructor; +import org.antlr.v4.runtime.Token; +import org.antlr.v4.runtime.tree.ParseTree; +import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.SymbolKind; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +@DiagnosticMetadata( + type = DiagnosticType.ERROR, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 1, + tags = { + DiagnosticTag.ERROR + } + +) +@RequiredArgsConstructor +public class MissedRequiredParameterDiagnostic extends AbstractVisitorDiagnostic { + + private final ReferenceIndex referenceIndex; + private final Map calls = new HashMap<>(); + + @Override + public ParseTree visitFile(BSLParser.FileContext ctx) { + super.visitFile(ctx); + for (var reference : referenceIndex.getReferencesFrom(documentContext.getUri(), SymbolKind.Method)) { + var call = calls.get(reference.getSelectionRange()); + if (call != null) { + checkMethod((MethodSymbol) reference.getSymbol(), call); + } + } + return ctx; + } + + @Override + public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { + var methodName = ctx.methodName().IDENTIFIER().getText(); + if (documentContext.getSymbolTree().getMethodSymbol(methodName).isPresent()) { + appendMethodCall(ctx.methodName().getStart(), ctx.doCall(), ctx); + } + + return super.visitGlobalMethodCall(ctx); + } + + @Override + public ParseTree visitMethodCall(BSLParser.MethodCallContext ctx) { + appendMethodCall(ctx.methodName().getStart(), ctx.doCall(), ctx); + return super.visitMethodCall(ctx); + } + + private void appendMethodCall(Token methodName, BSLParser.DoCallContext doCallContext, BSLParserRuleContext node) { + var parameters = doCallContext.callParamList().callParam(); + var methodCall = new MethodCall(); + methodCall.parameters = new Boolean[parameters.size()]; + + for (var i = 0; i < methodCall.parameters.length; i++) { + methodCall.parameters[i] = parameters.get(i).expression() != null; + } + + methodCall.range = Ranges.create(node); + calls.put(Ranges.create(methodName), methodCall); + } + + private void checkMethod(MethodSymbol methodDefinition, MethodCall callInfo) { + var callParametersCount = callInfo.parameters.length; + + var missedParameters = new ArrayList(); + for (var i = 0; i < methodDefinition.getParameters().size(); i++) { + var methodParameter = methodDefinition.getParameters().get(i); + if (methodParameter.isOptional()) { + continue; + } + + if (callParametersCount <= i || !callInfo.parameters[i]) { + missedParameters.add(methodParameter.getName()); + } + } + if (!missedParameters.isEmpty()) { + var message = info.getMessage(String.format("'%s'", String.join("', '", missedParameters))); + diagnosticStorage.addDiagnostic(callInfo.range, message); + } + } + + private static class MethodCall { + Boolean[] parameters; + Range range; + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCodeTryCatchExDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCodeTryCatchExDiagnostic.java index 5b72487aa3b..af3d3d0d48b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCodeTryCatchExDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCodeTryCatchExDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCommonModuleMethodDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCommonModuleMethodDiagnostic.java new file mode 100644 index 00000000000..17c8ca7b277 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCommonModuleMethodDiagnostic.java @@ -0,0 +1,129 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.references.model.LocationRepository; +import com.github._1c_syntax.bsl.languageserver.references.model.OccurrenceType; +import com.github._1c_syntax.bsl.languageserver.references.model.SymbolOccurrence; +import com.github._1c_syntax.bsl.languageserver.utils.Trees; +import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; +import com.github._1c_syntax.bsl.types.ConfigurationSource; +import com.github._1c_syntax.bsl.types.ModuleType; +import lombok.AllArgsConstructor; +import lombok.RequiredArgsConstructor; +import lombok.Value; +import org.antlr.v4.runtime.tree.ParseTree; +import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.SymbolKind; + +import java.util.Optional; + +@DiagnosticMetadata( + type = DiagnosticType.ERROR, + severity = DiagnosticSeverity.BLOCKER, + scope = DiagnosticScope.BSL, + minutesToFix = 5, + tags = { + DiagnosticTag.ERROR + } +) + +@RequiredArgsConstructor +public class MissingCommonModuleMethodDiagnostic extends AbstractDiagnostic { + public static final String PRIVATE_METHOD_MESSAGE = "privateMethod"; + private final LocationRepository locationRepository; + + private static String getMethodNameByLocation(BSLParserRuleContext node, Range range) { + return Trees.findTerminalNodeContainsPosition(node, range.getStart()) + .map(ParseTree::getText) + .orElseThrow(); + } + + @Override + protected void check() { + if (documentContext.getServerContext().getConfiguration().getConfigurationSource() == ConfigurationSource.EMPTY){ + return; + } + locationRepository.getSymbolOccurrencesByLocationUri(documentContext.getUri()) + .filter(symbolOccurrence -> symbolOccurrence.getOccurrenceType() == OccurrenceType.REFERENCE) + .filter(symbolOccurrence -> symbolOccurrence.getSymbol().getSymbolKind() == SymbolKind.Method) + .filter(symbolOccurrence -> symbolOccurrence.getSymbol().getModuleType() == ModuleType.CommonModule) + .map(this::getReferenceToMethodCall) + .flatMap(Optional::stream) + .forEach(this::fireIssue); + } + + private Optional getReferenceToMethodCall(SymbolOccurrence symbolOccurrence) { + final var symbol = symbolOccurrence.getSymbol(); + final var document = documentContext.getServerContext() + .getDocument(symbol.getMdoRef(), symbol.getModuleType()); + if (document.isEmpty()) return Optional.empty(); + final var mdObject = document.get().getMdObject(); + if (mdObject.isEmpty()) return Optional.empty(); + + // т.к. через refIndex.getReferences нельзя получить приватные методы, приходится обходить символы модуля + final var methodSymbol = document.get() + .getSymbolTree().getMethodSymbol(symbol.getSymbolName()); + if (methodSymbol.isEmpty()){ + final var location = symbolOccurrence.getLocation(); + // Нельзя использовать symbol.getSymbolName(), т.к. имя в нижнем регистре + return Optional.of( + new CallData(mdObject.get().getName(), + getMethodNameByLocation(documentContext.getAst(), location.getRange()), + location.getRange(), false, false)); + } + // вызовы приватных методов внутри самого модуля пропускаем + if (document.get().getUri().equals(documentContext.getUri())){ + return Optional.empty(); + } + return methodSymbol + .filter(methodSymbol2 -> !methodSymbol2.isExport()) + .map(methodSymbol1 -> new CallData(mdObject.get().getName(), + methodSymbol1.getName(), + symbolOccurrence.getLocation().getRange(), true, true)); + } + + private void fireIssue(CallData callData) { + final String message; + if (!callData.exists){ + message = info.getMessage(callData.methodName, callData.moduleName); + } else { + message = info.getResourceString(PRIVATE_METHOD_MESSAGE, callData.methodName, callData.moduleName); + } + diagnosticStorage.addDiagnostic(callData.moduleMethodRange, message); + } + + @Value + @AllArgsConstructor + private static class CallData { + String moduleName; + String methodName; + Range moduleMethodRange; + boolean nonExport; + boolean exists; + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingEventSubscriptionHandlerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingEventSubscriptionHandlerDiagnostic.java index 94a97cbd999..24825a050c0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingEventSubscriptionHandlerDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingEventSubscriptionHandlerDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,15 +28,12 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.mdo.CommonModule; +import com.github._1c_syntax.bsl.mdo.EventSubscription; import com.github._1c_syntax.bsl.types.ConfigurationSource; -import com.github._1c_syntax.bsl.types.MDOType; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; -import com.github._1c_syntax.mdclasses.mdo.MDEventSubscription; import org.eclipse.lsp4j.Range; -import java.util.regex.Pattern; - @DiagnosticMetadata( type = DiagnosticType.ERROR, severity = DiagnosticSeverity.BLOCKER, @@ -57,7 +54,6 @@ public class MissingEventSubscriptionHandlerDiagnostic extends AbstractDiagnosti * Костыль, но пока так */ private Range diagnosticRange; - private static final Pattern SPLIT_PATTERN = Pattern.compile("\\."); @Override protected void check() { @@ -73,47 +69,45 @@ protected void check() { } // для анализа выбираются все имеющиеся подписки на события - configuration.getChildren().stream() - .filter(mdo -> mdo.getMdoType() == MDOType.EVENT_SUBSCRIPTION) - .map(MDEventSubscription.class::cast) - .forEach((MDEventSubscription eventSubs) -> { + configuration.getEventSubscriptions() + .forEach((EventSubscription eventSubs) -> { // проверка на пустой обработчик if (eventSubs.getHandler().isEmpty()) { addDiagnostic(eventSubs); return; } - var handlerParts = SPLIT_PATTERN.split(eventSubs.getHandler()); - // правильный обработчик состоит из трех частей: // - CommonModule - тип объекта, всегда постоянный: общий модуль // - Имя - имя модуля // - ИмяМетода - имя метода в модуле - if (handlerParts.length != 3) { - addDiagnostic("incorrectHandler", eventSubs, eventSubs.getHandler()); + // если имя метода пустое, то дальше и смотреть нет смысла + if (eventSubs.getHandler().getMethodName().isEmpty()) { + addDiagnostic("incorrectHandler", eventSubs, eventSubs.getHandler().getMethodPath()); return; } // проверка на существование модуля - var module = configuration.getCommonModule(handlerParts[1]); + var module = configuration.findCommonModule(eventSubs.getHandler().getModuleName()); + if (module.isEmpty()) { - addDiagnostic("missingModule", eventSubs, handlerParts[1]); + addDiagnostic("missingModule", eventSubs, eventSubs.getHandler().getModuleName()); return; } var commonModule = module.get(); // проверка наличия у модуля серверного флага if (!commonModule.isServer()) { - addDiagnostic("shouldBeServer", eventSubs, handlerParts[1]); + addDiagnostic("shouldBeServer", eventSubs, eventSubs.getHandler().getModuleName()); } // проверка на наличие метода и его экспортности - checkMethod(eventSubs, handlerParts[2], commonModule); + checkMethod(eventSubs, eventSubs.getHandler().getMethodName(), commonModule); }); } - private void checkMethod(MDEventSubscription eventSubs, String methodName, MDCommonModule commonModule) { + private void checkMethod(EventSubscription eventSubs, String methodName, CommonModule commonModule) { documentContext.getServerContext() .getDocument(commonModule.getMdoReference().getMdoRef(), ModuleType.CommonModule) .ifPresent((DocumentContext commonModuleContext) -> { @@ -130,12 +124,12 @@ private void checkMethod(MDEventSubscription eventSubs, String methodName, MDCom }); } - private void addDiagnostic(String messageString, MDEventSubscription eventSubs, String text) { + private void addDiagnostic(String messageString, EventSubscription eventSubs, String text) { diagnosticStorage.addDiagnostic(diagnosticRange, info.getResourceString(messageString, text, eventSubs.getName())); } - private void addDiagnostic(MDEventSubscription eventSubs) { + private void addDiagnostic(EventSubscription eventSubs) { diagnosticStorage.addDiagnostic(diagnosticRange, info.getMessage(eventSubs.getName())); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingParameterDescriptionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingParameterDescriptionDiagnostic.java index 82827f52313..fc2284b8321 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingParameterDescriptionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingParameterDescriptionDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingReturnedValueDescriptionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingReturnedValueDescriptionDiagnostic.java index 901f2b884dd..cd1bc4c1285 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingReturnedValueDescriptionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingReturnedValueDescriptionDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnostic.java index 41167345575..6cfce0ce660 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -85,19 +85,19 @@ public class MissingSpaceDiagnostic extends AbstractDiagnostic implements QuickF @DiagnosticParameter( type = String.class, - defaultValue = "" + DEFAULT_LIST_FOR_CHECK_LEFT + defaultValue = DEFAULT_LIST_FOR_CHECK_LEFT ) private String listForCheckLeft = DEFAULT_LIST_FOR_CHECK_LEFT; @DiagnosticParameter( type = String.class, - defaultValue = "" + DEFAULT_LIST_FOR_CHECK_RIGHT + defaultValue = DEFAULT_LIST_FOR_CHECK_RIGHT ) private String listForCheckRight = DEFAULT_LIST_FOR_CHECK_RIGHT; @DiagnosticParameter( type = String.class, - defaultValue = "" + DEFAULT_LIST_FOR_CHECK_LEFT_AND_RIGHT + defaultValue = DEFAULT_LIST_FOR_CHECK_LEFT_AND_RIGHT ) private String listForCheckLeftAndRight = DEFAULT_LIST_FOR_CHECK_LEFT_AND_RIGHT; @@ -169,9 +169,7 @@ public void check() { } addDiagnosticLeftRight(token, noSpaceLeft, noSpaceRight); } - } - } @Override @@ -196,21 +194,17 @@ public List getQuickFixes( String diagnosticMessage = diagnostic.getMessage().toLowerCase(Locale.ENGLISH); // TODO @YanSergey. Переделать после выполнения issue #371 'Доработки ядра. Хранение информации для квикфиксов' - boolean missedLeft = diagnosticMessage.contains("слева") || diagnosticMessage.contains("left"); - boolean missedRight = diagnosticMessage.contains("справа") || diagnosticMessage.contains("right"); + var missedLeft = diagnosticMessage.contains("слева") || diagnosticMessage.contains("left"); + var missedRight = diagnosticMessage.contains("справа") || diagnosticMessage.contains("right"); var range = diagnostic.getRange(); if (missedLeft) { - var textEdit = new TextEdit( - new Range(range.getStart(), range.getStart()), - " "); + var textEdit = new TextEdit(new Range(range.getStart(), range.getStart()), " "); textEdits.add(textEdit); } if (missedRight) { - var textEdit = new TextEdit( - new Range(range.getEnd(), range.getEnd()), - " "); + var textEdit = new TextEdit(new Range(range.getEnd(), range.getEnd()), " "); textEdits.add(textEdit); } }); @@ -243,7 +237,6 @@ private void addDiagnosticLeftRight(Token token, boolean noSpaceLeft, boolean no } private static boolean noSpaceLeft(List tokens, Token t) { - var previousToken = tokens.get(t.getTokenIndex() - 1); return previousToken.getType() != BSLParser.LPAREN && !StringUtils.isWhitespace(previousToken.getText()); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTempStorageDeletionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTempStorageDeletionDiagnostic.java index 634ccd8cbcd..6aa970b94d3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTempStorageDeletionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTempStorageDeletionDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -33,9 +33,9 @@ import com.github._1c_syntax.bsl.parser.BSLParser.StatementContext; import com.github._1c_syntax.bsl.parser.BSLParser.SubContext; import com.github._1c_syntax.utils.CaseInsensitivePattern; +import edu.umd.cs.findbugs.annotations.Nullable; import org.antlr.v4.runtime.tree.ParseTree; -import javax.annotation.Nullable; import java.util.Collection; import java.util.Collections; import java.util.Objects; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTemporaryFileDeletionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTemporaryFileDeletionDiagnostic.java index ee9453d9f51..9855bf300b3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTemporaryFileDeletionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTemporaryFileDeletionDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -120,15 +120,15 @@ private boolean foundDeleteFile(BSLParser.CodeBlockContext codeBlockContext, Str .stream() .map(BSLParserRuleContext.class::cast) .filter((BSLParserRuleContext node) -> node.getStart().getLine() > filterLine) - .collect(Collectors.toList()); + .toList(); for (var node : listCallStatements) { String fullCallMethod; BSLParser.DoCallContext doCallContext; - if (node instanceof BSLParser.GlobalMethodCallContext) { - fullCallMethod = ((BSLParser.GlobalMethodCallContext) node).methodName().getText(); - doCallContext = ((BSLParser.GlobalMethodCallContext) node).doCall(); + if (node instanceof BSLParser.GlobalMethodCallContext globalMethodCallContext) { + fullCallMethod = globalMethodCallContext.methodName().getText(); + doCallContext = globalMethodCallContext.doCall(); } else { fullCallMethod = getFullMethodName((BSLParser.AccessCallContext) node); doCallContext = ((BSLParser.AccessCallContext) node).methodCall().doCall(); @@ -136,7 +136,7 @@ private boolean foundDeleteFile(BSLParser.CodeBlockContext codeBlockContext, Str if (doCallContext != null) { var matcher = searchDeleteFileMethod.matcher(fullCallMethod); - if (matcher.matches() && fullCallMethod.length() > 0 + if (matcher.matches() && !fullCallMethod.isEmpty() && foundVariableInCallParams(doCallContext, variableName)) { result = true; break; @@ -191,11 +191,9 @@ private static String getFullMethodName(BSLParser.AccessCallContext ctx) { var prefix = ""; List modifiers; - if (parent instanceof BSLParser.CallStatementContext) { + if (parent instanceof BSLParser.CallStatementContext callStatement) { - var callStatement = (BSLParser.CallStatementContext) parent; - - modifiers =callStatement.modifier(); + modifiers = callStatement.modifier(); if (callStatement.globalMethodCall() != null) { prefix = callStatement.globalMethodCall().methodName().IDENTIFIER().getText(); } else { @@ -203,9 +201,8 @@ private static String getFullMethodName(BSLParser.AccessCallContext ctx) { } } else if (parent instanceof BSLParser.ModifierContext - && parent.getParent() instanceof BSLParser.ComplexIdentifierContext) { + && parent.getParent() instanceof BSLParser.ComplexIdentifierContext root) { - var root = (BSLParser.ComplexIdentifierContext) parent.getParent(); modifiers = root.modifier(); var terminalNode = root.IDENTIFIER(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnostic.java index fc152acc2d4..9c385351361 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilineStringInQueryDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilineStringInQueryDiagnostic.java index dbcd7a31b6c..912037596f5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilineStringInQueryDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilineStringInQueryDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilingualStringHasAllDeclaredLanguagesDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilingualStringHasAllDeclaredLanguagesDiagnostic.java index e3bfed372b3..068180828d8 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilingualStringHasAllDeclaredLanguagesDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilingualStringHasAllDeclaredLanguagesDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilingualStringUsingWithTemplateDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilingualStringUsingWithTemplateDiagnostic.java index e6191ecd94d..2a1fa65d8a9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilingualStringUsingWithTemplateDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilingualStringUsingWithTemplateDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedConstructorsInStructureDeclarationDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedConstructorsInStructureDeclarationDiagnostic.java index 3424f14be25..b7d1a2681fa 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedConstructorsInStructureDeclarationDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedConstructorsInStructureDeclarationDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -32,10 +32,10 @@ import com.github._1c_syntax.bsl.languageserver.utils.Trees; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParser.NewExpressionContext; +import jakarta.annotation.PostConstruct; import org.antlr.v4.runtime.tree.ParseTree; import org.eclipse.lsp4j.DiagnosticRelatedInformation; -import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedFunctionInParametersDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedFunctionInParametersDiagnostic.java index 67ed454b546..87b0103697f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedFunctionInParametersDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedFunctionInParametersDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,10 +29,10 @@ import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import com.github._1c_syntax.utils.CaseInsensitivePattern; +import edu.umd.cs.findbugs.annotations.Nullable; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; -import javax.annotation.Nullable; import java.util.Map; import java.util.regex.Pattern; import java.util.stream.IntStream; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedStatementsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedStatementsDiagnostic.java index c9117f4081a..9e38828f753 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedStatementsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedStatementsDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -31,10 +31,10 @@ import com.github._1c_syntax.bsl.languageserver.utils.RelatedInformation; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; +import jakarta.annotation.PostConstruct; import org.antlr.v4.runtime.tree.ParseTree; import org.eclipse.lsp4j.DiagnosticRelatedInformation; -import javax.annotation.PostConstruct; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedTernaryOperatorDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedTernaryOperatorDiagnostic.java index 6a55db9035e..0c1579ffba9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedTernaryOperatorDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedTernaryOperatorDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonExportMethodsInApiRegionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonExportMethodsInApiRegionDiagnostic.java index f2d1c537ee5..0ea3207bdcc 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonExportMethodsInApiRegionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonExportMethodsInApiRegionDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnostic.java index 23b52e0e3de..2645d059875 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfOptionalParamsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfOptionalParamsDiagnostic.java index 6d72d7a39e8..1995a1bf989 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfOptionalParamsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfOptionalParamsDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfParamsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfParamsDiagnostic.java index 059921873a8..704437f699a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfParamsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfParamsDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfValuesInStructureConstructorDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfValuesInStructureConstructorDiagnostic.java index f5a30c1fffb..a9cb8d85d57 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfValuesInStructureConstructorDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfValuesInStructureConstructorDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OSUsersMethodDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OSUsersMethodDiagnostic.java index 903a485ee96..8e70230d908 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OSUsersMethodDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OSUsersMethodDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OneStatementPerLineDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OneStatementPerLineDiagnostic.java index c22214e6234..a77420f40ae 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OneStatementPerLineDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OneStatementPerLineDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OrderOfParamsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OrderOfParamsDiagnostic.java index 035a742cade..f4779a0223c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OrderOfParamsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OrderOfParamsDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OrdinaryAppSupportDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OrdinaryAppSupportDiagnostic.java index 973bbfec9ce..eb097d702f0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OrdinaryAppSupportDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OrdinaryAppSupportDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,6 +28,7 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.mdclasses.Configuration; import com.github._1c_syntax.bsl.types.ModuleType; import lombok.RequiredArgsConstructor; import org.eclipse.lsp4j.Range; @@ -64,16 +65,15 @@ protected void check() { } private void checkProperties(Range range) { - var configuration = documentContext.getServerContext().getConfiguration(); - if (!configuration.isUseManagedFormInOrdinaryApplication()) { - diagnosticStorage.addDiagnostic(range, info.getResourceString("managedFormInOrdinaryApp")); - } + if (configuration instanceof Configuration cf) { // у расширения нет таких атрибутов + if (!cf.isUseManagedFormInOrdinaryApplication()) { + diagnosticStorage.addDiagnostic(range, info.getResourceString("managedFormInOrdinaryApp")); + } - if (configuration.isUseOrdinaryFormInManagedApplication()) { - diagnosticStorage.addDiagnostic(range, info.getResourceString("ordinaryFormInManagedApp")); + if (cf.isUseOrdinaryFormInManagedApplication()) { + diagnosticStorage.addDiagnostic(range, info.getResourceString("ordinaryFormInManagedApp")); + } } - } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PairingBrokenTransactionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PairingBrokenTransactionDiagnostic.java index 6e9bb0def5a..60f755d2f8b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PairingBrokenTransactionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PairingBrokenTransactionDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnostic.java index 719b95817ac..4ddc1abacff 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PrivilegedModuleMethodCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PrivilegedModuleMethodCallDiagnostic.java new file mode 100644 index 00000000000..3dd51db76c4 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PrivilegedModuleMethodCallDiagnostic.java @@ -0,0 +1,109 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.symbol.ModuleSymbol; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticParameter; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.references.ReferenceIndex; +import com.github._1c_syntax.bsl.languageserver.references.model.Reference; +import com.github._1c_syntax.bsl.mdo.CommonModule; +import com.github._1c_syntax.bsl.types.ModuleType; +import lombok.RequiredArgsConstructor; +import org.eclipse.lsp4j.SymbolKind; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +@DiagnosticMetadata( + type = DiagnosticType.SECURITY_HOTSPOT, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 60, + tags = { + DiagnosticTag.SUSPICIOUS + }, + scope = DiagnosticScope.BSL +) +@RequiredArgsConstructor +public class PrivilegedModuleMethodCallDiagnostic extends AbstractDiagnostic { + + private static final boolean VALIDATE_NESTED_CALLS = true; + + @DiagnosticParameter( + type = Boolean.class, + defaultValue = "" + VALIDATE_NESTED_CALLS + ) + private boolean validateNestedCalls = VALIDATE_NESTED_CALLS; + + private final ReferenceIndex referenceIndex; + private List privilegedModuleSymbols = new ArrayList<>(); + + @Override + protected void check() { + if (privilegedModuleSymbols.isEmpty()) { + privilegedModuleSymbols = getPrivilegedModuleSymbols(); + } + if (privilegedModuleSymbols.isEmpty()) { + return; + } + + referenceIndex.getReferencesFrom(documentContext.getUri(), SymbolKind.Method).stream() + .filter(this::isReferenceToModules) + .forEach(this::fireIssue); + } + + private List getPrivilegedModuleSymbols() { + return documentContext.getServerContext().getConfiguration().getCommonModules() + .stream() + .filter(CommonModule::isPrivileged) + .flatMap(mdCommonModule -> getPrivilegedModuleSymbol(mdCommonModule).stream()) + .toList(); + } + + private Optional getPrivilegedModuleSymbol(CommonModule mdCommonModule) { + return documentContext.getServerContext().getDocument( + mdCommonModule.getMdoReference().getMdoRef(), ModuleType.CommonModule) + .map(documentContext1 -> documentContext1.getSymbolTree().getModule()); + } + + private boolean isReferenceToModules(Reference reference) { + if (!validateNestedCalls && reference.getUri().equals(documentContext.getUri())) { + return false; + } + return reference.getSourceDefinedSymbol() + .flatMap(sourceDefinedSymbol -> sourceDefinedSymbol.getRootParent(SymbolKind.Module)) + .filter(ModuleSymbol.class::isInstance) + .map(ModuleSymbol.class::cast) + .filter(privilegedModuleSymbols::contains) + .isPresent(); + } + + private void fireIssue(Reference reference) { + diagnosticStorage.addDiagnostic(reference.getSelectionRange(), + info.getMessage(reference.getSymbol().getName())); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProcedureReturnsValueDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProcedureReturnsValueDiagnostic.java index 119976d7abd..89dcaeb7506 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProcedureReturnsValueDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProcedureReturnsValueDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProtectedModuleDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProtectedModuleDiagnostic.java new file mode 100644 index 00000000000..19c5d0e5547 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProtectedModuleDiagnostic.java @@ -0,0 +1,91 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.MdoRefBuilder; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.mdo.Module; +import com.github._1c_syntax.bsl.mdo.ModuleOwner; +import com.github._1c_syntax.bsl.types.ConfigurationSource; +import com.github._1c_syntax.bsl.types.ModuleType; +import org.eclipse.lsp4j.Range; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 5, + tags = { + DiagnosticTag.BADPRACTICE, + DiagnosticTag.SUSPICIOUS + }, + modules = { + ModuleType.SessionModule + }, + scope = DiagnosticScope.BSL, + canLocateOnProject = true +) + +public class ProtectedModuleDiagnostic extends AbstractDiagnostic { + + /** + * Рендж на который будут повешены замечания + * Костыль, но пока так + */ + private Range diagnosticRange; + + @Override + protected void check() { + + var configuration = documentContext.getServerContext().getConfiguration(); + if (configuration.getConfigurationSource() == ConfigurationSource.EMPTY) { + return; + } + + diagnosticRange = documentContext.getSymbolTree().getModule().getSelectionRange(); + if (Ranges.isEmpty(diagnosticRange)) { + return; + } + + configuration.getChildren().stream() + .filter(md -> md instanceof ModuleOwner) + .map(md -> (ModuleOwner) md) + .forEach((ModuleOwner moduleOwner) -> { + var hasProtected = moduleOwner.getModules().stream() + .filter(Module::isProtected) + .findAny(); + if (hasProtected.isPresent()) { + addDiagnostic(moduleOwner); + } + }); + } + + private void addDiagnostic(ModuleOwner moduleOwner) { + var ownerMDOName = MdoRefBuilder.getLocaleOwnerMdoName(documentContext, moduleOwner); + diagnosticStorage.addDiagnostic(diagnosticRange, info.getMessage(ownerMDOName)); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PublicMethodsDescriptionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PublicMethodsDescriptionDiagnostic.java index b6af806109a..05efff84629 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PublicMethodsDescriptionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PublicMethodsDescriptionDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryParseErrorDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryParseErrorDiagnostic.java index fe4890f1b82..7fd85d6242c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryParseErrorDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryParseErrorDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryToMissingMetadataDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryToMissingMetadataDiagnostic.java index 7f012ab0741..87772d95dcc 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryToMissingMetadataDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryToMissingMetadataDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -26,13 +26,12 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdo.MD; import com.github._1c_syntax.bsl.parser.SDBLParser; import com.github._1c_syntax.bsl.types.ConfigurationSource; import com.github._1c_syntax.bsl.types.MDOType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; import org.antlr.v4.runtime.tree.ParseTree; -import java.util.Map; import java.util.Optional; @DiagnosticMetadata( @@ -50,17 +49,14 @@ public class QueryToMissingMetadataDiagnostic extends AbstractSDBLVisitorDiagnos @Override public ParseTree visitQueryPackage(SDBLParser.QueryPackageContext ctx) { - if (documentContext.getServerContext().getConfiguration().getConfigurationSource() == ConfigurationSource.EMPTY) { return ctx; } - return super.visitQueryPackage(ctx); } @Override public ParseTree visitMdo(SDBLParser.MdoContext mdo) { - if (nonMdoExists(mdo.type.getText(), mdo.tableName.getText())) { diagnosticStorage.addDiagnostic(mdo, info.getMessage(mdo.getText())); @@ -72,13 +68,9 @@ private boolean nonMdoExists(String mdoType, String mdoName) { return getMdo(mdoType, mdoName).isEmpty(); } - private Optional getMdo(String mdoTypeName, String mdoName) { + private Optional getMdo(String mdoTypeName, String mdoName) { return MDOType.fromValue(mdoTypeName).flatMap(mdoType -> - documentContext.getServerContext().getConfiguration().getChildrenByMdoRef().entrySet().stream() - .filter(entry -> entry.getKey().getType() == mdoType - && mdoName.equalsIgnoreCase(entry.getValue().getName())) - .map(Map.Entry::getValue) - .findFirst() - ); + documentContext.getServerContext().getConfiguration().findChild(mdo -> mdo.getMdoType() == mdoType + && mdoName.equalsIgnoreCase(mdo.getName()))); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QuickFixProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QuickFixProvider.java index 3319a3ec68e..3e988a1ad26 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QuickFixProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QuickFixProvider.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RedundantAccessToObjectDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RedundantAccessToObjectDiagnostic.java index 7dc5bead313..e48a7094f0d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RedundantAccessToObjectDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RedundantAccessToObjectDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,12 +28,12 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdo.CommonModule; +import com.github._1c_syntax.bsl.mdo.MD; import com.github._1c_syntax.bsl.mdo.support.ReturnValueReuse; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.types.MDOType; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; import com.github._1c_syntax.utils.CaseInsensitivePattern; import org.antlr.v4.runtime.tree.ParseTree; import org.eclipse.lsp4j.Diagnostic; @@ -68,8 +68,8 @@ public class RedundantAccessToObjectDiagnostic extends AbstractVisitorDiagnostic private static final boolean CHECK_FORM_MODULE = true; private static final boolean CHECK_RECORD_SET_MODULE = true; - private boolean needCheckName = false; - private boolean skipLValue = false; + private boolean needCheckName; + private boolean skipLValue; private Pattern namePatternWithDot; @DiagnosticParameter( @@ -94,14 +94,13 @@ public class RedundantAccessToObjectDiagnostic extends AbstractVisitorDiagnostic public List getDiagnostics(DocumentContext documentContext) { var typeModule = documentContext.getModuleType(); if (typeModule == ModuleType.CommonModule || typeModule == ModuleType.ManagerModule) { - documentContext.getMdObject().ifPresent((AbstractMDObjectBase mdObjectBase) -> { - - needCheckName = !(mdObjectBase instanceof MDCommonModule) - || ((MDCommonModule) mdObjectBase).getReturnValuesReuse() == ReturnValueReuse.DONT_USE; + documentContext.getMdObject().ifPresent((MD mdo) -> { + needCheckName = !(mdo instanceof CommonModule commonModule) + || commonModule.getReturnValuesReuse() == ReturnValueReuse.DONT_USE; skipLValue = true; namePatternWithDot = CaseInsensitivePattern.compile( - String.format(getManagerModuleName(mdObjectBase.getMdoType()), mdObjectBase.getName()) + String.format(getManagerModuleName(mdo.getMdoType()), mdo.getName()) ); }); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RefOveruseDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RefOveruseDiagnostic.java index 21422768b32..62ad3ee7cb8 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RefOveruseDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RefOveruseDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -26,18 +26,29 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import com.github._1c_syntax.bsl.languageserver.utils.Trees; +import com.github._1c_syntax.bsl.mdo.TabularSection; +import com.github._1c_syntax.bsl.mdo.TabularSectionOwner; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import com.github._1c_syntax.bsl.parser.SDBLParser; +import com.github._1c_syntax.bsl.types.ConfigurationSource; +import com.github._1c_syntax.bsl.types.MDOType; +import com.github._1c_syntax.bsl.types.MdoReference; import com.github._1c_syntax.utils.CaseInsensitivePattern; +import edu.umd.cs.findbugs.annotations.Nullable; import org.antlr.v4.runtime.tree.ParseTree; +import org.eclipse.lsp4j.Range; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -55,91 +66,207 @@ public class RefOveruseDiagnostic extends AbstractSDBLVisitorDiagnostic { private static final Pattern REF_PATTERN = CaseInsensitivePattern.compile("Ссылка|Reference"); - private static final int BAD_CHILD_COUNT = 3; + private static final int COUNT_OF_TABLE_DOT_REF = 3; + private static final int LAST_INDEX_OF_TABLE_DOT_REF = COUNT_OF_TABLE_DOT_REF - 1; private static final int COUNT_OF_TABLE_DOT_REF_DOT_REF = 5; - private Map dataSourcesWithTabularFlag = Collections.emptyMap(); + private static final Set RULE_COLUMNS = Set.of(SDBLParser.RULE_column, SDBLParser.RULE_query); + private static final Set METADATA_TYPES = Set.of( + SDBLParser.BUSINESS_PROCESS_TYPE, + SDBLParser.CATALOG_TYPE, + SDBLParser.DOCUMENT_TYPE, + SDBLParser.INFORMATION_REGISTER_TYPE, + SDBLParser.CONSTANT_TYPE, + SDBLParser.FILTER_CRITERION_TYPE, + SDBLParser.EXCHANGE_PLAN_TYPE, + SDBLParser.SEQUENCE_TYPE, + SDBLParser.DOCUMENT_JOURNAL_TYPE, + SDBLParser.ENUM_TYPE, + SDBLParser.CHART_OF_CHARACTERISTIC_TYPES_TYPE, + SDBLParser.CHART_OF_ACCOUNTS_TYPE, + SDBLParser.CHART_OF_CALCULATION_TYPES_TYPE, + SDBLParser.ACCUMULATION_REGISTER_TYPE, + SDBLParser.ACCOUNTING_REGISTER_TYPE, + SDBLParser.CALCULATION_REGISTER_TYPE, + SDBLParser.TASK_TYPE, + SDBLParser.EXTERNAL_DATA_SOURCE_TYPE); + private static final Collection EXCLUDED_COLUMNS_ROOT = + Set.of(SDBLParser.RULE_inlineTableField, SDBLParser.RULE_query); + public static final List SPECIAL_LIST_FOR_DATA_SOURCE = List.of(""); + + private Map> dataSourceWithTabularSectionNames = Collections.emptyMap(); + private Map> prevDataSourceWithTabularSectionNames = Collections.emptyMap(); + @Nullable + private Range prevQueryRange; + + @Override + public ParseTree visitQueryPackage(SDBLParser.QueryPackageContext ctx) { + var result = super.visitQueryPackage(ctx); + prevQueryRange = null; + prevDataSourceWithTabularSectionNames = Collections.emptyMap(); + dataSourceWithTabularSectionNames = Collections.emptyMap(); + return result; + } @Override public ParseTree visitQuery(SDBLParser.QueryContext ctx) { checkQuery(ctx).forEach(diagnosticStorage::addDiagnostic); - return ctx; + return super.visitQuery(ctx); } - private Stream checkQuery(SDBLParser.QueryContext ctx) { - var columnsCollection = Trees.findAllRuleNodes(ctx, SDBLParser.RULE_column); + private Stream checkQuery(SDBLParser.QueryContext ctx) { + var columns = Trees.findAllTopLevelDescendantNodes(ctx, RULE_COLUMNS).stream() + .filter(parserRuleContext -> parserRuleContext.getRuleIndex() == SDBLParser.RULE_column) + .filter(parserRuleContext -> Trees.getRootParent((BSLParserRuleContext) parserRuleContext, EXCLUDED_COLUMNS_ROOT) + .getRuleIndex() == SDBLParser.RULE_query) + .map(SDBLParser.ColumnContext.class::cast) + .collect(Collectors.toList()); - if (columnsCollection.isEmpty()) { + if (columns.isEmpty()) { return Stream.empty(); } - dataSourcesWithTabularFlag = dataSourcesWithTabularSection(ctx); - if (dataSourcesWithTabularFlag.isEmpty()) { - return getSimpleOverused(columnsCollection); + dataSourceWithTabularSectionNames = dataSourcesWithTabularSection(ctx); + if (dataSourceWithTabularSectionNames.isEmpty()) { + return getSimpleOverused(columns); } - return getOverused(columnsCollection); + return getOverused(columns); + } + + private Map> dataSourcesWithTabularSection(SDBLParser.QueryContext ctx) { + var newResult = calcDataSourceWithTabularSectionNames(findAllDataSourceWithoutInnerQueries(ctx)); + + var queryRange = Ranges.create(ctx); + + final Map> result; + if (prevQueryRange == null || !Ranges.containsRange(prevQueryRange, queryRange)) { + result = newResult; + prevDataSourceWithTabularSectionNames = result; + prevQueryRange = queryRange; + } else { + result = new HashMap<>(newResult); + result.putAll(prevDataSourceWithTabularSectionNames); + } + return result; } - private static Map dataSourcesWithTabularSection(SDBLParser.QueryContext ctx) { - return findAllDataSourceWithoutInnerQueries(ctx) + private Map> calcDataSourceWithTabularSectionNames( + Stream dataSources + ) { + + return dataSources + .map(dataSourceContext -> new TabularSectionTable(getTableNameOrAlias(dataSourceContext), + getTabularSectionNames(dataSourceContext))) .collect(Collectors.toMap( - RefOveruseDiagnostic::getTableNameOrAlias, - RefOveruseDiagnostic::isTableWithTabularSection, - (existing, replacement) -> existing, - HashMap::new)); + TabularSectionTable::tableNameOrAlias, + TabularSectionTable::tabularSectionNames, + (existing, replacement) -> existing)); } private static Stream findAllDataSourceWithoutInnerQueries( SDBLParser.QueryContext ctx) { - if (ctx.from == null){ + if (ctx.from == null) { return Stream.empty(); } return Stream.concat( ctx.from.dataSource().stream(), ctx.from.dataSource().stream() - .flatMap(dataSourceContext -> dataSourceContext.joinPart().stream()) - .map(SDBLParser.JoinPartContext::dataSource) - .filter(Objects::nonNull) + .flatMap(dataSourceContext -> getInnerDataSource(dataSourceContext).stream()) ); } + private static Collection getInnerDataSource( + SDBLParser.DataSourceContext dataSourceContext + ) { + var result = new ArrayList(); + Optional.ofNullable(dataSourceContext.dataSource()) + .map(RefOveruseDiagnostic::getInnerDataSource) + .ifPresent(result::addAll); + + var joinDataSources = dataSourceContext.joinPart().stream() + .map(SDBLParser.JoinPartContext::dataSource) + .filter(Objects::nonNull) + .toList(); + result.addAll(joinDataSources); + + var dataSourcesFromJoins = joinDataSources.stream() + .flatMap(dataSourceContext1 -> getInnerDataSource(dataSourceContext1).stream()) + .toList(); + + result.addAll(dataSourcesFromJoins); + return result; + } + private static String getTableNameOrAlias(SDBLParser.DataSourceContext dataSource) { final var value = Optional.of(dataSource); return value .map(SDBLParser.DataSourceContext::alias) - .map(alias -> (ParseTree)alias.name) + .map(alias -> (ParseTree) alias.name) .or(() -> value .map(SDBLParser.DataSourceContext::table) - .map(tableContext -> (ParseTree)tableContext.tableName)) + .map(tableContext -> (ParseTree) tableContext.tableName)) .or(() -> value .map(SDBLParser.DataSourceContext::parameterTable) - .map(tableContext -> (ParseTree)tableContext.parameter())) + .map(tableContext -> (ParseTree) tableContext.parameter())) .map(ParseTree::getText) .orElse(""); } - private static boolean isTableWithTabularSection(SDBLParser.DataSourceContext dataSourceContext) { + private List getTabularSectionNames(SDBLParser.DataSourceContext dataSourceContext) { final var table = dataSourceContext.table(); if (table == null) { - return dataSourceContext.virtualTable() != null; + return getSpecialListForDataSource(dataSourceContext.virtualTable() != null); + } + final var mdo = dataSourceContext.table().mdo(); + if (mdo == null) { + return getSpecialListForDataSource(table.tableName != null); + } + if (table.objectTableName != null) { + return SPECIAL_LIST_FOR_DATA_SOURCE; } - return table.tableName != null || table.objectTableName != null; + return getTabularSectionNames(mdo); } - private static Stream getSimpleOverused(Collection columnsCollection) { + private static List getSpecialListForDataSource(boolean useSpecialName) { + if (useSpecialName) { + return SPECIAL_LIST_FOR_DATA_SOURCE; + } + return Collections.emptyList(); + } + + private List getTabularSectionNames(SDBLParser.MdoContext mdo) { + final var configuration = documentContext.getServerContext() + .getConfiguration(); + if (configuration.getConfigurationSource() == ConfigurationSource.EMPTY) { + return Collections.emptyList(); + } + return MDOType.fromValue(mdo.type.getText()).stream() + .map(mdoTypeTabular -> MdoReference.create(mdoTypeTabular, mdo.tableName.getText())) + .map(configuration::findChild) + .filter(Optional::isPresent) + .map(Optional::get) + .filter(TabularSectionOwner.class::isInstance) + .map(TabularSectionOwner.class::cast) + .flatMap(RefOveruseDiagnostic::getTabularSectionNames) + .collect(Collectors.toList()); + } + + private static Stream getTabularSectionNames(TabularSectionOwner tabularSectionOwner) { + return tabularSectionOwner.getTabularSections().stream() + .map(TabularSection::getName); + } + + private static Stream getSimpleOverused(List columnsCollection) { return columnsCollection.stream() - .filter(columnNode -> columnNode.getChildCount() > BAD_CHILD_COUNT) - .map(column -> column.getChild(column.getChildCount() - 1)) - .filter(lastChild -> REF_PATTERN.matcher(lastChild.getText()).matches()) - .map(BSLParserRuleContext.class::cast); + .filter(columnNode -> columnNode.getChildCount() > COUNT_OF_TABLE_DOT_REF) + .filter(column -> REF_PATTERN.matcher(column.getChild(column.getChildCount() - 1).getText()).matches()); } - private Stream getOverused(Collection columnsCollection) { + private Stream getOverused(List columnsCollection) { return columnsCollection.stream() .map(SDBLParser.ColumnContext.class::cast) - .filter(column -> column.getChildCount() >= BAD_CHILD_COUNT) - .filter(this::isOveruse) - .map(BSLParserRuleContext.class::cast); + .filter(column -> column.getChildCount() >= COUNT_OF_TABLE_DOT_REF) + .filter(this::isOveruse); } private boolean isOveruse(SDBLParser.ColumnContext ctx) { @@ -154,26 +281,45 @@ private boolean isOveruse(SDBLParser.ColumnContext ctx) { // ^ ^ ^ // 0 1 2 - final int childCount = ctx.children.size(); - - // dots are also children of ColumnContext, - // that is why -3 must be an index of penultimate identifier - var penultimateChild = ctx.getChild(childCount - BAD_CHILD_COUNT); + var children = extractFirstMetadataTypeName(ctx); + var refIndex = findLastRef(children); - String penultimateIdentifierName = penultimateChild.getText(); + final var lastIndex = children.size() - 1; + if (refIndex == lastIndex) { + var penultimateIdentifierName = children.get(lastIndex - LAST_INDEX_OF_TABLE_DOT_REF).getText(); + return dataSourceWithTabularSectionNames.get(penultimateIdentifierName) == null; + } + if (refIndex < LAST_INDEX_OF_TABLE_DOT_REF) { + return false; + } + if (refIndex > LAST_INDEX_OF_TABLE_DOT_REF) { + return true; + } + var tabName = children.get(0).getText(); + return dataSourceWithTabularSectionNames.getOrDefault(tabName, Collections.emptyList()).isEmpty(); + } - if (REF_PATTERN.matcher(penultimateIdentifierName).matches()) { - if (childCount < COUNT_OF_TABLE_DOT_REF_DOT_REF){ - return true; + private static int findLastRef(List children) { + for (int i = children.size() - 1; i >= 0; i--) { + final var child = children.get(i); + final var childText = child.getText(); + if (REF_PATTERN.matcher(childText).matches()) { + return i; } - var prevChildID = ctx.getChild(childCount - COUNT_OF_TABLE_DOT_REF_DOT_REF).getText(); - return !dataSourcesWithTabularFlag.getOrDefault(prevChildID, false); } - var lastChild = ctx.getChild(childCount - 1); - String lastIdentifierName = lastChild.getText(); - if (REF_PATTERN.matcher(lastIdentifierName).matches()) { - return dataSourcesWithTabularFlag.get(penultimateIdentifierName) == null; + return -1; + } + + private static List extractFirstMetadataTypeName(SDBLParser.ColumnContext ctx) { + final var mdoName = ctx.mdoName; + final var children = ctx.children; + if (mdoName == null || children.size() < COUNT_OF_TABLE_DOT_REF_DOT_REF + || !METADATA_TYPES.contains(mdoName.getStart().getType())) { + return children; } - return false; + return children.subList(1, children.size() - 1); + } + + private record TabularSectionTable(String tableNameOrAlias, List tabularSectionNames) { } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ReservedParameterNamesDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ReservedParameterNamesDiagnostic.java new file mode 100644 index 00000000000..ae8ffad8f9f --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ReservedParameterNamesDiagnostic.java @@ -0,0 +1,89 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.ParameterDefinition; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticParameter; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; + +import com.github._1c_syntax.utils.CaseInsensitivePattern; + +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 5, + tags = { + DiagnosticTag.STANDARD, + DiagnosticTag.BADPRACTICE + } +) +public class ReservedParameterNamesDiagnostic extends AbstractSymbolTreeDiagnostic { + + private static final String RESERVED_WORDS_DEFAULT = ""; + + @DiagnosticParameter(type = String.class) + private Pattern reservedWords = CaseInsensitivePattern.compile(RESERVED_WORDS_DEFAULT); + + @Override + public void configure(Map configuration) { + + var incomingMask = (String) configuration.getOrDefault("reservedWords", RESERVED_WORDS_DEFAULT); + + this.reservedWords = CaseInsensitivePattern.compile("^" + incomingMask.trim() + "$"); + } + + @Override + protected void check() { + + if (reservedWords.pattern().isBlank()) { + return; + } + super.check(); + } + + @Override + public void visitMethod(MethodSymbol methodSymbol) { + + List parameters = methodSymbol.getParameters(); + checkParameterName(parameters); + } + + private void checkParameterName(List parameters) { + + parameters.forEach((ParameterDefinition parameter) -> { + + var matcher = reservedWords.matcher(parameter.getName()); + if (matcher.find()) { + diagnosticStorage.addDiagnostic(parameter.getRange(), info.getMessage(parameter.getName())); + } + }); + } + +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RewriteMethodParameterDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RewriteMethodParameterDiagnostic.java index 11cec29d2d6..155ab67769f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RewriteMethodParameterDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RewriteMethodParameterDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -35,6 +35,7 @@ import com.github._1c_syntax.bsl.languageserver.utils.Trees; import com.github._1c_syntax.bsl.parser.BSLParser; import lombok.RequiredArgsConstructor; +import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.RuleNode; import org.antlr.v4.runtime.tree.TerminalNode; import org.apache.commons.lang3.tuple.Pair; @@ -84,7 +85,8 @@ private static Stream> getParametersByVa .map(parameterDefinition -> Pair.of(methodSymbol, parameterDefinition)); } - private static Stream getVariableByParameter(MethodSymbol method, ParameterDefinition parameterDefinition) { + private static Stream getVariableByParameter(MethodSymbol method, + ParameterDefinition parameterDefinition) { return method.getChildren().stream() // в будущем могут появиться и другие символы, подчиненные методам .filter(sourceDefinedSymbol -> sourceDefinedSymbol.getSymbolKind() == SymbolKind.Variable) @@ -153,13 +155,14 @@ private Optional getRefContextInsideDefAssign(Reference defRef, Refere final var assignment = defNode .map(TerminalNode::getParent) .filter(BSLParser.LValueContext.class::isInstance) - .map(RuleNode::getParent) + .map(ParseTree::getParent) .filter(BSLParser.AssignmentContext.class::isInstance) .map(BSLParser.AssignmentContext.class::cast); return assignment.flatMap(assignContext -> Trees.findTerminalNodeContainsPosition(assignContext, nextRef.getSelectionRange().getStart())) - .map(TerminalNode::getParent); + .map(TerminalNode::getParent) + .map(RuleNode.class::cast); } private static boolean isVarNameOnlyIntoExpression(RuleNode refContext) { @@ -169,7 +172,7 @@ private static boolean isVarNameOnlyIntoExpression(RuleNode refContext) { .filter(node -> node.getChildCount() == 1) .map(RuleNode::getParent) .filter(BSLParser.MemberContext.class::isInstance) - .map(RuleNode::getParent) + .map(ParseTree::getParent) .filter(expression -> expression.getChildCount() == 1) .filter(BSLParser.ExpressionContext.class::isInstance) .isPresent(); @@ -181,7 +184,7 @@ private void fireIssue(VariableSymbol variable, Reference nodeForIssue, List(); resultRefs.add(RelatedInformation.create( documentContext.getUri(), diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SameMetadataObjectAndChildNamesDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SameMetadataObjectAndChildNamesDiagnostic.java index 1597324660e..37b8913ab4d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SameMetadataObjectAndChildNamesDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SameMetadataObjectAndChildNamesDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,12 +28,14 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdo.Attribute; +import com.github._1c_syntax.bsl.mdo.AttributeOwner; +import com.github._1c_syntax.bsl.mdo.ChildrenOwner; +import com.github._1c_syntax.bsl.mdo.MD; +import com.github._1c_syntax.bsl.mdo.TabularSection; +import com.github._1c_syntax.bsl.mdo.TabularSectionOwner; import com.github._1c_syntax.bsl.types.MDOType; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectComplex; -import com.github._1c_syntax.mdclasses.mdo.attributes.AbstractMDOAttribute; -import com.github._1c_syntax.mdclasses.mdo.attributes.TabularSection; import com.github._1c_syntax.utils.StringInterner; import java.util.List; @@ -52,8 +54,8 @@ ModuleType.ObjectModule, ModuleType.SessionModule }, - scope = DiagnosticScope.BSL - + scope = DiagnosticScope.BSL, + canLocateOnProject = true ) public class SameMetadataObjectAndChildNamesDiagnostic extends AbstractMetadataDiagnostic { @@ -83,28 +85,31 @@ public class SameMetadataObjectAndChildNamesDiagnostic extends AbstractMetadataD } @Override - protected void checkMetadata(AbstractMDObjectBase mdo) { - if (!(mdo instanceof AbstractMDObjectComplex) || ((AbstractMDObjectComplex) mdo).getAttributes().isEmpty()) { + protected void checkMetadata(MD mdo) { + if (!(mdo instanceof ChildrenOwner)) { return; } - var mdoName = stringInterner.intern(mdo.getName()); - ((AbstractMDObjectComplex) mdo).getAttributes().stream() - .filter(attribute -> mdoName.equalsIgnoreCase(attribute.getName())) - .forEach(attribute -> addAttributeDiagnostic(attribute, mdoName)); + if (mdo instanceof AttributeOwner attributeOwner && !attributeOwner.getAllAttributes().isEmpty()) { + var mdoName = stringInterner.intern(mdo.getName()); + checkkAttributes(attributeOwner.getAllAttributes(), mdoName); + } - ((AbstractMDObjectComplex) mdo).getAttributes().stream() - .filter(TabularSection.class::isInstance) - .map(TabularSection.class::cast) - .forEach((TabularSection table) -> { + if (mdo instanceof TabularSectionOwner tabularSectionOwner && !tabularSectionOwner.getTabularSections().isEmpty()) { + tabularSectionOwner.getTabularSections().forEach((TabularSection table) -> { var tableName = stringInterner.intern(table.getName()); - table.getAttributes().stream() - .filter(attribute -> tableName.equalsIgnoreCase(attribute.getName())) - .forEach(attribute -> addAttributeDiagnostic(attribute, tableName)); + checkkAttributes(table.getAllAttributes(), tableName); }); + } + } + + private void checkkAttributes(List attributeOwner, String mdoName) { + attributeOwner.stream() + .filter(attribute -> mdoName.equalsIgnoreCase(attribute.getName())) + .forEach(attribute -> addAttributeDiagnostic(attribute, mdoName)); } - private void addAttributeDiagnostic(AbstractMDOAttribute attribute, String mdoName) { + private void addAttributeDiagnostic(Attribute attribute, String mdoName) { String mdoRef; if (serverConfiguration.getLanguage() == Language.RU) { mdoRef = attribute.getMdoReference().getMdoRefRu(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ScheduledJobHandlerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ScheduledJobHandlerDiagnostic.java index f8611afd67f..9ac63290da1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ScheduledJobHandlerDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ScheduledJobHandlerDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,11 +29,11 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.references.ReferenceIndex; +import com.github._1c_syntax.bsl.mdo.CommonModule; +import com.github._1c_syntax.bsl.mdo.MD; +import com.github._1c_syntax.bsl.mdo.ScheduledJob; import com.github._1c_syntax.bsl.types.MDOType; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; -import com.github._1c_syntax.mdclasses.mdo.MDScheduledJob; import java.util.ArrayList; import java.util.Comparator; @@ -48,9 +48,9 @@ tags = { DiagnosticTag.ERROR }, - scope = DiagnosticScope.BSL + scope = DiagnosticScope.BSL, + canLocateOnProject = true ) - public class ScheduledJobHandlerDiagnostic extends AbstractMetadataDiagnostic { private static final String DIAGNOSTIC_MESSAGE = "diagnosticMessage"; @@ -62,19 +62,19 @@ public class ScheduledJobHandlerDiagnostic extends AbstractMetadataDiagnostic { private static final String DOUBLE_MESSAGE = "doubleMessage"; private final ReferenceIndex referenceIndex; - private final Map> scheduledJobHandlers = new HashMap<>(); + private final Map> scheduledJobHandlers = new HashMap<>(); - private static String getFullName(MDCommonModule mdCommonModule, String methodName) { - return getFullName(mdCommonModule.getName(), methodName); + public ScheduledJobHandlerDiagnostic(ReferenceIndex referenceIndex) { + super(List.of(MDOType.SCHEDULED_JOB)); + this.referenceIndex = referenceIndex; } - private static String getFullName(String commonModuleName, String methodName) { - return commonModuleName.concat(".").concat(methodName); + private static String getFullName(CommonModule commonModule, String methodName) { + return getFullName(commonModule.getName(), methodName); } - public ScheduledJobHandlerDiagnostic(ReferenceIndex referenceIndex) { - super(List.of(MDOType.SCHEDULED_JOB)); - this.referenceIndex = referenceIndex; + private static String getFullName(String commonModuleName, String methodName) { + return commonModuleName.concat(".").concat(methodName); } @Override @@ -86,29 +86,29 @@ protected void check() { private void checkHandlerDoubles() { scheduledJobHandlers.values().stream() .filter(mdScheduledJobs -> mdScheduledJobs.size() > 1) - .map((List mdScheduledJobs) -> { - mdScheduledJobs.sort(Comparator.comparing(AbstractMDObjectBase::getName)); + .map((List mdScheduledJobs) -> { + mdScheduledJobs.sort(Comparator.comparing(ScheduledJob::getName)); return mdScheduledJobs; }) .forEach(this::fireIssueForDoubles); scheduledJobHandlers.clear(); } - private void fireIssueForDoubles(List mdScheduledJobs) { + private void fireIssueForDoubles(List mdScheduledJobs) { final var scheduleJobNames = mdScheduledJobs.stream() - .map(AbstractMDObjectBase::getName) + .map(ScheduledJob::getName) .reduce((s, s2) -> s.concat(", ").concat(s2)) .orElseThrow(); - final var mdScheduledJob = mdScheduledJobs.get(0).getHandler(); + final var mdScheduledJob = mdScheduledJobs.get(0).getMethodName(); final var methodPath = getFullName(mdScheduledJob.getModuleName(), mdScheduledJob.getMethodName()); addDiagnostic(info.getResourceString(DOUBLE_MESSAGE, methodPath, scheduleJobNames)); } @Override - protected void checkMetadata(AbstractMDObjectBase mdo) { - final var scheduleJob = (MDScheduledJob) mdo; - final var handler = scheduleJob.getHandler(); + protected void checkMetadata(MD mdo) { + final var scheduleJob = (ScheduledJob) mdo; + final var handler = scheduleJob.getMethodName(); if (handler.isEmpty()) { addDiagnostic(scheduleJob); return; @@ -116,8 +116,8 @@ protected void checkMetadata(AbstractMDObjectBase mdo) { final var moduleName = handler.getModuleName(); - final var commonModuleOptional = - documentContext.getServerContext().getConfiguration().getCommonModule(moduleName); + final var commonModuleOptional = documentContext.getServerContext().getConfiguration() + .findCommonModule(moduleName); if (commonModuleOptional.isEmpty()) { addDiagnostic(MISSING_MODULE_MESSAGE, scheduleJob, moduleName); return; @@ -130,7 +130,7 @@ protected void checkMetadata(AbstractMDObjectBase mdo) { checkMethod(scheduleJob, mdCommonModule, handler.getMethodName()); } - private void checkMethod(MDScheduledJob scheduleJob, MDCommonModule mdCommonModule, String methodName) { + private void checkMethod(ScheduledJob scheduleJob, CommonModule mdCommonModule, String methodName) { final var fullName = getFullName(mdCommonModule, methodName); scheduledJobHandlers.computeIfAbsent(fullName, k -> new ArrayList<>()).add(scheduleJob); @@ -148,7 +148,7 @@ private void checkMethod(MDScheduledJob scheduleJob, MDCommonModule mdCommonModu }); } - private void checkMethod(MDScheduledJob scheduleJob, String fullName, MethodSymbol methodSymbol) { + private void checkMethod(ScheduledJob scheduleJob, String fullName, MethodSymbol methodSymbol) { if (!methodSymbol.isExport()) { addDiagnostic(NON_EXPORT_METHOD_MESSAGE, scheduleJob, fullName); } @@ -169,11 +169,11 @@ private boolean isEmptyMethodBody(MethodSymbol methodSymbol) { return referenceIndex.getReferencesFrom(methodSymbol).isEmpty(); } - private void addDiagnostic(String messageString, MDScheduledJob scheduleJob, String text) { + private void addDiagnostic(String messageString, ScheduledJob scheduleJob, String text) { addDiagnostic(info.getResourceString(messageString, text, scheduleJob.getName())); } - private void addDiagnostic(MDScheduledJob scheduleJob) { + private void addDiagnostic(ScheduledJob scheduleJob) { addDiagnostic(info.getMessage("", scheduleJob.getName())); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelectTopWithoutOrderByDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelectTopWithoutOrderByDiagnostic.java index 696bc4f662f..d2e3ccdfffb 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelectTopWithoutOrderByDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelectTopWithoutOrderByDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,10 +29,9 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.utils.Trees; import com.github._1c_syntax.bsl.parser.SDBLParser; +import edu.umd.cs.findbugs.annotations.Nullable; import org.antlr.v4.runtime.tree.ParseTree; -import javax.annotation.Nullable; - @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, severity = DiagnosticSeverity.MAJOR, diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelfAssignDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelfAssignDiagnostic.java index 72e22465984..08554aa7505 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelfAssignDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelfAssignDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelfInsertionDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelfInsertionDiagnostic.java index 35705ad24e7..431e7f6eb38 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelfInsertionDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelfInsertionDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SemicolonPresenceDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SemicolonPresenceDiagnostic.java index eb5556a4b24..b0bc10d2665 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SemicolonPresenceDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SemicolonPresenceDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ServerSideExportFormMethodDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ServerSideExportFormMethodDiagnostic.java index 71a4a066503..b0e69044d3f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ServerSideExportFormMethodDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ServerSideExportFormMethodDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,10 +29,10 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdo.Form; +import com.github._1c_syntax.bsl.mdo.MD; import com.github._1c_syntax.bsl.mdo.support.FormType; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDOForm; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; @DiagnosticMetadata( type = DiagnosticType.ERROR, @@ -52,9 +52,9 @@ public class ServerSideExportFormMethodDiagnostic extends AbstractSymbolTreeDiag @Override public void visitModule(ModuleSymbol module) { - documentContext.getMdObject().ifPresent((AbstractMDObjectBase mdo) -> { + documentContext.getMdObject().ifPresent((MD mdo) -> { // проверка актуальна только для управляемых форм - if (mdo instanceof AbstractMDOForm && ((AbstractMDOForm) mdo).getFormType() != FormType.ORDINARY) { + if (mdo instanceof Form form && form.getFormType() != FormType.ORDINARY) { super.visitModule(module); } }); @@ -63,8 +63,7 @@ public void visitModule(ModuleSymbol module) { @Override public void visitMethod(MethodSymbol method) { if (method.isExport() - && method.getCompilerDirectiveKind() - .orElse(CompilerDirectiveKind.AT_SERVER) != CompilerDirectiveKind.AT_CLIENT) { + && method.getCompilerDirectiveKind().orElse(CompilerDirectiveKind.AT_SERVER) != CompilerDirectiveKind.AT_CLIENT) { diagnosticStorage.addDiagnostic(method); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPermissionsForNewObjectsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPermissionsForNewObjectsDiagnostic.java index 9b6496680d0..cb37afe7dad 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPermissionsForNewObjectsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPermissionsForNewObjectsDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,8 +28,8 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.mdo.Role; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.MDRole; import java.util.Map; import java.util.Set; @@ -55,7 +55,7 @@ public class SetPermissionsForNewObjectsDiagnostic extends AbstractDiagnostic { @DiagnosticParameter( type = String.class, - defaultValue = "" + NAMES_FULL_ACCESS_ROLE + defaultValue = NAMES_FULL_ACCESS_ROLE ) private Set namesFullAccessRole = getSetFromString(NAMES_FULL_ACCESS_ROLE); @@ -68,8 +68,8 @@ public void check() { } documentContext.getServerContext().getConfiguration().getRoles().stream() - .filter(role -> role.getRoleData().isSetForNewObjects()) - .map(MDRole::getName) + .filter(role -> role.getData().isSetForNewObjects()) + .map(Role::getName) .filter(Predicate.not(namesFullAccessRole::contains)) .map(info::getMessage) .forEach((String diagnosticMessage) -> diagnosticStorage.addDiagnostic(range, diagnosticMessage) diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPrivilegedModeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPrivilegedModeDiagnostic.java new file mode 100644 index 00000000000..084ec2dc16f --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPrivilegedModeDiagnostic.java @@ -0,0 +1,76 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.utils.CaseInsensitivePattern; + +import java.util.Optional; +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.SECURITY_HOTSPOT, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 1, + tags = { + DiagnosticTag.SUSPICIOUS + }, + scope = DiagnosticScope.BSL +) + +public class SetPrivilegedModeDiagnostic extends AbstractFindMethodDiagnostic { + private static final Pattern messagePattern = CaseInsensitivePattern.compile( + "УстановитьПривилегированныйРежим|SetPrivilegedMode"); + + public SetPrivilegedModeDiagnostic() { + super(messagePattern); + } + + @Override + protected boolean checkGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { + final var result = super.checkGlobalMethodCall(ctx); + if (result && (isSetPrivilegedModeWithFalse(ctx))) { + return false; + } + return result; + } + + private static boolean isSetPrivilegedModeWithFalse(BSLParser.GlobalMethodCallContext ctx) { + return Optional.of(ctx) + .map(BSLParser.GlobalMethodCallContext::doCall) + .map(BSLParser.DoCallContext::callParamList) + .map(BSLParser.CallParamListContext::callParam) + .filter(callParamContexts -> callParamContexts.size() == 1) + .map(callParamContexts -> callParamContexts.get(0)) + .map(BSLParser.CallParamContext::expression) + .map(BSLParser.ExpressionContext::member) + .map(memberContexts -> memberContexts.get(0)) + .map(BSLParser.MemberContext::constValue) + .filter(constValueContext -> constValueContext.FALSE() != null) + .isPresent(); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SeveralCompilerDirectivesDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SeveralCompilerDirectivesDiagnostic.java index da3d1dcd4b7..5394c39447a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SeveralCompilerDirectivesDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SeveralCompilerDirectivesDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SpaceAtStartCommentDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SpaceAtStartCommentDiagnostic.java index f1ea4d37aa9..f3abfd362a7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SpaceAtStartCommentDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SpaceAtStartCommentDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -72,7 +72,7 @@ public class SpaceAtStartCommentDiagnostic extends AbstractDiagnostic implements @DiagnosticParameter( type = String.class, - defaultValue = "" + DEFAULT_COMMENTS_ANNOTATION + defaultValue = DEFAULT_COMMENTS_ANNOTATION ) private Pattern commentsAnnotation = DiagnosticHelper.createPatternFromString(DEFAULT_COMMENTS_ANNOTATION); @@ -116,7 +116,7 @@ public List getQuickFixes( diagnostics.forEach((Diagnostic diagnostic) -> { var range = diagnostic.getRange(); - String currentText = documentContext.getText(range); + var currentText = documentContext.getText(range); var textEdit = new TextEdit( range, diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/StyleElementConstructorsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/StyleElementConstructorsDiagnostic.java index 5cca7acb8e3..11bad234a76 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/StyleElementConstructorsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/StyleElementConstructorsDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -26,6 +26,7 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.bsl.Constructors; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.utils.CaseInsensitivePattern; import org.antlr.v4.runtime.tree.ParseTree; @@ -45,29 +46,13 @@ public class StyleElementConstructorsDiagnostic extends AbstractVisitorDiagnostic { private static final Pattern PATTERN = CaseInsensitivePattern.compile("^(Рамка|Цвет|Шрифт|Color|Border|Font)$"); - private static final Pattern QUOTE_PATTERN = Pattern.compile("\""); @Override public ParseTree visitNewExpression(BSLParser.NewExpressionContext ctx) { - var ctxTypeName = typeName(ctx); - - if (PATTERN.matcher(ctxTypeName).find()) { - diagnosticStorage.addDiagnostic(ctx, info.getMessage(ctxTypeName)); - } + Constructors.typeName(ctx) + .filter(it -> PATTERN.matcher(it).matches()) + .ifPresent(name -> diagnosticStorage.addDiagnostic(ctx, info.getMessage(name))); return super.visitNewExpression(ctx); } - - private static String typeName(BSLParser.NewExpressionContext ctx) { - if (ctx.typeName() != null) { - return ctx.typeName().getText(); - } - - if (ctx.doCall().callParamList().isEmpty()) { - return ""; - } - - return QUOTE_PATTERN.matcher(ctx.doCall().callParamList().callParam(0).getText()).replaceAll(""); - } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TempFilesDirDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TempFilesDirDiagnostic.java index 95093dbeba7..367f007fed7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TempFilesDirDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TempFilesDirDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TernaryOperatorUsageDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TernaryOperatorUsageDiagnostic.java index 582fab9ef66..f5c6a3007b7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TernaryOperatorUsageDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TernaryOperatorUsageDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnostic.java index dead2803477..18b15a562a9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TimeoutsInExternalResourcesDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TimeoutsInExternalResourcesDiagnostic.java index 20d3b39023b..fa42b781986 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TimeoutsInExternalResourcesDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TimeoutsInExternalResourcesDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -32,9 +32,9 @@ import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.support.CompatibilityMode; import com.github._1c_syntax.utils.CaseInsensitivePattern; +import edu.umd.cs.findbugs.annotations.Nullable; import org.antlr.v4.runtime.tree.ParseTree; -import javax.annotation.CheckForNull; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -84,7 +84,7 @@ private Pattern getPatternNewExpression() { } } - private static String getVariableName(@CheckForNull BSLParser.StatementContext statement) { + private static String getVariableName(@Nullable BSLParser.StatementContext statement) { var variableName = ""; if (statement != null && statement.assignment() != null) { var lValueContext = statement.assignment().lValue(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TooManyReturnsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TooManyReturnsDiagnostic.java index 796a1a7e9d8..94f82b3c09a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TooManyReturnsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TooManyReturnsDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TransferringParametersBetweenClientAndServerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TransferringParametersBetweenClientAndServerDiagnostic.java new file mode 100644 index 00000000000..116c88db32c --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TransferringParametersBetweenClientAndServerDiagnostic.java @@ -0,0 +1,180 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.ParameterDefinition; +import com.github._1c_syntax.bsl.languageserver.context.symbol.VariableSymbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.annotations.CompilerDirectiveKind; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.references.ReferenceIndex; +import com.github._1c_syntax.bsl.languageserver.references.model.OccurrenceType; +import com.github._1c_syntax.bsl.languageserver.references.model.Reference; +import com.github._1c_syntax.bsl.languageserver.utils.RelatedInformation; +import lombok.AllArgsConstructor; +import lombok.RequiredArgsConstructor; +import lombok.Value; +import org.eclipse.lsp4j.DiagnosticRelatedInformation; +import org.eclipse.lsp4j.SymbolKind; + +import java.util.Collection; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@DiagnosticMetadata( + type = DiagnosticType.CODE_SMELL, + severity = DiagnosticSeverity.MAJOR, + minutesToFix = 2, + tags = { + DiagnosticTag.BADPRACTICE, + DiagnosticTag.PERFORMANCE, + DiagnosticTag.STANDARD + } +) +@RequiredArgsConstructor +public class TransferringParametersBetweenClientAndServerDiagnostic extends AbstractDiagnostic { + private static final Set SERVER_COMPILER_DIRECTIVE_KINDS = EnumSet.of( + CompilerDirectiveKind.AT_SERVER, + CompilerDirectiveKind.AT_SERVER_NO_CONTEXT + ); + + private final ReferenceIndex referenceIndex; + + // Не учитываются вложенные вызовы. Только прямые - клиентский метод вызывает серверный метод напрямую + + @Override + protected void check() { + calcIssues() + .forEach(paramReference -> paramReference.getParameterDefinitions().forEach(parameterDefinition -> + diagnosticStorage.addDiagnostic(parameterDefinition.getRange(), + info.getMessage(parameterDefinition.getName(), paramReference.getMethodSymbol().getName()), + getRelatedInformation(paramReference.getReferences()))) + ); + } + + private Stream calcIssues() { + return documentContext.getSymbolTree().getMethods().stream() + .filter(TransferringParametersBetweenClientAndServerDiagnostic::isEqualCompilerDirectives) + .flatMap(methodSymbol -> getParamReference(methodSymbol).stream()); + } + + private Optional getParamReference(MethodSymbol method) { + var parameterDefinitions = calcNotAssignedParams(method); + if (parameterDefinitions.isEmpty()) { + return Optional.empty(); + } + final var refsFromClientCalls = getRefsFromClientCalls(method); + if (refsFromClientCalls.isEmpty()) { + return Optional.empty(); + } + return Optional.of(new ParamReference(method, parameterDefinitions, + refsFromClientCalls)); + } + + private List calcNotAssignedParams(MethodSymbol method) { + var parameterDefinitions = getMethodParamsByRef(method); + if (parameterDefinitions.isEmpty()) { + return Collections.emptyList(); + } + return calcNotAssignedParams(method, parameterDefinitions); + } + + private List calcNotAssignedParams(MethodSymbol method, + List parameterDefinitions) { + return parameterDefinitions.stream() + .filter(parameterDefinition -> isAssignedParam(method, parameterDefinition)) + .toList(); + } + + private boolean isAssignedParam(MethodSymbol method, ParameterDefinition parameterDefinition) { + return getVariableByParameter(method, parameterDefinition) + .noneMatch(variableSymbol -> referenceIndex.getReferencesTo(variableSymbol).stream() + .anyMatch(ref -> ref.getOccurrenceType() == OccurrenceType.DEFINITION)); + } + + private static Stream getVariableByParameter(MethodSymbol method, + ParameterDefinition parameterDefinition) { + return method.getChildren().stream() + // в будущем могут появиться и другие символы, подчиненные методам + .filter(sourceDefinedSymbol -> sourceDefinedSymbol.getSymbolKind() == SymbolKind.Variable) + .filter(variable -> parameterDefinition.getRange().getStart().equals(variable.getSelectionRange().getStart())) + .filter(VariableSymbol.class::isInstance) + .map(VariableSymbol.class::cast) + .findFirst().stream(); + } + + private List getRefsFromClientCalls(MethodSymbol method) { + return referenceIndex.getReferencesTo(method).stream() + // в будущем могут появиться и другие виды ссылок + .filter(ref -> ref.getOccurrenceType() == OccurrenceType.REFERENCE) + .filter(TransferringParametersBetweenClientAndServerDiagnostic::isClientCall) + .toList(); + } + + private static boolean isClientCall(Reference ref) { + return Optional.of(ref.getFrom()) + .filter(MethodSymbol.class::isInstance) + .map(MethodSymbol.class::cast) + .filter(TransferringParametersBetweenClientAndServerDiagnostic::isEqualCompilerDirective) + .isPresent(); + } + + private static boolean isEqualCompilerDirectives(MethodSymbol method) { + return method.getCompilerDirectiveKind() + .filter(((Collection) SERVER_COMPILER_DIRECTIVE_KINDS)::contains) + .isPresent(); + } + + private static boolean isEqualCompilerDirective(MethodSymbol method) { + return method.getCompilerDirectiveKind() + .filter(compilerDirective -> compilerDirective == CompilerDirectiveKind.AT_CLIENT) + .isPresent(); + } + + private static List getMethodParamsByRef(MethodSymbol methodSymbol) { + return methodSymbol.getParameters().stream() + .filter(parameterDefinition -> !parameterDefinition.isByValue()) + .toList(); + } + + private static List getRelatedInformation(List references) { + return references.stream() + .map(reference -> RelatedInformation.create(reference.getUri(), reference.getSelectionRange(), "+1")) + .collect(Collectors.toList()); + } + + @Value + @AllArgsConstructor + private static class ParamReference { + MethodSymbol methodSymbol; + List parameterDefinitions; + List references; + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TryNumberDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TryNumberDiagnostic.java index 20bf2153458..ea568a0643e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TryNumberDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TryNumberDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic.java index f69408ce566..e0903842509 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -38,8 +38,7 @@ import org.antlr.v4.runtime.Token; import org.apache.commons.lang3.StringUtils; import org.languagetool.JLanguageTool; -import org.languagetool.language.AmericanEnglish; -import org.languagetool.language.Russian; +import org.languagetool.Languages; import org.languagetool.rules.RuleMatch; import java.io.IOException; @@ -68,8 +67,8 @@ public class TypoDiagnostic extends AbstractDiagnostic { @Getter(lazy = true, value = AccessLevel.PRIVATE) private static final Map languageToolPoolMap = Map.of( - "en", new JLanguageToolPool(new AmericanEnglish()), - "ru", new JLanguageToolPool(new Russian()) + "en", new JLanguageToolPool(Languages.getLanguageForShortCode("en-US")), + "ru", new JLanguageToolPool(Languages.getLanguageForShortCode("ru")) ); /** diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnaryPlusInConcatenationDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnaryPlusInConcatenationDiagnostic.java index 530b547865e..6c872a7303f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnaryPlusInConcatenationDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnaryPlusInConcatenationDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnionAllDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnionAllDiagnostic.java index c94762d1bd7..6d6aef9b2ff 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnionAllDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnionAllDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnknownPreprocessorSymbolDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnknownPreprocessorSymbolDiagnostic.java index d64b5ee8d1c..36696834cbc 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnknownPreprocessorSymbolDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnknownPreprocessorSymbolDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnostic.java index 4999bedebb9..f602790a4ae 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java index ad37e3fb99c..c16475e1d6f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalMethodDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalMethodDiagnostic.java index 2323e5201aa..adb3ad09868 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalMethodDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalMethodDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -37,18 +37,17 @@ import org.antlr.v4.runtime.tree.Trees; import java.util.EnumSet; -import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; -import java.util.stream.Collectors; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, severity = DiagnosticSeverity.MAJOR, modules = { - ModuleType.CommonModule + ModuleType.CommonModule, + ModuleType.ObjectModule }, minutesToFix = 1, tags = { @@ -74,6 +73,7 @@ public class UnusedLocalMethodDiagnostic extends AbstractVisitorDiagnostic { AnnotationKind.BEFORE, AnnotationKind.CHANGEANDVALIDATE ); + private static final boolean CHECK_OBJECT_MODULE = false; @DiagnosticParameter( type = String.class, @@ -81,10 +81,18 @@ public class UnusedLocalMethodDiagnostic extends AbstractVisitorDiagnostic { ) private Pattern attachableMethodPrefixes = DiagnosticHelper.createPatternFromString(ATTACHABLE_METHOD_PREFIXES); + @DiagnosticParameter( + type = Boolean.class, + defaultValue = "" + CHECK_OBJECT_MODULE + ) + private boolean checkObjectModule = CHECK_OBJECT_MODULE; + @Override public void configure(Map configuration) { this.attachableMethodPrefixes = DiagnosticHelper.createPatternFromString( (String) configuration.getOrDefault("attachableMethodPrefixes", ATTACHABLE_METHOD_PREFIXES)); + + this.checkObjectModule = (boolean) configuration.getOrDefault("checkObjectModule", CHECK_OBJECT_MODULE); } private boolean isAttachable(MethodSymbol methodSymbol) { @@ -104,12 +112,16 @@ private static boolean isOverride(MethodSymbol method) { @Override public ParseTree visitFile(BSLParser.FileContext ctx) { + var moduleType = documentContext.getModuleType(); + if (!checkObjectModule && moduleType == ModuleType.ObjectModule) { + return ctx; + } - List collect = Trees.findAllRuleNodes(ctx, BSLParser.RULE_globalMethodCall) + var collect = Trees.findAllRuleNodes(ctx, BSLParser.RULE_globalMethodCall) .stream() .map(parseTree -> ((BSLParser.GlobalMethodCallContext) parseTree).methodName().getText().toLowerCase(Locale.ENGLISH)) - .collect(Collectors.toList()); + .toList(); documentContext.getSymbolTree().getMethods() .stream() diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalVariableDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalVariableDiagnostic.java index f18110f93f3..943683239ff 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalVariableDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalVariableDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -66,7 +66,11 @@ public void check() { documentContext.getSymbolTree().getVariables().stream() .filter(variable -> CHECKING_VARIABLE_KINDS.contains(variable.getKind())) .filter(variable -> !variable.isExport()) - .filter(variable -> referenceIndex.getReferencesTo(variable).stream().filter(ref -> ref.getOccurrenceType() == OccurrenceType.REFERENCE).findFirst().isEmpty()) - .forEach(variable -> diagnosticStorage.addDiagnostic(variable.getSelectionRange(), info.getMessage(variable.getName()))); + .filter(variable -> referenceIndex.getReferencesTo(variable).stream() + .filter(ref -> ref.getOccurrenceType() == OccurrenceType.REFERENCE).findFirst().isEmpty() + ) + .forEach(variable -> diagnosticStorage.addDiagnostic( + variable.getSelectionRange(), info.getMessage(variable.getName())) + ); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedParametersDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedParametersDiagnostic.java index ae6714e993a..cb972229a63 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedParametersDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedParametersDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -31,10 +31,8 @@ import com.github._1c_syntax.utils.CaseInsensitivePattern; import org.antlr.v4.runtime.tree.ParseTree; -import java.util.List; import java.util.Locale; import java.util.Objects; -import java.util.Optional; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -62,9 +60,16 @@ public ParseTree visitSubCodeBlock(BSLParser.SubCodeBlockContext ctx) { return ctx; } - List paramsNames = Trees.findAllRuleNodes(ctx.getParent(), BSLParser.RULE_param) + var params = Trees.findAllRuleNodes(ctx.getParent(), BSLParser.RULE_param) .stream() - .map(node -> ((BSLParser.ParamContext) node).IDENTIFIER().getText().toLowerCase(Locale.getDefault())) + .map(BSLParser.ParamContext.class::cast) + .map(BSLParser.ParamContext::IDENTIFIER) + .filter(Objects::nonNull) + .toList(); + + var paramsNames = params + .stream() + .map(ind -> ind.getText().toLowerCase(Locale.getDefault())) .collect(Collectors.toList()); Trees.findAllTokenNodes(ctx, BSLParser.IDENTIFIER) @@ -74,9 +79,8 @@ public ParseTree visitSubCodeBlock(BSLParser.SubCodeBlockContext ctx) { paramsNames.remove((node.getText().toLowerCase(Locale.getDefault()))) ); - Trees.findAllRuleNodes(ctx.getParent(), BSLParser.RULE_param) + params .stream() - .map(param -> ((BSLParser.ParamContext) param).IDENTIFIER()) .filter(param -> paramsNames.contains(param.getText().toLowerCase(Locale.getDefault()))) .forEach(param -> diagnosticStorage.addDiagnostic(param, info.getMessage(param.getText())) @@ -86,15 +90,11 @@ public ParseTree visitSubCodeBlock(BSLParser.SubCodeBlockContext ctx) { } private static boolean itsHandler(BSLParser.SubCodeBlockContext ctx) { - - Optional subNames = Trees.findAllRuleNodes(ctx.getParent(), BSLParser.RULE_subName).stream().findFirst(); - - String subName = ""; + var subNames = Trees.findAllRuleNodes(ctx.getParent(), BSLParser.RULE_subName).stream().findFirst(); + var subName = ""; if (subNames.isPresent()) { subName = subNames.get().getText(); } - return HANDLER_PATTERN.matcher(subName).matches(); } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsageWriteLogEventDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsageWriteLogEventDiagnostic.java index bd5ec8f1877..ecdb74378c5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsageWriteLogEventDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsageWriteLogEventDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,14 +29,15 @@ import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import com.github._1c_syntax.utils.CaseInsensitivePattern; +import edu.umd.cs.findbugs.annotations.Nullable; import org.antlr.v4.runtime.tree.ParseTree; -import javax.annotation.Nullable; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.regex.Pattern; +import java.util.stream.Collectors; @DiagnosticMetadata( type = DiagnosticType.CODE_SMELL, @@ -70,6 +71,9 @@ public class UsageWriteLogEventDiagnostic extends AbstractVisitorDiagnostic { private static final Pattern PATTERN_ERROR = CaseInsensitivePattern.compile( "ошибка|error" ); + private static final Pattern ERROR_PROCESSING_ERROR = CaseInsensitivePattern.compile( + "обработкаошибок|errorprocessing" + ); private static final int WRITE_LOG_EVENT_METHOD_PARAMS_COUNT = 5; public static final int COMMENTS_PARAM_INDEX = 4; @@ -93,7 +97,7 @@ public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext context private void checkParams(BSLParser.GlobalMethodCallContext context) { final var callParams = context.doCall().callParamList().callParam(); - if (!checkFirstParams(context, callParams)){ + if (!checkFirstParams(context, callParams)) { return; } @@ -112,7 +116,10 @@ private void checkParams(BSLParser.GlobalMethodCallContext context) { } } - private boolean checkFirstParams(BSLParser.GlobalMethodCallContext context, List callParams) { + private boolean checkFirstParams( + BSLParser.GlobalMethodCallContext context, + List callParams + ) { if (callParams.size() < WRITE_LOG_EVENT_METHOD_PARAMS_COUNT) { fireIssue(context, WRONG_NUMBER_MESSAGE); return false; @@ -176,7 +183,7 @@ private static boolean isCommentCorrect(BSLParser.CallParamContext commentsCtx) if (hasRaiseStatement(codeBlockContext)) { return true; } - return isValidExpression(codeBlockContext, commentsCtx.expression(), true); + return isValidCommentExpression(codeBlockContext, commentsCtx.expression(), true); } private static boolean hasRaiseStatement(BSLParser.CodeBlockContext codeBlockContext) { @@ -192,7 +199,7 @@ private static boolean hasRaiseStatement(BSLParser.CodeBlockContext codeBlockCon // то проверим, что в присвоении есть ПодробноеПредставлениеОшибки(ИнформацияОбОшибке() // если есть какая-то переменная, определенная на уровень выше (например, параметр метода), то не анализируем ее - private static boolean isValidExpression( + private static boolean isValidCommentExpression( BSLParser.CodeBlockContext codeBlock, @Nullable BSLParser.ExpressionContext expression, boolean checkPrevAssignment @@ -200,49 +207,70 @@ private static boolean isValidExpression( if (expression == null) { return true; } - final var assignmentGlobalCalls = Trees.findAllRuleNodes(expression, BSLParser.RULE_globalMethodCall); - if (!assignmentGlobalCalls.isEmpty()) { - if (isErrorDescriptionCallCorrect(assignmentGlobalCalls)) { + final var methodCalls = Trees.findAllRuleNodes(expression, + List.of(BSLParser.RULE_globalMethodCall, BSLParser.RULE_methodCall)).stream() + .filter(BSLParserRuleContext.class::isInstance) + .map(BSLParserRuleContext.class::cast) + .collect(Collectors.toList()); + if (!methodCalls.isEmpty()) { + if (isErrorDescriptionCallCorrect(methodCalls)) { return true; } - if (hasSimpleErrorDescription(assignmentGlobalCalls) || hasBriefErrorDescription(assignmentGlobalCalls)) { + if (hasSimpleErrorDescription(methodCalls) || hasBriefErrorDescription(methodCalls)) { return false; } } + return isValidExpression(expression, codeBlock, checkPrevAssignment); } - private static boolean isErrorDescriptionCallCorrect(Collection globalCalls) { - return globalCalls.stream() - .filter(context -> context instanceof BSLParser.GlobalMethodCallContext) - .map(BSLParser.GlobalMethodCallContext.class::cast) - .filter(context -> isAppropriateName(context, PATTERN_DETAIL_ERROR_DESCRIPTION)) - .anyMatch(UsageWriteLogEventDiagnostic::hasFirstDescendantGlobalCall); + private static boolean isErrorDescriptionCallCorrect(Collection calls) { + return calls.stream() + .filter(context -> isAppropriateMethodName(context, PATTERN_DETAIL_ERROR_DESCRIPTION)) + .filter(context -> context instanceof BSLParser.GlobalMethodCallContext + || (context instanceof BSLParser.MethodCallContext && isErrorProcessingCall((BSLParser.MethodCallContext) context))) + .anyMatch(UsageWriteLogEventDiagnostic::hasFirstDescendantGlobalCallWithPatternError); } - private static boolean isAppropriateName( - BSLParser.GlobalMethodCallContext context, + private static boolean isAppropriateMethodName( + BSLParserRuleContext context, Pattern patternDetailErrorDescription ) { - return patternDetailErrorDescription.matcher(context.methodName().getText()).matches(); + BSLParser.MethodNameContext methodNameContext = context.getRuleContext(BSLParser.MethodNameContext.class, 0); + return patternDetailErrorDescription.matcher(methodNameContext.getText()).matches(); + } + + private static boolean isErrorProcessingCall(BSLParser.MethodCallContext methodCallContext) { + return Optional.of(methodCallContext) + .map(BSLParserRuleContext::getParent) + .filter(context -> context instanceof BSLParser.AccessCallContext) + .map(BSLParserRuleContext::getParent) + .filter(context -> context instanceof BSLParser.ModifierContext) + .map(BSLParserRuleContext::getParent) + .filter(context -> context instanceof BSLParser.ComplexIdentifierContext) + .map(BSLParser.ComplexIdentifierContext.class::cast) + .map(BSLParser.ComplexIdentifierContext::IDENTIFIER) + .filter(terminalNode -> ERROR_PROCESSING_ERROR.matcher(terminalNode.getText()).matches()) + .isPresent(); } - private static boolean hasFirstDescendantGlobalCall(BSLParser.GlobalMethodCallContext globalCallCtx) { + private static boolean hasFirstDescendantGlobalCallWithPatternError(BSLParserRuleContext globalCallCtx) { return Trees.findAllRuleNodes(globalCallCtx, BSLParser.RULE_globalMethodCall).stream() .map(BSLParser.GlobalMethodCallContext.class::cast) - .anyMatch(context -> isAppropriateName(context, PATTERN_ERROR_INFO)); + .anyMatch(context -> isAppropriateMethodName(context, PATTERN_ERROR_INFO)); } - private static boolean hasSimpleErrorDescription(Collection globalCalls) { + private static boolean hasSimpleErrorDescription(Collection globalCalls) { return globalCalls.stream() .filter(context -> context instanceof BSLParser.GlobalMethodCallContext) - .anyMatch(context -> isAppropriateName((BSLParser.GlobalMethodCallContext) context, PATTERN_SIMPLE_ERROR_DESCRIPTION)); + .anyMatch(context -> isAppropriateMethodName(context, PATTERN_SIMPLE_ERROR_DESCRIPTION)); } - private static boolean hasBriefErrorDescription(Collection globalCalls) { - return globalCalls.stream() - .filter(context -> context instanceof BSLParser.GlobalMethodCallContext) - .anyMatch(context -> isAppropriateName((BSLParser.GlobalMethodCallContext) context, PATTERN_BRIEF_ERROR_DESCRIPTION)); + private static boolean hasBriefErrorDescription(Collection calls) { + return calls.stream() + .filter(context -> isAppropriateMethodName(context, PATTERN_BRIEF_ERROR_DESCRIPTION)) + .anyMatch(context -> context instanceof BSLParser.GlobalMethodCallContext + || (context instanceof BSLParser.MethodCallContext && isErrorProcessingCall((BSLParser.MethodCallContext) context))); } private static boolean isValidExpression(BSLParser.ExpressionContext context, BSLParser.CodeBlockContext codeBlock, @@ -272,7 +300,7 @@ private static boolean isValidVarAssignment( String varName = identifierContext.getText(); return getAssignment(varName, codeBlock) .map(BSLParser.AssignmentContext::expression) - .map(expression -> isValidExpression(codeBlock, expression, false)) + .map(expression -> isValidCommentExpression(codeBlock, expression, false)) .orElse(true); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnostic.java index 487d3017daa..4a9c15d7844 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseSystemInformationDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseSystemInformationDiagnostic.java new file mode 100644 index 00000000000..8fc9511346b --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseSystemInformationDiagnostic.java @@ -0,0 +1,58 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.languageserver.utils.bsl.Constructors; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.utils.CaseInsensitivePattern; +import org.antlr.v4.runtime.tree.ParseTree; + +import java.util.regex.Pattern; + +@DiagnosticMetadata( + type = DiagnosticType.SECURITY_HOTSPOT, + severity = DiagnosticSeverity.CRITICAL, + activatedByDefault = false, + minutesToFix = 5, + tags = { + DiagnosticTag.SUSPICIOUS + } + +) +public class UseSystemInformationDiagnostic extends AbstractVisitorDiagnostic { + + private static final Pattern PATTERN = CaseInsensitivePattern.compile("^(СистемнаяИнформация|SystemInfo)$"); + + + @Override + public ParseTree visitNewExpression(BSLParser.NewExpressionContext ctx) { + Constructors.typeName(ctx) + .filter(it -> PATTERN.matcher(it).matches()) + .ifPresent(it -> diagnosticStorage.addDiagnostic(ctx)); + + return super.visitNewExpression(ctx); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingCancelParameterDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingCancelParameterDiagnostic.java index 8584f355fd5..38616f1cee8 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingCancelParameterDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingCancelParameterDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingExternalCodeToolsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingExternalCodeToolsDiagnostic.java index d367979e05e..5eeeb9d3b46 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingExternalCodeToolsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingExternalCodeToolsDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnostic.java index 89590b7fc09..628b7d1a108 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -30,7 +30,6 @@ import com.github._1c_syntax.utils.CaseInsensitivePattern; import org.antlr.v4.runtime.tree.ParseTree; -import java.util.regex.Matcher; import java.util.regex.Pattern; @DiagnosticMetadata( @@ -48,13 +47,13 @@ public class UsingFindElementByStringDiagnostic extends AbstractVisitorDiagnostic { private final Pattern pattern = CaseInsensitivePattern.compile( - "(НайтиПоНаименованию|FindByDescription|НайтиПоКоду|FindByCode)" + "(НайтиПоНаименованию|FindByDescription|НайтиПоКоду|FindByCode|НайтиПоНомеру|FindByNumber)" ); @Override public ParseTree visitMethodCall(BSLParser.MethodCallContext ctx) { - Matcher matcher = pattern.matcher(ctx.methodName().getText()); - if (matcher.find()) { + var matcher = pattern.matcher(ctx.methodName().getText()); + if (matcher.matches()) { BSLParser.CallParamContext param = ctx.doCall().callParamList().callParam().get(0); if (param.children == null || param.getStart().getType() == BSLParser.STRING || diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingGotoDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingGotoDiagnostic.java index 727886808c4..374a422a924 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingGotoDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingGotoDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodeNetworkAddressDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodeNetworkAddressDiagnostic.java index 60f9d0bceeb..0658f845d00 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodeNetworkAddressDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodeNetworkAddressDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodePathDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodePathDiagnostic.java index e0bfe39a78a..b30b513d893 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodePathDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodePathDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodeSecretInformationDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodeSecretInformationDiagnostic.java index dfdf9137115..72672625eab 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodeSecretInformationDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodeSecretInformationDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingLikeInQueryDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingLikeInQueryDiagnostic.java index e43dae6e4d2..bcfad90a863 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingLikeInQueryDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingLikeInQueryDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnostic.java index c5443be0b4c..dd17454342e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,6 +28,7 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdclasses.Configuration; import com.github._1c_syntax.bsl.mdo.support.UseMode; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.utils.CaseInsensitivePattern; @@ -95,10 +96,10 @@ public UsingModalWindowsDiagnostic() { @Override public ParseTree visitFile(BSLParser.FileContext ctx) { var configuration = documentContext.getServerContext().getConfiguration(); - // если использование модальных окон разрешено (без предупреждение) + // если использование модальных окон разрешено (без предупреждения) // и не установлен флаг игнорирования использования модальных окон, то // ничего не диагностируется - if (!forceModalityMode && configuration.getModalityUseMode() == UseMode.USE) { + if (!forceModalityMode && configuration instanceof Configuration cf && cf.getModalityUseMode() == UseMode.USE) { return ctx; } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingObjectNotAvailableUnixDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingObjectNotAvailableUnixDiagnostic.java index 4467f37574f..b003e94c39f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingObjectNotAvailableUnixDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingObjectNotAvailableUnixDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingServiceTagDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingServiceTagDiagnostic.java index 8d58d95ae2d..baff5391937 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingServiceTagDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingServiceTagDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,7 +29,6 @@ import org.antlr.v4.runtime.Token; import java.util.Map; -import java.util.regex.Matcher; import java.util.regex.Pattern; @DiagnosticMetadata( @@ -49,7 +48,7 @@ public class UsingServiceTagDiagnostic extends AbstractDiagnostic { @DiagnosticParameter( type = String.class, - defaultValue = "" + SERVICE_TAGS_DEFAULT + defaultValue = SERVICE_TAGS_DEFAULT ) private String serviceTags = SERVICE_TAGS_DEFAULT; private Pattern pattern = getPatternSearch(SERVICE_TAGS_DEFAULT); @@ -71,7 +70,7 @@ public void check() { documentContext.getComments() .parallelStream() .forEach((Token token) -> { - Matcher matcher = pattern.matcher(token.getText()); + var matcher = pattern.matcher(token.getText()); if (!matcher.find()) { return; } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnostic.java index a82de659945..f622174fb8d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,6 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.context.symbol.annotations.CompilerDirectiveKind; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCompatibilityMode; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata; @@ -28,6 +29,8 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; +import com.github._1c_syntax.bsl.mdclasses.Configuration; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.bsl.mdo.support.UseMode; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.utils.CaseInsensitivePattern; @@ -127,15 +130,36 @@ public UsingSynchronousCallsDiagnostic() { @Override public ParseTree visitFile(BSLParser.FileContext ctx) { var configuration = documentContext.getServerContext().getConfiguration(); - // если использование синхронных вызовов разрешено (без предупреждение), то + // если использование синхронных вызовов разрешено (без предупреждения), то // ничего не диагностируется - if (configuration.getSynchronousExtensionAndAddInCallUseMode() == UseMode.USE) { + if (configuration instanceof Configuration cf && cf.getSynchronousExtensionAndAddInCallUseMode() == UseMode.USE) { + return ctx; + } + + if (isServerModule(documentContext)) { return ctx; } return super.visitFile(ctx); } + private static boolean isServerModule(DocumentContext documentContext) { + return switch (documentContext.getModuleType()) { + case ApplicationModule, CommandModule, FormModule, ManagedApplicationModule -> false; + case CommonModule -> isServerCommonModule(documentContext); + default -> true; // Все прочие модули это строго серверные и в них синхронные вызовы разрешены + }; + } + + private static boolean isServerCommonModule(DocumentContext documentContext) { + var mdObject = documentContext.getMdObject(); + + return mdObject.map(CommonModule.class::cast) + .filter(commonModule -> !(commonModule.isClientManagedApplication() || + commonModule.isClientOrdinaryApplication())) + .isPresent(); + } + @Override public ParseTree visitSub(BSLParser.SubContext ctx) { var methodSymbol = documentContext.getSymbolTree().getMethodSymbol(ctx); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingThisFormDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingThisFormDiagnostic.java index 506e94fbd3f..d3fc3c80a0d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingThisFormDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingThisFormDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/VirtualTableCallWithoutParametersDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/VirtualTableCallWithoutParametersDiagnostic.java index 849f7ae7759..7deedaeda04 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/VirtualTableCallWithoutParametersDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/VirtualTableCallWithoutParametersDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongDataPathForFormElementsDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongDataPathForFormElementsDiagnostic.java index d19e05e5c91..8d1e23504ec 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongDataPathForFormElementsDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongDataPathForFormElementsDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -27,11 +27,11 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.mdo.Form; +import com.github._1c_syntax.bsl.mdo.MD; +import com.github._1c_syntax.bsl.mdo.storage.form.FormItem; import com.github._1c_syntax.bsl.mdo.support.ScriptVariant; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; -import com.github._1c_syntax.mdclasses.mdo.children.Form; -import com.github._1c_syntax.mdclasses.mdo.children.form.FormItem; import org.eclipse.lsp4j.Range; import java.util.function.Predicate; @@ -50,7 +50,6 @@ tags = { DiagnosticTag.UNPREDICTABLE, } - ) public class WrongDataPathForFormElementsDiagnostic extends AbstractDiagnostic { @@ -58,7 +57,6 @@ public class WrongDataPathForFormElementsDiagnostic extends AbstractDiagnostic { @Override protected void check() { - var range = documentContext.getSymbolTree().getModule().getSelectionRange(); if (!Ranges.isEmpty(range)) { checkCurrentModule(range); @@ -66,7 +64,7 @@ protected void check() { } private static boolean wrongDataPath(FormItem formItem) { - return formItem.getDataPath().getSegment().startsWith("~"); + return formItem.getDataPath().segments().startsWith("~"); } private static boolean haveFormModules(Form form) { @@ -86,11 +84,10 @@ private void checkCurrentModule(Range range) { private void checkAllFormsWithoutModules() { checkMdoObjectStream(form -> !haveFormModules(form), - documentContext.getServerContext().getConfiguration().getChildrenByMdoRef().values().stream()); + documentContext.getServerContext().getConfiguration().getPlainChildren().stream()); } - private void checkMdoObjectStream(Predicate

formFilter, Stream stream) { - + private void checkMdoObjectStream(Predicate formFilter, Stream stream) { stream .filter(Form.class::isInstance) .map(Form.class::cast) @@ -99,13 +96,11 @@ private void checkMdoObjectStream(Predicate formFilter, Stream diagnosticStorage.addDiagnostic(diagnosticRange, diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongHttpServiceHandlerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongHttpServiceHandlerDiagnostic.java index ea863988492..30ae3c06bda 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongHttpServiceHandlerDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongHttpServiceHandlerDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,9 +28,9 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.mdo.HTTPService; +import com.github._1c_syntax.bsl.mdo.children.HTTPServiceMethod; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.MDHttpService; -import com.github._1c_syntax.mdclasses.mdo.children.HTTPServiceMethod; import org.eclipse.lsp4j.Range; @DiagnosticMetadata( @@ -64,18 +64,16 @@ protected void check() { private void processModule() { documentContext.getMdObject() - .filter(MDHttpService.class::isInstance) - .map(MDHttpService.class::cast) + .filter(HTTPService.class::isInstance) + .map(HTTPService.class::cast) .ifPresent(this::checkService); } - private void checkService(MDHttpService mdHttpService) { - - mdHttpService.getUrlTemplates().stream() - .flatMap(httpServiceURLTemplate -> httpServiceURLTemplate.getHttpServiceMethods().stream()) + private void checkService(HTTPService httpService) { + httpService.getUrlTemplates().stream() + .flatMap(httpServiceURLTemplate -> httpServiceURLTemplate.getMethods().stream()) .forEach((HTTPServiceMethod service) -> { final var serviceName = service.getMdoReference().getMdoRef(); - if (service.getHandler().isEmpty()) { addMissingHandlerDiagnostic(serviceName); return; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongUseFunctionProceedWithCallDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongUseFunctionProceedWithCallDiagnostic.java index 1bceaf8f125..1ce3c739a06 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongUseFunctionProceedWithCallDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongUseFunctionProceedWithCallDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongUseOfRollbackTransactionMethodDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongUseOfRollbackTransactionMethodDiagnostic.java index e3fd2d8bfe8..75202a9fdb6 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongUseOfRollbackTransactionMethodDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongUseOfRollbackTransactionMethodDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -31,7 +31,6 @@ import com.github._1c_syntax.utils.CaseInsensitivePattern; import java.util.regex.Pattern; -import java.util.stream.Collectors; @DiagnosticMetadata( type = DiagnosticType.ERROR, @@ -41,7 +40,6 @@ tags = { DiagnosticTag.STANDARD } - ) public class WrongUseOfRollbackTransactionMethodDiagnostic extends AbstractFindMethodDiagnostic { @@ -65,7 +63,7 @@ protected boolean checkGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { var methodsList = Trees.findAllRuleNodes(parentNode, BSLParser.RULE_globalMethodCall).stream() .map(BSLParser.GlobalMethodCallContext.class::cast) .map(e -> e.methodName().getText()) - .collect(Collectors.toList()); + .toList(); if (MESSAGE_PATTERN.matcher(ctx.methodName().getText()).matches()) { return methodsList.indexOf(ctx.methodName().getText()) != 0; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongWebServiceHandlerDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongWebServiceHandlerDiagnostic.java index b281f8763a6..5db09abf223 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongWebServiceHandlerDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongWebServiceHandlerDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -27,9 +27,9 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.mdo.WebService; +import com.github._1c_syntax.bsl.mdo.children.WebServiceOperation; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.MDWebService; -import com.github._1c_syntax.mdclasses.mdo.children.WEBServiceOperation; import org.eclipse.lsp4j.Range; @DiagnosticMetadata( @@ -63,20 +63,19 @@ protected void check() { private void processModule() { documentContext.getMdObject() - .filter(MDWebService.class::isInstance) - .map(MDWebService.class::cast) + .filter(WebService.class::isInstance) + .map(WebService.class::cast) .ifPresent(this::checkService); } - private void checkService(MDWebService mdWebService) { - + private void checkService(WebService mdWebService) { mdWebService.getOperations() .forEach(webServiceOperation -> checkOperation(mdWebService.getName(), webServiceOperation)); } - private void checkOperation(String serviceName, WEBServiceOperation webServiceOperation) { + private void checkOperation(String serviceName, WebServiceOperation webServiceOperation) { final var operationName = webServiceOperation.getName(); - final var handler = webServiceOperation.getHandler(); + final var handler = webServiceOperation.getProcedureName(); if (handler.isEmpty()) { addMissingHandlerDiagnostic(serviceName, operationName); return; @@ -101,5 +100,4 @@ private void addMissingHandlerDiagnostic(String serviceName, String operationNam diagnosticRange, info.getResourceString("missingHandler", operationName, serviceName)); } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/YoLetterUsageDiagnostic.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/YoLetterUsageDiagnostic.java index 7610e8f39d4..4f4d2000feb 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/YoLetterUsageDiagnostic.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/YoLetterUsageDiagnostic.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/DiagnosticBeanPostProcessor.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/DiagnosticBeanPostProcessor.java index 9f1082f77df..d7b8080f0cd 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/DiagnosticBeanPostProcessor.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/DiagnosticBeanPostProcessor.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -44,7 +44,7 @@ public Object postProcessBeforeInitialization(Object bean, String beanName) { return bean; } - BSLDiagnostic diagnostic = (BSLDiagnostic) bean; + var diagnostic = (BSLDiagnostic) bean; var info = diagnosticInfos.get(diagnostic.getClass()); diagnostic.setInfo(info); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/DiagnosticInfosConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/DiagnosticInfosConfiguration.java index 51635f28a63..0639afcedbc 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/DiagnosticInfosConfiguration.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/DiagnosticInfosConfiguration.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/DiagnosticObjectProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/DiagnosticObjectProvider.java index 2370f746df0..b3c3ef02ba3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/DiagnosticObjectProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/DiagnosticObjectProvider.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/DiagnosticsConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/DiagnosticsConfiguration.java index 30ad22fe4c3..c0c3c0edbfb 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/DiagnosticsConfiguration.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/DiagnosticsConfiguration.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -31,12 +31,12 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCompatibilityMode; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope; -import com.github._1c_syntax.bsl.supconf.SupportConfiguration; +import com.github._1c_syntax.bsl.mdclasses.CF; +import com.github._1c_syntax.bsl.mdo.MD; +import com.github._1c_syntax.bsl.mdo.MDChild; import com.github._1c_syntax.bsl.support.CompatibilityMode; import com.github._1c_syntax.bsl.support.SupportVariant; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; -import com.github._1c_syntax.mdclasses.mdo.MDSubsystem; import lombok.RequiredArgsConstructor; import org.eclipse.lsp4j.jsonrpc.messages.Either; import org.springframework.beans.factory.annotation.Lookup; @@ -47,11 +47,9 @@ import java.util.Collection; import java.util.Collections; -import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import java.util.stream.Stream; @Configuration @RequiredArgsConstructor @@ -64,17 +62,16 @@ public abstract class DiagnosticsConfiguration { @Scope("prototype") public List diagnostics(DocumentContext documentContext) { - Collection diagnosticInfos = diagnosticInfos(); - - DiagnosticsOptions diagnosticsOptions = configuration.getDiagnosticsOptions(); + var diagnosticInfos = diagnosticInfos(); + var diagnosticsOptions = configuration.getDiagnosticsOptions(); if (needToComputeDiagnostics(documentContext, diagnosticsOptions)) { - FileType fileType = documentContext.getFileType(); - CompatibilityMode compatibilityMode = documentContext + var fileType = documentContext.getFileType(); + var compatibilityMode = documentContext .getServerContext() .getConfiguration() .getCompatibilityMode(); - ModuleType moduleType = documentContext.getModuleType(); + var moduleType = documentContext.getModuleType(); return diagnosticInfos.stream() .filter(diagnosticInfo -> isEnabled(diagnosticInfo, diagnosticsOptions)) @@ -110,9 +107,7 @@ private static boolean filterSubsystems(DocumentContext documentContext, Diagnos return true; } - var subsystemsNames = subsystemFlatList(mdoObject.get().getIncludedSubsystems()).stream() - .map(AbstractMDObjectBase::getName) - .collect(Collectors.toList()); + var subsystemsNames = getSubsystemNames(documentContext.getServerContext().getConfiguration(), mdoObject.get()); var include = subsystemsFilter.getInclude().isEmpty() || subsystemsNames.stream() @@ -133,16 +128,11 @@ private static boolean checkSupport(DocumentContext documentContext, Diagnostics } var configuredSkipSupport = diagnosticsOptions.getSkipSupport(); - if (configuredSkipSupport == SkipSupport.NEVER) { return true; } - Map supportVariants = documentContext.getSupportVariants(); - var moduleSupportVariant = supportVariants.values().stream() - .min(Comparator.naturalOrder()) - .orElse(SupportVariant.NONE); - + var moduleSupportVariant = documentContext.getSupportVariant(); if (moduleSupportVariant == SupportVariant.NONE) { return true; } @@ -155,7 +145,6 @@ private static boolean checkSupport(DocumentContext documentContext, Diagnostics } private boolean isEnabled(DiagnosticInfo diagnosticInfo, DiagnosticsOptions diagnosticsOptions) { - var mode = diagnosticsOptions.getMode(); if (mode == Mode.OFF) { return false; @@ -188,7 +177,7 @@ private boolean isEnabled(DiagnosticInfo diagnosticInfo, DiagnosticsOptions diag } private static boolean inScope(DiagnosticInfo diagnosticInfo, FileType fileType) { - DiagnosticScope scope = diagnosticInfo.getScope(); + var scope = diagnosticInfo.getScope(); DiagnosticScope fileScope; if (fileType == FileType.OS) { fileScope = DiagnosticScope.OS; @@ -204,13 +193,13 @@ private static boolean correctModuleType(DiagnosticInfo diagnosticInfo, ModuleTy return true; } - ModuleType[] diagnosticModules = diagnosticInfo.getModules(); + var diagnosticModules = diagnosticInfo.getModules(); if (diagnosticModules.length == 0) { return true; } - boolean contain = false; + var contain = false; for (ModuleType module : diagnosticModules) { if (module == moduletype) { contain = true; @@ -224,8 +213,7 @@ private static boolean passedCompatibilityMode( DiagnosticInfo diagnosticInfo, CompatibilityMode contextCompatibilityMode ) { - DiagnosticCompatibilityMode compatibilityMode = diagnosticInfo.getCompatibilityMode(); - + var compatibilityMode = diagnosticInfo.getCompatibilityMode(); if (compatibilityMode == DiagnosticCompatibilityMode.UNDEFINED) { return true; } @@ -233,11 +221,20 @@ private static boolean passedCompatibilityMode( return CompatibilityMode.compareTo(compatibilityMode.getCompatibilityMode(), contextCompatibilityMode) >= 0; } - // перенести в mdClasses - private static List subsystemFlatList(Collection subsystems) { - return subsystems.stream() - .flatMap(subsys -> Stream.concat(Stream.of(subsys), subsystemFlatList(subsys.getIncludedSubsystems()).stream())) + private static List getSubsystemNames(CF configuration, MD mdObject) { + var subsystemsNames = configuration + .includedSubsystems(mdObject, true) + .stream() + .map(MD::getName) .collect(Collectors.toList()); - } + // если объект не обнаружен, попробуем поискать его родителя + if (subsystemsNames.isEmpty() && mdObject instanceof MDChild child) { + var parent = configuration.findChild(child.getOwner()); + if (parent.isPresent()) { + subsystemsNames = getSubsystemNames(configuration, parent.get()); + } + } + return subsystemsNames; + } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/Disabled.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/Disabled.java index c257f1e6020..5f23ee1652f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/Disabled.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/Disabled.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/package-info.java index d0246d96a4f..4c8fbd13e06 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/infrastructure/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -19,7 +19,8 @@ * You should have received a copy of the GNU Lesser General Public * License along with BSL Language Server. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.diagnostics.infrastructure; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticCode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticCode.java index 7224ff6dccf..35437659f18 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticCode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticCode.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticCompatibilityMode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticCompatibilityMode.java index 91170e68363..ea39df08153 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticCompatibilityMode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticCompatibilityMode.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,6 +22,7 @@ package com.github._1c_syntax.bsl.languageserver.diagnostics.metadata; import com.github._1c_syntax.bsl.support.CompatibilityMode; +import lombok.Getter; public enum DiagnosticCompatibilityMode { UNDEFINED(0, 0), @@ -48,16 +49,15 @@ public enum DiagnosticCompatibilityMode { COMPATIBILITY_MODE_8_3_18(3, 18), COMPATIBILITY_MODE_8_3_19(3, 19), COMPATIBILITY_MODE_8_3_20(3, 20), - COMPATIBILITY_MODE_8_3_21(3, 21) - ; + COMPATIBILITY_MODE_8_3_21(3, 21), + COMPATIBILITY_MODE_8_3_22(3, 22), + COMPATIBILITY_MODE_8_3_23(3, 23), + COMPATIBILITY_MODE_8_3_24(3, 24); + @Getter private final CompatibilityMode compatibilityMode; DiagnosticCompatibilityMode(int minor, int version) { this.compatibilityMode = new CompatibilityMode(minor, version); } - - public CompatibilityMode getCompatibilityMode() { - return compatibilityMode; - } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java index f991100ff3b..c4c74d1866e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfo.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -27,11 +27,11 @@ import com.github._1c_syntax.bsl.languageserver.utils.Resources; import com.github._1c_syntax.bsl.types.ModuleType; import com.github._1c_syntax.utils.StringInterner; +import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import java.io.IOException; -import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; @@ -49,6 +49,7 @@ public class DiagnosticInfo { = createSeverityToLSPSeverityMap(); private static final Map diagnosticTagMap = createDiagnosticTagMap(); + @Getter private final Class diagnosticClass; private final LanguageServerConfiguration configuration; private final StringInterner stringInterner; @@ -71,17 +72,13 @@ public DiagnosticInfo( diagnosticParameters = DiagnosticParameterInfo.createDiagnosticParameters(this); } - public Class getDiagnosticClass() { - return diagnosticClass; - } - public DiagnosticCode getCode() { return diagnosticCode; } public String getDiagnosticCodeDescriptionHref() { var language = configuration.getLanguage(); - boolean useDevSite = configuration.isUseDevSite(); + var useDevSite = configuration.isUseDevSite(); var siteRoot = configuration.getSiteRoot(); var devSuffix = useDevSite ? "/dev" : ""; @@ -102,10 +99,10 @@ public String getName() { } public String getDescription() { - String langCode = configuration.getLanguage().getLanguageCode(); + var langCode = configuration.getLanguage().getLanguageCode(); - String resourceName = langCode + "/" + diagnosticCode.getStringValue() + ".md"; - InputStream descriptionStream = diagnosticClass.getResourceAsStream(resourceName); + var resourceName = langCode + "/" + diagnosticCode.getStringValue() + ".md"; + var descriptionStream = diagnosticClass.getResourceAsStream(resourceName); if (descriptionStream == null) { LOGGER.error("Can't find resource {}", resourceName); @@ -194,6 +191,14 @@ public Optional getParameter(String parameterName) { return diagnosticParameters.stream().filter(param -> param.getName().equals(parameterName)).findAny(); } + public boolean canLocateOnProject() { + return diagnosticMetadata.canLocateOnProject(); + } + + public double getExtraMinForComplexity() { + return diagnosticMetadata.extraMinForComplexity(); + } + public Map getDefaultConfiguration() { return diagnosticParameters.stream() .collect(Collectors.toMap(DiagnosticParameterInfo::getName, DiagnosticParameterInfo::getDefaultValue)); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticMetadata.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticMetadata.java index 5cc14694b33..6b2d2af2d0e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticMetadata.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticMetadata.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -39,19 +39,53 @@ @Primary @Scope("prototype") public @interface DiagnosticMetadata { + /** + * Тип диагностики + */ DiagnosticType type() default DiagnosticType.ERROR; + /** + * Серьезность замечания + */ DiagnosticSeverity severity() default DiagnosticSeverity.MINOR; + /** + * Область применения диагностики по диалекту языка (bsl или oscript) + */ DiagnosticScope scope() default DiagnosticScope.ALL; + /** + * Типы модулей, анализируемых диагностикой + */ ModuleType[] modules() default {}; + /** + * Время, необходимое для исправления замечания + */ int minutesToFix() default 0; + /** + * Признак включения диагностики в профиле по умолчанию + */ boolean activatedByDefault() default true; + /** + * Версия платформы 1С:Предприятие, с которой диагностика применяется + */ DiagnosticCompatibilityMode compatibilityMode() default DiagnosticCompatibilityMode.UNDEFINED; + /** + * Перечень меток (тегов) диагностики + */ DiagnosticTag[] tags() default {}; + + /** + * Замечания диагностики могут быть прикреплены на уровень анализируемого проекта (в частности в SonarQube) + */ + boolean canLocateOnProject() default false; + + /** + * Надбавка ко времени исправления замечания за повышенную сложность + */ + double extraMinForComplexity() default 0; } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticParameter.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticParameter.java index 3b983efa668..3ce93790ce2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticParameter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticParameter.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,7 +29,7 @@ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface DiagnosticParameter { - Class type(); + Class type(); String defaultValue() default ""; } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticParameterInfo.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticParameterInfo.java index 65305b7dfbd..93408f773c9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticParameterInfo.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticParameterInfo.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,42 +21,30 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics.metadata; +import lombok.Getter; + import java.lang.reflect.Field; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; +/** + * Описание параметров диагностики + */ +@Getter public final class DiagnosticParameterInfo { - private final Class type; + private final Class type; private final String name; private final String description; private final Object defaultValue; private DiagnosticParameterInfo(Field field, String description) { - DiagnosticParameter diagnosticParameter = field.getAnnotation(DiagnosticParameter.class); this.type = diagnosticParameter.type(); this.name = field.getName(); this.description = description; this.defaultValue = castDiagnosticParameterValue(diagnosticParameter.defaultValue()); - - } - - public Class getType() { - return type; - } - - public String getName() { - return name; - } - - public String getDescription() { - return this.description; - } - - public Object getDefaultValue() { - return this.defaultValue; } private Object castDiagnosticParameterValue(String valueToCast) { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticScope.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticScope.java index 6d698ebea8b..a07652d151a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticScope.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticScope.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticSeverity.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticSeverity.java index 8c92f3070c6..e63304f4448 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticSeverity.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticSeverity.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticTag.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticTag.java index cb334b4bf66..4be2b21b64c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticTag.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticTag.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,6 +21,11 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics.metadata; +import lombok.Getter; + +/** + * Варианты тегов диагностик + */ public enum DiagnosticTag { STANDARD("Нарушение стандартов 1С"), LOCKINOS("Не будет работать в другой ОС"), @@ -37,13 +42,11 @@ public enum DiagnosticTag { ERROR("Ошибочная конструкция"), LOCALIZE("Проблемы локализации"); + @Getter private final String description; DiagnosticTag(String descriptionRu) { this.description = descriptionRu; } - public String getDescription() { - return description; - } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticType.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticType.java index cef79e8c806..8e19b734de6 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticType.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticType.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/package-info.java index c5e6f4b9074..a2c77695afa 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/package-info.java index f4a133e61b2..a0d2806d59f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -19,7 +19,8 @@ * You should have received a copy of the GNU Lesser General Public * License along with BSL Language Server. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.diagnostics; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/typo/JLanguageToolPool.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/typo/JLanguageToolPool.java index cf97229fad1..cd5b4778ef4 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/typo/JLanguageToolPool.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/typo/JLanguageToolPool.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/documentlink/DiagnosticDescriptionDocumentLinkSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/documentlink/DiagnosticDescriptionDocumentLinkSupplier.java index cde1ab9b0f2..b2bd9f86368 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/documentlink/DiagnosticDescriptionDocumentLinkSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/documentlink/DiagnosticDescriptionDocumentLinkSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/documentlink/DocumentLinkSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/documentlink/DocumentLinkSupplier.java index 2c732ace0e0..1c63a207e49 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/documentlink/DocumentLinkSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/documentlink/DocumentLinkSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/documentlink/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/documentlink/package-info.java index 62c397b375c..efd8b6483ee 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/documentlink/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/documentlink/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,7 +23,8 @@ * Пакет предназначен для реализации различных ссылок на внешние источники информации ("documentLink"), * используемых {@link com.github._1c_syntax.bsl.languageserver.providers.DocumentLinkProvider}. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.documentlink; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/events/LanguageServerInitializeRequestReceivedEvent.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/events/LanguageServerInitializeRequestReceivedEvent.java index f67199ce418..22237c3d8d7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/events/LanguageServerInitializeRequestReceivedEvent.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/events/LanguageServerInitializeRequestReceivedEvent.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/events/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/events/package-info.java index 8f61c646d52..f6590d56a65 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/events/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/events/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,7 +22,8 @@ /** * События пакета com.github._1c_syntax.bsl.languageserver. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.events; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/AbstractCommentFoldingRangeSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/AbstractCommentFoldingRangeSupplier.java index 5461c2ef28d..f2d2fd8fc8f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/AbstractCommentFoldingRangeSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/AbstractCommentFoldingRangeSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/CodeBlockFoldingRangeSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/CodeBlockFoldingRangeSupplier.java index f4df0b83192..befbcde40fb 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/CodeBlockFoldingRangeSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/CodeBlockFoldingRangeSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,6 +24,7 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserBaseVisitor; +import edu.umd.cs.findbugs.annotations.Nullable; import lombok.Getter; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; @@ -31,7 +32,6 @@ import org.eclipse.lsp4j.FoldingRangeKind; import org.springframework.stereotype.Component; -import javax.annotation.CheckForNull; import java.util.ArrayList; import java.util.List; @@ -43,7 +43,7 @@ public class CodeBlockFoldingRangeSupplier implements FoldingRangeSupplier { @Override public List getFoldingRanges(DocumentContext documentContext) { - CodeBlockVisitor codeBlockVisitor = new CodeBlockVisitor(); + var codeBlockVisitor = new CodeBlockVisitor(); codeBlockVisitor.visitFile(documentContext.getAst()); return codeBlockVisitor.getRegionRanges(); } @@ -95,7 +95,7 @@ public ParseTree visitTryStatement(BSLParser.TryStatementContext ctx) { return super.visitTryStatement(ctx); } - private void addRegionRange(@CheckForNull TerminalNode start, @CheckForNull TerminalNode stop) { + private void addRegionRange(@Nullable TerminalNode start, @Nullable TerminalNode stop) { if (start == null || stop == null) { return; } @@ -104,7 +104,7 @@ private void addRegionRange(@CheckForNull TerminalNode start, @CheckForNull Term int stopLine = stop.getSymbol().getLine(); if (stopLine > startLine) { - FoldingRange foldingRange = new FoldingRange(startLine - 1, stopLine - 1); + var foldingRange = new FoldingRange(startLine - 1, stopLine - 1); foldingRange.setKind(FoldingRangeKind.Region); regionRanges.add(foldingRange); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/CommentFoldingRangeSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/CommentFoldingRangeSupplier.java index 57afef75cce..2eb1c073396 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/CommentFoldingRangeSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/CommentFoldingRangeSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/FoldingRangeSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/FoldingRangeSupplier.java index 15a5a3b10e8..61914c819be 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/FoldingRangeSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/FoldingRangeSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/PreprocIfFoldingRangeSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/PreprocIfFoldingRangeSupplier.java index 3e4ea42c813..bd7973a8c7c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/PreprocIfFoldingRangeSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/PreprocIfFoldingRangeSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryCommentFoldingRangeSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryCommentFoldingRangeSupplier.java index fce4800fa1a..56bba9e9a00 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryCommentFoldingRangeSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryCommentFoldingRangeSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryPackageFoldingRangeSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryPackageFoldingRangeSupplier.java index fc027cbc872..b9c35112e70 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryPackageFoldingRangeSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryPackageFoldingRangeSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/RegionFoldingRangeSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/RegionFoldingRangeSupplier.java index 1772aa7d1b3..aca4bd57873 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/RegionFoldingRangeSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/RegionFoldingRangeSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/UseFoldingRangeSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/UseFoldingRangeSupplier.java index 2ded0503f88..181baf0267a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/UseFoldingRangeSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/UseFoldingRangeSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/package-info.java index 71f4981a421..3f60127ef72 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/folding/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,7 +23,8 @@ * Пакет предназначен для реализации различных видов сворачивания ("folding"), * используемых {@link com.github._1c_syntax.bsl.languageserver.providers.FoldingRangeProvider}. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.folding; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/AnnotationParamSymbolMarkupContentBuilder.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/AnnotationParamSymbolMarkupContentBuilder.java new file mode 100644 index 00000000000..793dcf8e2f3 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/AnnotationParamSymbolMarkupContentBuilder.java @@ -0,0 +1,79 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.hover; + +import com.github._1c_syntax.bsl.languageserver.context.symbol.AnnotationParamSymbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.AnnotationSymbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.ParameterDefinition; +import lombok.RequiredArgsConstructor; +import org.eclipse.lsp4j.MarkupContent; +import org.eclipse.lsp4j.MarkupKind; +import org.eclipse.lsp4j.SymbolKind; +import org.springframework.stereotype.Component; + +import java.util.Optional; +import java.util.StringJoiner; + +/** + * Построитель контента для всплывающего окна для {@link AnnotationSymbol}. + */ +@Component +@RequiredArgsConstructor +public class AnnotationParamSymbolMarkupContentBuilder implements MarkupContentBuilder { + + private final DescriptionFormatter descriptionFormatter; + + @Override + public MarkupContent getContent(AnnotationParamSymbol symbol) { + var maybeMethodSymbol = symbol.getParent(); + if (maybeMethodSymbol.filter(MethodSymbol.class::isInstance).isEmpty()) { + return new MarkupContent(MarkupKind.MARKDOWN, ""); + } + + var markupBuilder = new StringJoiner("\n"); + var methodSymbol = (MethodSymbol) maybeMethodSymbol.get(); + var maybeParameterDefinition = methodSymbol.getParameters().stream() + .filter(parameter -> parameter.getName().equalsIgnoreCase(symbol.getName())) + .findFirst(); + + if (maybeParameterDefinition.isEmpty()) { + return new MarkupContent(MarkupKind.MARKDOWN, ""); + } + + var parameterDefinition = maybeParameterDefinition.get(); + + // описание параметра аннотации + String parameter = descriptionFormatter.parameterToString(parameterDefinition); + descriptionFormatter.addSectionIfNotEmpty(markupBuilder, parameter); + + String content = markupBuilder.toString(); + + return new MarkupContent(MarkupKind.MARKDOWN, content); + } + + @Override + public SymbolKind getSymbolKind() { + return SymbolKind.TypeParameter; + } + +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/AnnotationSymbolMarkupContentBuilder.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/AnnotationSymbolMarkupContentBuilder.java new file mode 100644 index 00000000000..757b29dc119 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/AnnotationSymbolMarkupContentBuilder.java @@ -0,0 +1,94 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.hover; + +import com.github._1c_syntax.bsl.languageserver.context.symbol.AnnotationSymbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import lombok.RequiredArgsConstructor; +import org.eclipse.lsp4j.MarkupContent; +import org.eclipse.lsp4j.MarkupKind; +import org.eclipse.lsp4j.SymbolKind; +import org.springframework.stereotype.Component; + +import java.util.StringJoiner; + +/** + * Построитель контента для всплывающего окна для {@link AnnotationSymbol}. + */ +@Component +@RequiredArgsConstructor +public class AnnotationSymbolMarkupContentBuilder implements MarkupContentBuilder { + + private final DescriptionFormatter descriptionFormatter; + + @Override + public MarkupContent getContent(AnnotationSymbol symbol) { + var maybeMethodSymbol = symbol.getParent(); + if (maybeMethodSymbol.filter(MethodSymbol.class::isInstance).isEmpty()) { + return new MarkupContent(MarkupKind.MARKDOWN, ""); + } + + var markupBuilder = new StringJoiner("\n"); + var methodSymbol = (MethodSymbol) maybeMethodSymbol.get(); + + // сигнатура + // местоположение метода + // описание метода + // параметры + // примеры + // варианты вызова + + // сигнатура + String signature = descriptionFormatter.getSignature(symbol, methodSymbol); + descriptionFormatter.addSectionIfNotEmpty(markupBuilder, signature); + + // местоположение метода + String methodLocation = descriptionFormatter.getLocation(methodSymbol); + descriptionFormatter.addSectionIfNotEmpty(markupBuilder, methodLocation); + + // описание метода + String purposeSection = descriptionFormatter.getPurposeSection(methodSymbol); + descriptionFormatter.addSectionIfNotEmpty(markupBuilder, purposeSection); + + // параметры + String parametersSection = descriptionFormatter.getParametersSection(methodSymbol); + descriptionFormatter.addSectionIfNotEmpty(markupBuilder, parametersSection); + + // примеры + String examplesSection = descriptionFormatter.getExamplesSection(methodSymbol); + descriptionFormatter.addSectionIfNotEmpty(markupBuilder, examplesSection); + + // варианты вызова + String callOptionsSection = descriptionFormatter.getCallOptionsSection(methodSymbol); + descriptionFormatter.addSectionIfNotEmpty(markupBuilder, callOptionsSection); + + String content = markupBuilder.toString(); + + return new MarkupContent(MarkupKind.MARKDOWN, content); + } + + @Override + public SymbolKind getSymbolKind() { + return SymbolKind.Interface; + } + +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatter.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatter.java new file mode 100644 index 00000000000..7018cf05778 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatter.java @@ -0,0 +1,370 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.hover; + +import com.github._1c_syntax.bsl.languageserver.context.symbol.AnnotationSymbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.ParameterDefinition; +import com.github._1c_syntax.bsl.languageserver.context.symbol.VariableSymbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.annotations.Annotation; +import com.github._1c_syntax.bsl.languageserver.context.symbol.description.MethodDescription; +import com.github._1c_syntax.bsl.languageserver.context.symbol.description.ParameterDescription; +import com.github._1c_syntax.bsl.languageserver.context.symbol.description.TypeDescription; +import com.github._1c_syntax.bsl.languageserver.utils.MdoRefBuilder; +import com.github._1c_syntax.bsl.languageserver.utils.Resources; +import lombok.RequiredArgsConstructor; +import org.eclipse.lsp4j.SymbolKind; +import org.springframework.stereotype.Component; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.StringJoiner; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Component +@RequiredArgsConstructor +public class DescriptionFormatter { + + private static final String PROCEDURE_KEY = "procedure"; + private static final String FUNCTION_KEY = "function"; + private static final String ANNOTATION_KEY = "annotation"; + private static final String EXPORT_KEY = "export"; + private static final String VAL_KEY = "val"; + private static final String VARIABLE_KEY = "var"; + private static final String PARAMETERS_KEY = "parameters"; + private static final String RETURNED_VALUE_KEY = "returnedValue"; + private static final String EXAMPLES_KEY = "examples"; + private static final String CALL_OPTIONS_KEY = "callOptions"; + private static final String PARAMETER_TEMPLATE = "* **%s**: %s"; + + private final Resources resources; + + public void addSectionIfNotEmpty(StringJoiner markupBuilder, String newContent) { + if (!newContent.isEmpty()) { + markupBuilder.add(newContent); + markupBuilder.add(""); + markupBuilder.add("---"); + } + } + + public String getPurposeSection(MethodSymbol methodSymbol) { + return methodSymbol.getDescription() + .map(MethodDescription::getPurposeDescription) + .orElse(""); + } + + public String getParametersSection(MethodSymbol methodSymbol) { + var result = new StringJoiner(" \n"); // два пробела + methodSymbol.getParameters().forEach(parameterDefinition -> + result.add(parameterToString(parameterDefinition)) + ); + + var parameters = result.toString(); + + if (!parameters.isBlank()) { + var parametersSection = new StringJoiner("\n"); + String header = "**" + getResourceString(PARAMETERS_KEY) + ":**"; + parametersSection.add(header); + parametersSection.add(""); + parametersSection.add(parameters); + return parametersSection.toString(); + } + + return ""; + } + + public String getReturnedValueSection(MethodSymbol methodSymbol) { + var result = new StringJoiner(" \n"); // два пробела + methodSymbol.getDescription().ifPresent((MethodDescription methodDescription) -> { + Map typesMap = typesToMap(methodDescription.getReturnedValue(), 0); + result.add(typesMapToString(typesMap, 1)); + }); + + var returnedValue = result.toString(); + + if (!returnedValue.isEmpty()) { + returnedValue = "**" + getResourceString(RETURNED_VALUE_KEY) + ":**\n\n" + returnedValue; + } + + return returnedValue; + } + + public String getExamplesSection(MethodSymbol methodSymbol) { + var examples = methodSymbol.getDescription() + .map(MethodDescription::getExamples) + .orElseGet(Collections::emptyList); + return getSectionWithCodeFences(examples, EXAMPLES_KEY); + } + + public String getCallOptionsSection(MethodSymbol methodSymbol) { + var callOptions = methodSymbol.getDescription() + .map(MethodDescription::getCallOptions) + .orElseGet(Collections::emptyList); + return getSectionWithCodeFences(callOptions, CALL_OPTIONS_KEY); + } + + public String getSectionWithCodeFences(Collection codeBlocks, String resourceKey) { + String codeFences = codeBlocks + .stream() + .map(codeBlock -> "```bsl\n" + codeBlock + "\n```") + .collect(Collectors.joining("\n")); + + if (!codeFences.isEmpty()) { + codeFences = "**" + getResourceString(resourceKey) + ":**\n\n" + codeFences; + } + + return codeFences; + } + + public String getLocation(MethodSymbol symbol) { + var documentContext = symbol.getOwner(); + var startPosition = symbol.getSelectionRange().getStart(); + String mdoRef = MdoRefBuilder.getMdoRef(documentContext); + + return String.format( + "[%s](%s#%d)", + mdoRef, + documentContext.getUri(), + startPosition.getLine() + 1 + ); + } + + public String getLocation(VariableSymbol symbol) { + var documentContext = symbol.getOwner(); + var startPosition = symbol.getSelectionRange().getStart(); + String mdoRef = MdoRefBuilder.getMdoRef(documentContext); + + String parentPostfix = symbol.getRootParent(SymbolKind.Method) + .map(sourceDefinedSymbol -> "." + sourceDefinedSymbol.getName()) + .orElse(""); + mdoRef += parentPostfix; + + return String.format( + "[%s](%s#%d)", + mdoRef, + documentContext.getUri(), + startPosition.getLine() + 1 + ); + } + + public String getSignature(MethodSymbol methodSymbol) { + var signatureTemplate = "```bsl\n%s %s(%s)%s%s\n```"; + + String methodKind; + if (methodSymbol.isFunction()) { + methodKind = getResourceString(FUNCTION_KEY); + } else { + methodKind = getResourceString(PROCEDURE_KEY); + } + String methodName = methodSymbol.getName(); + + var parameters = getParametersSignatureDescription(methodSymbol); + var returnedValueType = getReturnedValueTypeDescriptionPart(methodSymbol); + String export = methodSymbol.isExport() ? (" " + getResourceString(EXPORT_KEY)) : ""; + + return String.format( + signatureTemplate, + methodKind, + methodName, + parameters, + export, + returnedValueType + ); + } + + public String getSignature(AnnotationSymbol symbol, MethodSymbol methodSymbol) { + var signatureTemplate = "```bsl\n%s &%s(%s)\n```"; + + var annotationKind = getResourceString(ANNOTATION_KEY); + var annotationName = symbol.getName(); + + var parameters = getParametersSignatureDescription(methodSymbol); + + return String.format( + signatureTemplate, + annotationKind, + annotationName, + parameters + ); + } + + public String getSignature(VariableSymbol symbol) { + var signatureTemplate = "```bsl\n%s %s%s\n```"; + + var varKey = getResourceString(VARIABLE_KEY); + var name = symbol.getName(); + var export = symbol.isExport() ? (" " + getResourceString(EXPORT_KEY)) : ""; + + return String.format( + signatureTemplate, + varKey, + name, + export + ); + } + + public String getParametersSignatureDescription(MethodSymbol methodSymbol) { + var parametersDescription = new StringJoiner(", "); + methodSymbol.getParameters().forEach((ParameterDefinition parameterDefinition) -> { + StringBuilder parameter = new StringBuilder(); + parameter.append(getAnnotationsDescriptionPart(parameterDefinition)); + var parameterName = parameterDefinition.getName(); + + if (parameterDefinition.isByValue()) { + parameter.append(getResourceString(VAL_KEY)).append(" "); + } + parameter.append(parameterName); + + var parameterTypes = parameterDefinition.getDescription() + .map(ParameterDescription::getTypes) + .map(DescriptionFormatter::getTypes) + .orElse(""); + + if (!parameterTypes.isEmpty()) { + parameter.append(": ").append(parameterTypes); + } + + if (parameterDefinition.isOptional()) { + parameter.append(" = "); + parameter.append(parameterDefinition.getDefaultValue().value()); + } + + parametersDescription.add(parameter.toString()); + }); + + return parametersDescription.toString(); + } + + private static String getAnnotationsDescriptionPart(ParameterDefinition parameterDefinition) { + var description = new StringBuilder(); + for (Annotation annotation : parameterDefinition.getAnnotations()) { + description.append("&").append(annotation.getName()).append(" "); + } + + return description.toString(); + } + + private static String getReturnedValueTypeDescriptionPart(MethodSymbol methodSymbol) { + String returnedValueType = methodSymbol.getDescription() + .map(MethodDescription::getReturnedValue) + .map(DescriptionFormatter::getTypes) + .orElse(""); + if (!returnedValueType.isEmpty()) { + returnedValueType = ": " + returnedValueType; + } + return returnedValueType; + } + + private static String getTypes(List typeDescriptions) { + return typeDescriptions.stream() + .map(TypeDescription::getName) + .flatMap(parameterType -> Stream.of(parameterType.split(","))) + .map(String::trim) + .collect(Collectors.joining(" | ")); + } + + public String parameterToString(ParameterDescription parameterDescription, int level) { + var result = new StringJoiner(" \n"); // два пробела + Map typesMap = typesToMap(parameterDescription.getTypes(), level); + var parameterTemplate = " ".repeat(level) + PARAMETER_TEMPLATE; + + if (typesMap.size() == 1) { + result.add(String.format(parameterTemplate, + parameterDescription.getName(), + typesMapToString(typesMap, 0))); + } else { + result.add(String.format(parameterTemplate, parameterDescription.getName(), "")); + result.add(typesMapToString(typesMap, level + 1)); + } + return result.toString(); + } + + public String parameterToString(ParameterDefinition parameterDefinition) { + var level = 0; + var parameterDescription = parameterDefinition.getDescription(); + if (parameterDescription.isPresent()) { + return parameterToString(parameterDescription.get(), level); + } + + return String.format( + PARAMETER_TEMPLATE, + parameterDefinition.getName(), + "" + ); + } + + private Map typesToMap(List parameterTypes, int level) { + Map types = new HashMap<>(); + + parameterTypes.forEach((TypeDescription type) -> { + var typeDescription = typeToString(type, level); + String typeName; + if (type.isHyperlink()) { + typeName = String.format("[%s](%s)", type.getName(), type.getLink()); + } else { + typeName = String.format("`%s`", type.getName()); + } + + types.merge(typeDescription, typeName, (oldValue, newValue) -> String.format("%s | %s", oldValue, newValue)); + }); + return types; + } + + private static String typesMapToString(Map types, int level) { + var result = new StringJoiner(" \n"); // два пробела + var indent = "  ".repeat(level); + types.forEach((String key, String value) -> { + if (key.isBlank()) { + result.add(value); + } else { + result.add(String.format("%s%s %s", indent, value, key)); + } + }); + return result.toString(); + } + + private String typeToString(TypeDescription type, int level) { + var result = new StringJoiner(" \n"); // два пробела + var description = type.getDescription().replace("\n", "
" + "  ".repeat(level + 1)); + + if (!description.isBlank()) { + description = "- " + description; + } + if (!type.getParameters().isEmpty()) { + description += ":"; + } + + result.add(description); + type.getParameters().forEach((ParameterDescription parameter) -> + result.add(parameterToString(parameter, level + 1))); + return result.toString(); + } + + private String getResourceString(String key) { + return resources.getResourceString(getClass(), key); + } + +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/MarkupContentBuilder.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/MarkupContentBuilder.java index cc8855b645b..273c2df826f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/MarkupContentBuilder.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/MarkupContentBuilder.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/MarkupContentBuilderConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/MarkupContentBuilderConfiguration.java index 6af3582aaba..a435905296f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/MarkupContentBuilderConfiguration.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/MarkupContentBuilderConfiguration.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/MethodSymbolMarkupContentBuilder.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/MethodSymbolMarkupContentBuilder.java index 366b22347a1..988f18d513c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/MethodSymbolMarkupContentBuilder.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/MethodSymbolMarkupContentBuilder.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,27 +21,14 @@ */ package com.github._1c_syntax.bsl.languageserver.hover; -import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; -import com.github._1c_syntax.bsl.languageserver.context.symbol.ParameterDefinition; -import com.github._1c_syntax.bsl.languageserver.context.symbol.description.MethodDescription; -import com.github._1c_syntax.bsl.languageserver.context.symbol.description.ParameterDescription; -import com.github._1c_syntax.bsl.languageserver.context.symbol.description.TypeDescription; -import com.github._1c_syntax.bsl.languageserver.utils.MdoRefBuilder; -import com.github._1c_syntax.bsl.languageserver.utils.Resources; import lombok.RequiredArgsConstructor; import org.eclipse.lsp4j.MarkupContent; import org.eclipse.lsp4j.MarkupKind; import org.eclipse.lsp4j.SymbolKind; import org.springframework.stereotype.Component; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; import java.util.StringJoiner; -import java.util.stream.Collectors; -import java.util.stream.Stream; /** * Построитель контента для всплывающего окна для {@link MethodSymbol}. @@ -60,7 +47,7 @@ public class MethodSymbolMarkupContentBuilder implements MarkupContentBuilder { - if (parameterDefinition.getDescription().isPresent()) { - result.add(parameterToString(parameterDefinition.getDescription().get(), level)); - } else { - result.add(parameterToString(parameterDefinition)); - } - } - ); - - var parameters = result.toString(); - - if (!parameters.isBlank()) { - var parametersSection = new StringJoiner("\n"); - String header = "**" + getResourceString(PARAMETERS_KEY) + ":**"; - parametersSection.add(header); - parametersSection.add(""); - parametersSection.add(parameters); - return parametersSection.toString(); - } - - return ""; - } - - private String getReturnedValueSection(MethodSymbol methodSymbol) { - var result = new StringJoiner(" \n"); // два пробела - methodSymbol.getDescription().ifPresent((MethodDescription methodDescription) -> { - Map typesMap = typesToMap(methodDescription.getReturnedValue(), 0); - result.add(typesMapToString(typesMap, 1)); - }); - - var returnedValue = result.toString(); - - if (!returnedValue.isEmpty()) { - returnedValue = "**" + getResourceString(RETURNED_VALUE_KEY) + ":**\n\n" + returnedValue; - } - - return returnedValue; - } - - private String getExamplesSection(MethodSymbol methodSymbol) { - var examples = methodSymbol.getDescription() - .map(MethodDescription::getExamples) - .orElseGet(Collections::emptyList); - return getSectionWithCodeFences(examples, EXAMPLES_KEY); - } - - private String getCallOptionsSection(MethodSymbol methodSymbol) { - var callOptions = methodSymbol.getDescription() - .map(MethodDescription::getCallOptions) - .orElseGet(Collections::emptyList); - return getSectionWithCodeFences(callOptions, CALL_OPTIONS_KEY); - } - - private String getSectionWithCodeFences(List codeBlocks, String resourceKey) { - String codeFences = codeBlocks - .stream() - .map(codeBlock -> "```bsl\n" + codeBlock + "\n```") - .collect(Collectors.joining("\n")); - - if (!codeFences.isEmpty()) { - codeFences = "**" + getResourceString(resourceKey) + ":**\n\n" + codeFences; - } - - return codeFences; - } - - private static String getLocation(MethodSymbol symbol) { - var documentContext = symbol.getOwner(); - var startPosition = symbol.getSelectionRange().getStart(); - String mdoRef = MdoRefBuilder.getMdoRef(documentContext); - - return String.format( - "[%s](%s#%d)", - mdoRef, - documentContext.getUri(), - startPosition.getLine() + 1 - ); - } - - private String getSignature(MethodSymbol methodSymbol) { - String signatureTemplate = "```bsl\n%s %s(%s)%s%s\n```"; - - String methodKind; - if (methodSymbol.isFunction()) { - methodKind = getResourceString(FUNCTION_KEY); - } else { - methodKind = getResourceString(PROCEDURE_KEY); - } - String methodName = methodSymbol.getName(); - - var parametersDescription = new StringJoiner(", "); - methodSymbol.getParameters().forEach((ParameterDefinition parameterDefinition) -> { - var parameter = ""; - var parameterName = parameterDefinition.getName(); - - if (parameterDefinition.isByValue()) { - parameter = parameter + getResourceString(VAL_KEY) + " "; - } - parameter += parameterName; - - var parameterTypes = parameterDefinition.getDescription() - .map(ParameterDescription::getTypes) - .map(MethodSymbolMarkupContentBuilder::getTypes) - .orElse(""); - - if (!parameterTypes.isEmpty()) { - parameter += ": " + parameterTypes; - } - - if (parameterDefinition.isOptional()) { - parameter += " = "; - parameter += parameterDefinition.getDefaultValue().getValue(); - } - - parametersDescription.add(parameter); - }); - var parameters = parametersDescription.toString(); - - String returnedValueType = methodSymbol.getDescription() - .map(MethodDescription::getReturnedValue) - .map(MethodSymbolMarkupContentBuilder::getTypes) - .orElse(""); - if (!returnedValueType.isEmpty()) { - returnedValueType = ": " + returnedValueType; - } - - String export = methodSymbol.isExport() ? (" " + getResourceString(EXPORT_KEY)) : ""; - - return String.format( - signatureTemplate, - methodKind, - methodName, - parameters, - export, - returnedValueType - ); - } - - private static String getTypes(List typeDescriptions) { - return typeDescriptions.stream() - .map(TypeDescription::getName) - .flatMap(parameterType -> Stream.of(parameterType.split(","))) - .map(String::trim) - .collect(Collectors.joining(" | ")); - } - - private String getResourceString(String key) { - return Resources.getResourceString(configuration.getLanguage(), getClass(), key); - } - - private static String parameterToString(ParameterDescription parameter, int level) { - var result = new StringJoiner(" \n"); // два пробела - Map typesMap = typesToMap(parameter.getTypes(), level); - var parameterTemplate = " ".repeat(level) + PARAMETER_TEMPLATE; - - if (typesMap.size() == 1) { - result.add(String.format(parameterTemplate, - parameter.getName(), - typesMapToString(typesMap, 0))); - } else { - result.add(String.format(parameterTemplate, parameter.getName(), "")); - result.add(typesMapToString(typesMap, level + 1)); - } - return result.toString(); - } - - private static String parameterToString(ParameterDefinition parameterDefinition) { - return String.format(PARAMETER_TEMPLATE, parameterDefinition.getName(), ""); - } - - private static Map typesToMap(List parameterTypes, int level) { - Map types = new HashMap<>(); - - parameterTypes.forEach((TypeDescription type) -> { - var typeDescription = typeToString(type, level); - String typeName; - if (type.isHyperlink()) { - typeName = String.format("[%s](%s)", type.getName(), type.getLink()); - } else { - typeName = String.format("`%s`", type.getName()); - } - - types.merge(typeDescription, typeName, (oldValue, newValue) -> String.format("%s | %s", oldValue, newValue)); - }); - return types; - } - - private static String typesMapToString(Map types, int level) { - var result = new StringJoiner(" \n"); // два пробела - var indent = "  ".repeat(level); - types.forEach((String key, String value) -> { - if (key.isBlank()) { - result.add(value); - } else { - result.add(String.format("%s%s %s", indent, value, key)); - } - }); - return result.toString(); - } - - private static String typeToString(TypeDescription type, int level) { - var result = new StringJoiner(" \n"); // два пробела - var description = type.getDescription().replace("\n", "
" + "  ".repeat(level + 1)); - - if (!description.isBlank()) { - description = "- " + description; - } - if (!type.getParameters().isEmpty()) { - description += ":"; - } - - result.add(description); - type.getParameters().forEach((ParameterDescription parameter) -> - result.add(parameterToString(parameter, level + 1))); - return result.toString(); - } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/VariableSymbolMarkupContentBuilder.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/VariableSymbolMarkupContentBuilder.java index 7a207053bf4..f9fb1662929 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/VariableSymbolMarkupContentBuilder.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/VariableSymbolMarkupContentBuilder.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,8 +24,6 @@ import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.bsl.languageserver.context.symbol.VariableSymbol; import com.github._1c_syntax.bsl.languageserver.context.symbol.variable.VariableDescription; -import com.github._1c_syntax.bsl.languageserver.utils.MdoRefBuilder; -import com.github._1c_syntax.bsl.languageserver.utils.Resources; import lombok.RequiredArgsConstructor; import org.eclipse.lsp4j.MarkupContent; import org.eclipse.lsp4j.MarkupKind; @@ -42,6 +40,7 @@ public class VariableSymbolMarkupContentBuilder implements MarkupContentBuilder< private static final String EXPORT_KEY = "export"; private final LanguageServerConfiguration configuration; + private final DescriptionFormatter descriptionFormatter; @Override public MarkupContent getContent(VariableSymbol symbol) { @@ -52,22 +51,22 @@ public MarkupContent getContent(VariableSymbol symbol) { // описание переменной // сигнатура - String signature = getSignature(symbol); - addSectionIfNotEmpty(markupBuilder, signature); + String signature = descriptionFormatter.getSignature(symbol); + descriptionFormatter.addSectionIfNotEmpty(markupBuilder, signature); // местоположение переменной - String location = getLocation(symbol); - addSectionIfNotEmpty(markupBuilder, location); + String location = descriptionFormatter.getLocation(symbol); + descriptionFormatter.addSectionIfNotEmpty(markupBuilder, location); // описание переменной symbol.getDescription() .map(VariableDescription::getPurposeDescription) - .ifPresent(description -> addSectionIfNotEmpty(markupBuilder, description)); + .ifPresent(description -> descriptionFormatter.addSectionIfNotEmpty(markupBuilder, description)); symbol.getDescription() .flatMap(VariableDescription::getTrailingDescription) .map(VariableDescription::getPurposeDescription) - .ifPresent(trailingDescription -> addSectionIfNotEmpty(markupBuilder, trailingDescription)); + .ifPresent(trailingDescription -> descriptionFormatter.addSectionIfNotEmpty(markupBuilder, trailingDescription)); String content = markupBuilder.toString(); @@ -79,48 +78,4 @@ public SymbolKind getSymbolKind() { return SymbolKind.Variable; } - private String getSignature(VariableSymbol symbol) { - String signatureTemplate = "```bsl\n%s %s%s\n```"; - - String varKey = getResourceString(VARIABLE_KEY); - String name = symbol.getName(); - String export = symbol.isExport() ? (" " + getResourceString(EXPORT_KEY)) : ""; - - return String.format( - signatureTemplate, - varKey, - name, - export - ); - } - - private static String getLocation(VariableSymbol symbol) { - var documentContext = symbol.getOwner(); - var startPosition = symbol.getSelectionRange().getStart(); - String mdoRef = MdoRefBuilder.getMdoRef(symbol.getOwner()); - - String parentPostfix = symbol.getRootParent(SymbolKind.Method) - .map(sourceDefinedSymbol -> "." + sourceDefinedSymbol.getName()) - .orElse(""); - mdoRef += parentPostfix; - - return String.format( - "[%s](%s#%d)", - mdoRef, - documentContext.getUri(), - startPosition.getLine() + 1 - ); - } - - private static void addSectionIfNotEmpty(StringJoiner markupBuilder, String newContent) { - if (!newContent.isEmpty()) { - markupBuilder.add(newContent); - markupBuilder.add(""); - markupBuilder.add("---"); - } - } - - private String getResourceString(String key) { - return Resources.getResourceString(configuration.getLanguage(), getClass(), key); - } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/package-info.java index a2c7583cfcb..8a9b1141f2c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/hover/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,7 +22,8 @@ /** * Формирование всплывающего окна. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.hover; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/CacheConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/CacheConfiguration.java new file mode 100644 index 00000000000..fe4340dae3d --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/CacheConfiguration.java @@ -0,0 +1,33 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.infrastructure; + +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Configuration; + +/** + * Spring-конфигурация кэширования. + */ +@Configuration +@EnableCaching +public class CacheConfiguration { +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/LanguageClientAwareAppender.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/LanguageClientAwareAppender.java new file mode 100644 index 00000000000..cc1cb3f51f1 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/LanguageClientAwareAppender.java @@ -0,0 +1,103 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.infrastructure; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.ConsoleAppender; +import com.github._1c_syntax.bsl.languageserver.LanguageClientHolder; +import jakarta.annotation.Nullable; +import lombok.Setter; +import org.eclipse.lsp4j.MessageParams; +import org.eclipse.lsp4j.MessageType; +import org.springframework.beans.factory.annotation.Autowired; + +import java.io.IOException; +import java.util.Map; + +/** + * Расширение штатного {@link ConsoleAppender}, выводящего сообщения + * в {@link org.eclipse.lsp4j.services.LanguageClient}, если он подключен, + * или в штатные потоки вывода в обратном случае. + */ +public class LanguageClientAwareAppender + extends ConsoleAppender { + + /** + * Singletone-like хранилище проинициализированного инфраструктурой Logback аппендера + * для последующего возврата его через {@link LogbackConfiguration#languageClientAwareAppender()}. + */ + protected static LanguageClientAwareAppender INSTANCE; + + private static final Map loggingLevels = Map.of( + Level.TRACE, MessageType.Log, + Level.DEBUG, MessageType.Log, + Level.ERROR, MessageType.Error, + Level.INFO, MessageType.Info, + Level.WARN, MessageType.Warning + ); + + /** + * Хранилище возможно подключенного LanguageClient. + */ + @Nullable + @Setter(onMethod_ = {@Autowired}) + private LanguageClientHolder clientHolder; + + /** + * Конструктор по умолчанию. + *

+ * Сохраняет сконструированный объект в переменную {@link LanguageClientAwareAppender#INSTANCE}. + */ + public LanguageClientAwareAppender() { + super(); + // hacky hack + INSTANCE = this; + } + + /** + * Общий метод вывода информации, проверяющий наличие подключенного LanguageClient. + * + * @param event Логируемое событие + * @throws IOException Выбрасывает исключение в случае ошибок записи в стандартные потоки вывода. + */ + @Override + protected void writeOut(ILoggingEvent event) throws IOException { + if (clientHolder != null && clientHolder.isConnected()) { + var languageClient = clientHolder.getClient().orElseThrow(); + + var messageType = loggingLevels.getOrDefault(event.getLevel(), MessageType.Log); + String message = "[%s - %s] [%s] [%s]: %s".formatted( + event.getLevel(), + event.getInstant(), + event.getThreadName(), + event.getLoggerName(), + event.getFormattedMessage() + ); + var params = new MessageParams(messageType, message); + languageClient.logMessage(params); + + return; + } + super.writeOut(event); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionParseTreeRewriter.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/LogbackConfiguration.java similarity index 56% rename from src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionParseTreeRewriter.java rename to src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/LogbackConfiguration.java index bf5541799e4..ee2dfc5c524 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionParseTreeRewriter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/LogbackConfiguration.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -19,26 +19,22 @@ * 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.utils.expressiontree; - -import com.github._1c_syntax.bsl.parser.BSLParser; +package com.github._1c_syntax.bsl.languageserver.infrastructure; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; /** - * Преобразователь выражения в дерево вычисления. + * Spring-конфигурация для настройки logback. */ -public final class ExpressionParseTreeRewriter { - - private ExpressionParseTreeRewriter(){ - } +@Configuration +public class LogbackConfiguration { /** - * @return результирующее выражение в виде дерева вычисления операций + * @return Настроенный аппендер сообщений в LanguageClient. */ - public static BslExpression buildExpressionTree(BSLParser.ExpressionContext expression) { - var visitor = new ExpressionTreeBuildingVisitor(); - visitor.visitExpression(expression); - return visitor.getExpressionTree(); + @Bean + public LanguageClientAwareAppender languageClientAwareAppender() { + return LanguageClientAwareAppender.INSTANCE; } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/SchedulingConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/SchedulingConfiguration.java index 654954f1560..dc429e6e759 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/SchedulingConfiguration.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/SchedulingConfiguration.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/UtilsConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/UtilsConfiguration.java index 6b7a52e8946..f5c95bfbe59 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/UtilsConfiguration.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/UtilsConfiguration.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,19 +22,23 @@ package com.github._1c_syntax.bsl.languageserver.infrastructure; import com.github._1c_syntax.utils.StringInterner; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Role; /** * Конфигурация бинов из 1c-syntax/utils. */ @Configuration +@Role(BeanDefinition.ROLE_INFRASTRUCTURE) public class UtilsConfiguration { /** * @return Настроенный объект интернирователя строк. */ @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) public StringInterner stringInterner() { return new StringInterner(); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/package-info.java index ae08f421ea3..5c231441dbc 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/infrastructure/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,7 +22,8 @@ /** * Spring-специфичные классы для настройки внутренней инфраструктуры уровня приложения. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.infrastructure; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/AbstractComplexityInlayHintSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/AbstractComplexityInlayHintSupplier.java new file mode 100644 index 00000000000..92b44793754 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/AbstractComplexityInlayHintSupplier.java @@ -0,0 +1,105 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.inlayhints; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.computer.ComplexitySecondaryLocation; +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import org.eclipse.lsp4j.InlayHint; +import org.eclipse.lsp4j.InlayHintKind; +import org.eclipse.lsp4j.InlayHintParams; + +import java.net.URI; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Абстрактный поставщик подсказок о сложности методов. + *

+ * По умолчанию подсказки отключены. Для включения нужно вызвать метод {@link #toggleHints(URI, String)}. + */ +public abstract class AbstractComplexityInlayHintSupplier implements InlayHintSupplier { + + private final Map> enabledMethods = new HashMap<>(); + + /** + * Получение подсказок о местах увеличения сложности метода. + *

+ * + * {@inheritDoc} + */ + @Override + public List getInlayHints(DocumentContext documentContext, InlayHintParams params) { + var enabledMethodsInFile = enabledMethods.getOrDefault(documentContext.getUri(), Collections.emptySet()); + var cognitiveComplexityLocations = getComplexityLocations(documentContext); + + return documentContext.getSymbolTree().getMethodsByName().entrySet().stream() + .filter(entry -> enabledMethodsInFile.contains(entry.getKey())) + .map(Map.Entry::getValue) + .map(methodSymbol -> cognitiveComplexityLocations.getOrDefault(methodSymbol, Collections.emptyList()).stream() + .map(AbstractComplexityInlayHintSupplier::toInlayHint) + .collect(Collectors.toList())) + .flatMap(Collection::stream) + .collect(Collectors.toList()); + } + + /** + * Переключить показ подсказок сложности для метода. + * + * @param uri URI документа. + * @param methodName Имя метода. + */ + public void toggleHints(URI uri, String methodName) { + var methodsInFile = enabledMethods.computeIfAbsent(uri, uri1 -> new HashSet<>()); + if (methodsInFile.contains(methodName)) { + methodsInFile.remove(methodName); + } else { + methodsInFile.add(methodName); + } + } + + /** + * Получение мест увеличения сложности метода. Нужно переопределить в наследниках. + * + * @param documentContext Контекст документа. + * @return Места увеличения сложности метода. + */ + protected abstract Map> getComplexityLocations( + DocumentContext documentContext + ); + + private static InlayHint toInlayHint(ComplexitySecondaryLocation complexitySecondaryLocation) { + var inlayHint = new InlayHint(); + inlayHint.setPosition(complexitySecondaryLocation.getRange().getStart()); + inlayHint.setPaddingRight(Boolean.TRUE); + inlayHint.setKind(InlayHintKind.Parameter); + inlayHint.setLabel(complexitySecondaryLocation.getMessage()); + return inlayHint; + } + +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/CognitiveComplexityInlayHintSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/CognitiveComplexityInlayHintSupplier.java new file mode 100644 index 00000000000..da3bf85a94a --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/CognitiveComplexityInlayHintSupplier.java @@ -0,0 +1,51 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.inlayhints; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +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.stereotype.Component; + +import java.util.List; +import java.util.Map; + +/** + * Поставщик подсказок о когнитивной сложности методов. + */ +@Component +@RequiredArgsConstructor +public class CognitiveComplexityInlayHintSupplier extends AbstractComplexityInlayHintSupplier { + + /** + * {@inheritDoc} + */ + @Override + protected Map> getComplexityLocations( + DocumentContext documentContext + ) { + return documentContext + .getCognitiveComplexityData() + .getMethodsComplexitySecondaryLocations(); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/CyclomaticComplexityInlayHintSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/CyclomaticComplexityInlayHintSupplier.java new file mode 100644 index 00000000000..cbfae048f8b --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/CyclomaticComplexityInlayHintSupplier.java @@ -0,0 +1,51 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.inlayhints; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +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.stereotype.Component; + +import java.util.List; +import java.util.Map; + +/** + * Поставщик подсказок о цикломатической сложности методов. + */ +@Component +@RequiredArgsConstructor +public class CyclomaticComplexityInlayHintSupplier extends AbstractComplexityInlayHintSupplier { + + /** + * {@inheritDoc} + */ + @Override + protected Map> getComplexityLocations( + DocumentContext documentContext + ) { + return documentContext + .getCyclomaticComplexityData() + .getMethodsComplexitySecondaryLocations(); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/InlayHintSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/InlayHintSupplier.java new file mode 100644 index 00000000000..44bea201a79 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/InlayHintSupplier.java @@ -0,0 +1,62 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.inlayhints; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import org.eclipse.lsp4j.InlayHint; +import org.eclipse.lsp4j.InlayHintParams; + +import java.beans.Introspector; +import java.util.List; + +/** + * Базовый интерфейс для наполнения {@link com.github._1c_syntax.bsl.languageserver.providers.InlayHintProvider} + * данными о доступных в документе inlay hints. + */ +public interface InlayHintSupplier { + + String INLAY_HINT_SUPPLIER = "InlayHintSupplier"; + + /** + * Идентификатор сапплаера. + * + * @return Идентификатор сапплаера. + */ + default String getId() { + String simpleName = getClass().getSimpleName(); + if (simpleName.endsWith(INLAY_HINT_SUPPLIER)) { + simpleName = simpleName.substring(0, simpleName.length() - INLAY_HINT_SUPPLIER.length()); + simpleName = Introspector.decapitalize(simpleName); + } + + return simpleName; + } + + /** + * Получить inlay hints, доступные в документе. + * + * @param documentContext Контекст документа, для которого надо рассчитать inlay hints. + * @param params Параметры запроса. + * @return Список inlay hints в документе. + */ + List getInlayHints(DocumentContext documentContext, InlayHintParams params); +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/SourceDefinedMethodCallInlayHintSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/SourceDefinedMethodCallInlayHintSupplier.java new file mode 100644 index 00000000000..8efedcdf9ff --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/SourceDefinedMethodCallInlayHintSupplier.java @@ -0,0 +1,207 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.inlayhints; + +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 com.github._1c_syntax.bsl.languageserver.context.symbol.ParameterDefinition; +import com.github._1c_syntax.bsl.languageserver.hover.DescriptionFormatter; +import com.github._1c_syntax.bsl.languageserver.references.ReferenceIndex; +import com.github._1c_syntax.bsl.languageserver.references.model.Reference; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.languageserver.utils.Trees; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; +import lombok.RequiredArgsConstructor; +import org.apache.commons.lang3.StringUtils; +import org.eclipse.lsp4j.InlayHint; +import org.eclipse.lsp4j.InlayHintKind; +import org.eclipse.lsp4j.InlayHintParams; +import org.eclipse.lsp4j.MarkupContent; +import org.eclipse.lsp4j.MarkupKind; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.SymbolKind; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * Поставщик подсказок о параметрах вызываемого метода. + */ +@Component +@RequiredArgsConstructor +public class SourceDefinedMethodCallInlayHintSupplier implements InlayHintSupplier { + + // TODO: высчитать позицию хинта относительно последнего параметра. + private static final boolean DEFAULT_SHOW_ALL_PARAMETERS = false; + private static final boolean DEFAULT_SHOW_PARAMETERS_WITH_THE_SAME_NAME = false; + private static final boolean DEFAULT_DEFAULT_VALUES = true; + + private final ReferenceIndex referenceIndex; + private final LanguageServerConfiguration configuration; + private final DescriptionFormatter descriptionFormatter; + + + @Override + public List getInlayHints(DocumentContext documentContext, InlayHintParams params) { + var range = params.getRange(); + +// var ast = documentContext.getAst(); +// Trees.findAllRuleNodes( +// ast, +// BSLParser.RULE_methodCall, +// BSLParser.RULE_globalMethodCall +// ); + + return referenceIndex.getReferencesFrom(documentContext.getUri(), SymbolKind.Method).stream() + .filter(reference -> Ranges.containsPosition(range, reference.getSelectionRange().getStart())) + .filter(Reference::isSourceDefinedSymbolReference) + .map(this::toInlayHints) + .flatMap(Collection::stream) + .toList(); + } + + + private List toInlayHints(Reference reference) { + + var methodSymbol = (MethodSymbol) reference.getSymbol(); + var parameters = methodSymbol.getParameters(); + + var ast = reference.getFrom().getOwner().getAst(); + var doCalls = Trees.findAllRuleNodes(ast, BSLParser.RULE_doCall); + + return doCalls.stream() + .map(BSLParser.DoCallContext.class::cast) + .filter(doCall -> isRightMethod(doCall.getParent(), reference)) + .map(BSLParser.DoCallContext::callParamList) + .map(BSLParser.CallParamListContext::callParam) + .map((List callParams) -> { + var hints = new ArrayList(); + for (var i = 0; i < parameters.size(); i++) { + + // todo: show all parameters (in config)? + if (callParams.size() < i + 1) { + break; + } + + var parameter = parameters.get(i); + var callParam = callParams.get(i); + + var passedValue = callParam.getText(); + + if (!showParametersWithTheSameName() && StringUtils.containsIgnoreCase(passedValue, parameter.getName())) { + continue; + } + + var inlayHint = new InlayHint(); + inlayHint.setKind(InlayHintKind.Parameter); + + setLabelAndPadding(inlayHint, parameter, passedValue); + setPosition(inlayHint, callParam); + setTooltip(inlayHint, parameter); + + hints.add(inlayHint); + } + + return hints; + }) + .flatMap(Collection::stream) + .toList(); + + } + + private void setLabelAndPadding( + InlayHint inlayHint, + ParameterDefinition parameter, + String passedValue + ) { + + var defaultValue = parameter.getDefaultValue(); + + var labelBuilder = new StringBuilder(); + labelBuilder.append(parameter.getName()); + + if (showDefaultValues() + && passedValue.isBlank() + && !defaultValue.equals(ParameterDefinition.DefaultValue.EMPTY) + ) { + labelBuilder.append(" ("); + labelBuilder.append(defaultValue.value()); + labelBuilder.append(")"); + } else { + labelBuilder.append(":"); + inlayHint.setPaddingRight(Boolean.TRUE); + } + + inlayHint.setLabel(labelBuilder.toString()); + } + + private static void setPosition(InlayHint inlayHint, BSLParser.CallParamContext callParam) { + var position = new Position(callParam.getStart().getLine() - 1, callParam.getStart().getCharPositionInLine()); + inlayHint.setPosition(position); + } + + private void setTooltip(InlayHint inlayHint, ParameterDefinition parameter) { + var markdown = descriptionFormatter.parameterToString(parameter); + var tooltip = new MarkupContent(MarkupKind.MARKDOWN, markdown); + inlayHint.setTooltip(tooltip); + } + + + private boolean showParametersWithTheSameName() { + var parameters = configuration.getInlayHintOptions().getParameters().getOrDefault(getId(), Either.forLeft(true)); + if (parameters.isLeft()) { + return DEFAULT_SHOW_PARAMETERS_WITH_THE_SAME_NAME; + } else { + return (boolean) parameters.getRight().getOrDefault( + "showParametersWithTheSameName", + DEFAULT_SHOW_PARAMETERS_WITH_THE_SAME_NAME + ); + } + } + + private boolean showDefaultValues() { + var parameters = configuration.getInlayHintOptions().getParameters().getOrDefault(getId(), Either.forLeft(true)); + if (parameters.isLeft()) { + return DEFAULT_DEFAULT_VALUES; + } else { + return (boolean) parameters.getRight().getOrDefault("showDefaultValues", DEFAULT_DEFAULT_VALUES); + } + } + + + private static boolean isRightMethod(BSLParserRuleContext doCallParent, Reference reference) { + var selectionRange = reference.getSelectionRange(); + + if (doCallParent instanceof BSLParser.MethodCallContext methodCallContext) { + return selectionRange.equals(Ranges.create(methodCallContext.methodName())); + } else if (doCallParent instanceof BSLParser.GlobalMethodCallContext globalMethodCallContext) { + return selectionRange.equals(Ranges.create(globalMethodCallContext.methodName())); + } else { + return false; + } + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/infrastructure/InlayHintsConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/infrastructure/InlayHintsConfiguration.java new file mode 100644 index 00000000000..ee6b86b8565 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/infrastructure/InlayHintsConfiguration.java @@ -0,0 +1,71 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.inlayhints.infrastructure; + +import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; +import com.github._1c_syntax.bsl.languageserver.inlayhints.InlayHintSupplier; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Scope; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE; + +/** + * Spring-конфигурация для определения бинов + * пакета {@link com.github._1c_syntax.bsl.languageserver.inlayhints}. + */ +@Configuration +public class InlayHintsConfiguration { + + /** + * Получить список активированных в данный момент сапплаеров inlay hints. + * + * @param configuration Конфигурация сервера. + * @param inlayHintSuppliers Список сапплаеров inlay hints в разрезе из идентификаторов. + * @return Список активированных в данный момент сапплаеров inlay hints. + */ + @Bean + @Scope(SCOPE_PROTOTYPE) + public List enabledInlayHintSuppliers( + LanguageServerConfiguration configuration, + Collection inlayHintSuppliers + ) { + var parameters = configuration.getInlayHintOptions().getParameters(); + return inlayHintSuppliers.stream() + .filter(supplier -> supplierIsEnabled(supplier.getId(), parameters)) + .collect(Collectors.toList()); + } + + private static boolean supplierIsEnabled( + String supplierId, + Map>> parameters + ) { + var supplierConfig = parameters.getOrDefault(supplierId, Either.forLeft(true)); + return supplierConfig.isRight() || supplierConfig.getLeft(); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/infrastructure/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/infrastructure/package-info.java new file mode 100644 index 00000000000..32b40ee3e9b --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/infrastructure/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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. + */ +/** + * Spring-специфичные классы для настройки внутренней инфраструктуры + * пакета {@link com.github._1c_syntax.bsl.languageserver.inlayhints}. + */ +@DefaultAnnotation(NonNull.class) +package com.github._1c_syntax.bsl.languageserver.inlayhints.infrastructure; + +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/package-info.java new file mode 100644 index 00000000000..fb74989ea39 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/package-info.java @@ -0,0 +1,30 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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. + */ +/** + * Пакет предназначен для реализации inlay hints, + * предоставляемых {@link com.github._1c_syntax.bsl.languageserver.providers.InlayHintProvider}. + */ +@DefaultAnnotation(NonNull.class) +package com.github._1c_syntax.bsl.languageserver.inlayhints; + +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/jsonrpc/DiagnosticParams.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/jsonrpc/DiagnosticParams.java index 82fa20549a9..ab3ce3e19a1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/jsonrpc/DiagnosticParams.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/jsonrpc/DiagnosticParams.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,6 +21,7 @@ */ package com.github._1c_syntax.bsl.languageserver.jsonrpc; +import edu.umd.cs.findbugs.annotations.Nullable; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -30,8 +31,6 @@ import org.eclipse.lsp4j.Range; import org.eclipse.lsp4j.TextDocumentIdentifier; -import javax.annotation.Nullable; - /** * Параметры запроса textDocument/x-diagnostics. *
diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/jsonrpc/Diagnostics.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/jsonrpc/Diagnostics.java index 9252c6982ea..e1fe86e6ae9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/jsonrpc/Diagnostics.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/jsonrpc/Diagnostics.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/jsonrpc/ProtocolExtension.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/jsonrpc/ProtocolExtension.java index 7a7d50c8709..2dc67987d3d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/jsonrpc/ProtocolExtension.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/jsonrpc/ProtocolExtension.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/jsonrpc/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/jsonrpc/package-info.java index e4da6e90689..51a1d89ed1c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/jsonrpc/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/jsonrpc/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,7 +22,8 @@ /** * Кастомные расширения Language Server Protocol. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.jsonrpc; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/package-info.java index 8133cdafc9f..5179e581a5f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -19,7 +19,8 @@ * You should have received a copy of the GNU Lesser General Public * License along with BSL Language Server. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CallHierarchyProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CallHierarchyProvider.java index 81e5c357044..ba179e2454b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CallHierarchyProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CallHierarchyProvider.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,10 +23,12 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.context.symbol.SourceDefinedSymbol; -import com.github._1c_syntax.bsl.languageserver.references.model.Reference; +import com.github._1c_syntax.bsl.languageserver.context.symbol.Symbol; import com.github._1c_syntax.bsl.languageserver.references.ReferenceIndex; import com.github._1c_syntax.bsl.languageserver.references.ReferenceResolver; +import com.github._1c_syntax.bsl.languageserver.references.model.Reference; import com.github._1c_syntax.bsl.languageserver.utils.MdoRefBuilder; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import lombok.RequiredArgsConstructor; import org.eclipse.lsp4j.CallHierarchyIncomingCall; import org.eclipse.lsp4j.CallHierarchyIncomingCallsParams; @@ -35,14 +37,15 @@ import org.eclipse.lsp4j.CallHierarchyOutgoingCallsParams; import org.eclipse.lsp4j.CallHierarchyPrepareParams; import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.SymbolKind; import org.springframework.stereotype.Component; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.Comparator; import java.util.List; -import java.util.stream.Collectors; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.mapping; @@ -55,6 +58,10 @@ public class CallHierarchyProvider { private final ReferenceResolver referenceResolver; private final ReferenceIndex referenceIndex; + private final Comparator callHierarchyItemComparator = Comparator + .comparing(CallHierarchyItem::getDetail) + .thenComparing(CallHierarchyItem::getSelectionRange, Ranges::compare); + public List prepareCallHierarchy( DocumentContext documentContext, CallHierarchyPrepareParams params @@ -65,8 +72,7 @@ public List prepareCallHierarchy( .flatMap(Reference::getSourceDefinedSymbol) .map(CallHierarchyProvider::getCallHierarchyItem) .map(Collections::singletonList) - .orElse(Collections.emptyList()) - ; + .orElse(Collections.emptyList()); } public List incomingCalls( @@ -90,8 +96,8 @@ public List incomingCalls( .entrySet() .stream() .map(entry -> new CallHierarchyIncomingCall(getCallHierarchyItem(entry.getKey()), entry.getValue())) - .collect(Collectors.toList()); - + .sorted((o1, o2) -> callHierarchyItemComparator.compare(o1.getFrom(), o2.getFrom())) + .toList(); } public List outgoingCalls( @@ -101,13 +107,13 @@ public List outgoingCalls( URI uri = documentContext.getUri(); Position position = params.getItem().getSelectionRange().getStart(); - return referenceResolver.findReference(uri, position) .flatMap(Reference::getSourceDefinedSymbol) .stream() .map(referenceIndex::getReferencesFrom) .flatMap(Collection::stream) .filter(Reference::isSourceDefinedSymbolReference) + .filter(reference -> isSymbolSupported(reference.getSymbol())) .collect(groupingBy( reference -> reference.getSourceDefinedSymbol().orElseThrow(), mapping(Reference::getSelectionRange, toCollection(ArrayList::new))) @@ -115,8 +121,8 @@ public List outgoingCalls( .entrySet() .stream() .map(entry -> new CallHierarchyOutgoingCall(getCallHierarchyItem(entry.getKey()), entry.getValue())) - .collect(Collectors.toList()); - + .sorted((o1, o2) -> callHierarchyItemComparator.compare(o1.getTo(), o2.getTo())) + .toList(); } private static CallHierarchyItem getCallHierarchyItem(SourceDefinedSymbol sourceDefinedSymbol) { @@ -133,4 +139,8 @@ private static CallHierarchyItem getCallHierarchyItem(SourceDefinedSymbol source return item; } + + private static boolean isSymbolSupported(Symbol symbol) { + return symbol.getSymbolKind() == SymbolKind.Method; + } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeActionProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeActionProvider.java index 2b1dc6d7ba5..0c7f9f3ab63 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeActionProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeActionProvider.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeLensProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeLensProvider.java index b264896b973..9f6c2f9201d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeLensProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeLensProvider.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,13 +21,14 @@ */ package com.github._1c_syntax.bsl.languageserver.providers; +import com.fasterxml.jackson.databind.ObjectMapper; import com.github._1c_syntax.bsl.languageserver.ClientCapabilitiesHolder; import com.github._1c_syntax.bsl.languageserver.LanguageClientHolder; import com.github._1c_syntax.bsl.languageserver.codelenses.CodeLensData; import com.github._1c_syntax.bsl.languageserver.codelenses.CodeLensSupplier; -import com.github._1c_syntax.bsl.languageserver.codelenses.databind.CodeLensDataObjectMapper; import com.github._1c_syntax.bsl.languageserver.configuration.events.LanguageServerConfigurationChangedEvent; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import org.eclipse.lsp4j.ClientCapabilities; @@ -40,7 +41,6 @@ import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; import java.util.Collection; import java.util.List; import java.util.Map; @@ -61,7 +61,7 @@ public class CodeLensProvider { private final ObjectProvider>> enabledCodeLensSuppliersProvider; private final LanguageClientHolder clientHolder; private final ClientCapabilitiesHolder clientCapabilitiesHolder; - private final CodeLensDataObjectMapper codeLensDataObjectMapper; + private final ObjectMapper objectMapper; private List> enabledCodeLensSuppliers; @@ -118,17 +118,7 @@ public CodeLens resolveCodeLens( public void handleEvent(LanguageServerConfigurationChangedEvent event) { enabledCodeLensSuppliers = enabledCodeLensSuppliersProvider.getObject(); - boolean clientSupportsRefreshCodeLenses = clientCapabilitiesHolder.getCapabilities() - .map(ClientCapabilities::getWorkspace) - .map(WorkspaceClientCapabilities::getCodeLens) - .map(CodeLensWorkspaceCapabilities::getRefreshSupport) - .orElse(false); - - if (!clientSupportsRefreshCodeLenses) { - return; - } - - clientHolder.execIfConnected(LanguageClient::refreshCodeLenses); + refreshCodeLenses(); } /** @@ -148,6 +138,23 @@ public CodeLensData extractData(CodeLens codeLens) { return (CodeLensData) rawCodeLensData; } - return codeLensDataObjectMapper.readValue(rawCodeLensData.toString(), CodeLensData.class); + return objectMapper.readValue(rawCodeLensData.toString(), CodeLensData.class); + } + + /** + * Отправить запрос на обновление линз кода. + */ + public void refreshCodeLenses() { + boolean clientSupportsRefreshCodeLenses = clientCapabilitiesHolder.getCapabilities() + .map(ClientCapabilities::getWorkspace) + .map(WorkspaceClientCapabilities::getCodeLens) + .map(CodeLensWorkspaceCapabilities::getRefreshSupport) + .orElse(false); + + if (!clientSupportsRefreshCodeLenses) { + return; + } + + clientHolder.execIfConnected(LanguageClient::refreshCodeLenses); } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/ColorProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/ColorProvider.java index a9a01229549..c5a3a5e7db9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/ColorProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/ColorProvider.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CommandProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CommandProvider.java new file mode 100644 index 00000000000..7c65483d18d --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/CommandProvider.java @@ -0,0 +1,117 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.providers; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github._1c_syntax.bsl.languageserver.commands.CommandArguments; +import com.github._1c_syntax.bsl.languageserver.commands.CommandSupplier; +import lombok.RequiredArgsConstructor; +import lombok.SneakyThrows; +import org.eclipse.lsp4j.ExecuteCommandParams; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +/** + * Провайдер, обрабатывающий запросы {@code workspace/executeCommans}. + * + * @see Execute a command specification. + */ +@Component +@RequiredArgsConstructor +public class CommandProvider { + + private final Map> commandSuppliersById; + private final ObjectMapper objectMapper; + + private final CodeLensProvider codeLensProvider; + private final InlayHintProvider inlayHintProvider; + + /** + * Выполнить серверную команду. + * + * @param arguments Аргументы команды. + * + * @return Результат выполнения команды. + */ + public Object executeCommand(CommandArguments arguments) { + var commandId = arguments.getId(); + + var commandSupplier = commandSuppliersById.get(commandId); + if (commandSupplier == null) { + throw new RuntimeException("Unknown command id: " + commandId); + } + + var result = commandSupplier + .execute(arguments) + .orElse(null); + + CompletableFuture.runAsync(() -> { + if (commandSupplier.needRefreshInlayHintsAfterExecuteCommand()) { + inlayHintProvider.refreshInlayHints(); + } + if (commandSupplier.needRefreshCodeLensesAfterExecuteCommand()) { + codeLensProvider.refreshCodeLenses(); + } + }); + + return result; + } + + /** + * Список идентификаторов известных серверных команд. + * + * @return Список идентификаторов известных серверных команд. + */ + public List getCommandIds() { + return List.copyOf(commandSuppliersById.keySet()); + } + + /** + * Извлечь аргументы команды из параметров входящего запроса. + * + * @param executeCommandParams Параметры запроса workspace/executeCommand. + * @return Аргументы команды. + * + * @throws RuntimeException Выбрасывает исключение, если параметры входящего запроса не содержат + * данных для вычисления аргументов команды. + */ + @SneakyThrows + public CommandArguments extractArguments(ExecuteCommandParams executeCommandParams) { + var rawArguments = executeCommandParams.getArguments(); + + if (rawArguments.isEmpty()) { + throw new RuntimeException("Command arguments is empty"); + } + + var rawArgument = rawArguments.get(0); + + if (rawArgument instanceof CommandArguments) { + return (CommandArguments) rawArgument; + } + + return objectMapper.readValue(rawArgument.toString(), CommandArguments.class); + } + +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DefinitionProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DefinitionProvider.java index c7e3f070c64..457d7efd872 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DefinitionProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DefinitionProvider.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,8 +23,8 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.context.symbol.SourceDefinedSymbol; -import com.github._1c_syntax.bsl.languageserver.references.model.Reference; import com.github._1c_syntax.bsl.languageserver.references.ReferenceResolver; +import com.github._1c_syntax.bsl.languageserver.references.model.Reference; import lombok.RequiredArgsConstructor; import org.eclipse.lsp4j.DefinitionParams; import org.eclipse.lsp4j.LocationLink; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProvider.java index d50a5d19425..683be1123b3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProvider.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,7 +24,6 @@ import com.github._1c_syntax.bsl.languageserver.LanguageClientHolder; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import org.eclipse.lsp4j.Diagnostic; import org.eclipse.lsp4j.PublishDiagnosticsParams; import org.springframework.stereotype.Component; @@ -33,7 +32,6 @@ import java.util.List; import java.util.function.Supplier; -@Slf4j @Component @RequiredArgsConstructor public final class DiagnosticProvider { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java index a716faaa136..135c5afed29 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProvider.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProvider.java index 942b3a5407d..b9fc1b34619 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProvider.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -45,6 +45,7 @@ public final class DocumentSymbolProvider { private static final Set supportedVariableKinds = EnumSet.of( VariableKind.MODULE, + VariableKind.LOCAL, VariableKind.GLOBAL ); @@ -64,6 +65,7 @@ private static DocumentSymbol toDocumentSymbol(SourceDefinedSymbol symbol) { ); List children = symbol.getChildren().stream() + .filter(DocumentSymbolProvider::isSupported) .map(DocumentSymbolProvider::toDocumentSymbol) .collect(Collectors.toList()); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/FoldingRangeProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/FoldingRangeProvider.java index 168a868bc08..a988746f2a2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/FoldingRangeProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/FoldingRangeProvider.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/FormatProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/FormatProvider.java index 8b76ba6e937..75da7a2890a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/FormatProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/FormatProvider.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/HoverProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/HoverProvider.java index b67e92c5a25..6906e8d1230 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/HoverProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/HoverProvider.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,8 +24,8 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.context.symbol.Symbol; import com.github._1c_syntax.bsl.languageserver.hover.MarkupContentBuilder; -import com.github._1c_syntax.bsl.languageserver.references.model.Reference; import com.github._1c_syntax.bsl.languageserver.references.ReferenceResolver; +import com.github._1c_syntax.bsl.languageserver.references.model.Reference; import lombok.RequiredArgsConstructor; import org.eclipse.lsp4j.Hover; import org.eclipse.lsp4j.HoverParams; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/InlayHintProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/InlayHintProvider.java new file mode 100644 index 00000000000..7a953d215a1 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/InlayHintProvider.java @@ -0,0 +1,110 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.providers; + +import com.github._1c_syntax.bsl.languageserver.ClientCapabilitiesHolder; +import com.github._1c_syntax.bsl.languageserver.LanguageClientHolder; +import com.github._1c_syntax.bsl.languageserver.configuration.events.LanguageServerConfigurationChangedEvent; +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.inlayhints.InlayHintSupplier; +import lombok.RequiredArgsConstructor; +import org.eclipse.lsp4j.ClientCapabilities; +import org.eclipse.lsp4j.InlayHint; +import org.eclipse.lsp4j.InlayHintParams; +import org.eclipse.lsp4j.InlayHintWorkspaceCapabilities; +import org.eclipse.lsp4j.WorkspaceClientCapabilities; +import org.eclipse.lsp4j.services.LanguageClient; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Провайдер, обрабатывающий запросы {@code textDocument/inlayHint} и {@code inlayHint/resolve}. + * + * @see Inlay hint request. + * @see Inlay hint resolve request + */ +@Component +@RequiredArgsConstructor +public class InlayHintProvider { + + @Qualifier("enabledInlayHintSuppliers") + private final ObjectProvider> enabledInlayHintSuppliersProvider; + private final ClientCapabilitiesHolder clientCapabilitiesHolder; + private final LanguageClientHolder clientHolder; + + private List enabledInlayHintSuppliers; + + @PostConstruct + protected void init() { + enabledInlayHintSuppliers = enabledInlayHintSuppliersProvider.getObject(); + } + + /** + * Получить список inlay hints в документе. + * + * @param documentContext Документ, для которого запрашиваются inlay hints. + * @param params Параметры запроса. + * @return Список inlay hints в документе + */ + public List getInlayHint(DocumentContext documentContext, InlayHintParams params) { + return enabledInlayHintSuppliers.stream() + .map(supplier -> supplier.getInlayHints(documentContext, params)) + .flatMap(Collection::stream) + .collect(Collectors.toList()); + } + + /** + * Обработчик события {@link LanguageServerConfigurationChangedEvent}. + *

+ * В случае поддержки запроса подключенным клиентом инициирует запрос {@code workspace/inlayHint/refresh}. + * + * @param event Событие + */ + @EventListener + public void handleEvent(LanguageServerConfigurationChangedEvent event) { + enabledInlayHintSuppliers = enabledInlayHintSuppliersProvider.getObject(); + + refreshInlayHints(); + } + + /** + * Отправить запрос на обновление inlay hints. + */ + public void refreshInlayHints() { + boolean refreshSupport = clientCapabilitiesHolder.getCapabilities() + .map(ClientCapabilities::getWorkspace) + .map(WorkspaceClientCapabilities::getInlayHint) + .map(InlayHintWorkspaceCapabilities::getRefreshSupport) + .orElse(Boolean.FALSE); + + if (refreshSupport) { + clientHolder.execIfConnected(LanguageClient::refreshInlayHints); + } + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/ReferencesProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/ReferencesProvider.java index f0437d45cf3..a51708de6fe 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/ReferencesProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/ReferencesProvider.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,9 +22,9 @@ package com.github._1c_syntax.bsl.languageserver.providers; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; -import com.github._1c_syntax.bsl.languageserver.references.model.Reference; import com.github._1c_syntax.bsl.languageserver.references.ReferenceIndex; import com.github._1c_syntax.bsl.languageserver.references.ReferenceResolver; +import com.github._1c_syntax.bsl.languageserver.references.model.Reference; import lombok.RequiredArgsConstructor; import org.eclipse.lsp4j.Location; import org.eclipse.lsp4j.ReferenceParams; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/RenameProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/RenameProvider.java index 38cee8e8570..d36f7d5912c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/RenameProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/RenameProvider.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/SelectionRangeProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/SelectionRangeProvider.java index c0aa60e0242..758dc49b818 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/SelectionRangeProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/SelectionRangeProvider.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -26,14 +26,13 @@ import com.github._1c_syntax.bsl.languageserver.utils.Trees; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; +import edu.umd.cs.findbugs.annotations.Nullable; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; import org.eclipse.lsp4j.SelectionRange; import org.eclipse.lsp4j.SelectionRangeParams; import org.springframework.stereotype.Component; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Comparator; import java.util.List; @@ -76,7 +75,7 @@ public class SelectionRangeProvider { * Получение данных о {@link SelectionRange} по позиции в документе. * * @param documentContext контекст документа. - * @param params параметры вызова. + * @param params параметры вызова. * @return список найденных диапазонов. */ public List getSelectionRange(DocumentContext documentContext, SelectionRangeParams params) { @@ -92,7 +91,7 @@ public List getSelectionRange(DocumentContext documentContext, S .collect(Collectors.toList()); } - @CheckForNull + @Nullable private static SelectionRange toSelectionRange(@Nullable ParseTree node) { if (node == null) { return null; @@ -130,16 +129,16 @@ private static Optional nextParentWithDifferentRange(ParseTree ctx) { } private static BSLParserRuleContext getParentContext(ParseTree ctx) { - if (ctx instanceof BSLParser.StatementContext) { - return getStatementParent((BSLParser.StatementContext) ctx); + if (ctx instanceof BSLParser.StatementContext statementContext) { + return getStatementParent(statementContext); } return getDefaultParent(ctx); } - @CheckForNull + @Nullable private static BSLParserRuleContext getDefaultParent(ParseTree ctx) { - return (BSLParserRuleContext) ctx.getParent(); + return (BSLParserRuleContext) ctx.getParent(); } private static BSLParserRuleContext getStatementParent(BSLParser.StatementContext statement) { @@ -202,13 +201,11 @@ private static BSLParserRuleContext getStatementParent(BSLParser.StatementContex } private static boolean ifBranchMatchesIfStatement(BSLParserRuleContext ctx) { - if (!(ctx instanceof BSLParser.IfBranchContext)) { + if (!(ctx instanceof BSLParser.IfBranchContext ifBranch)) { return false; } - var ifBranch = (BSLParser.IfBranchContext) ctx; var ifStatement = (BSLParser.IfStatementContext) ifBranch.getParent(); return ifStatement.elseBranch() == null && ifStatement.elsifBranch().isEmpty(); } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/SymbolProvider.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/SymbolProvider.java index 8aa9d08211f..031211b66c9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/SymbolProvider.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/SymbolProvider.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -55,7 +55,7 @@ public class SymbolProvider { private final ServerContext context; - private static final Set supportedVariableKinds = EnumSet.of( + private static final Set SUPPORTED_VARIABLE_KINDS = EnumSet.of( VariableKind.MODULE, VariableKind.GLOBAL ); @@ -87,14 +87,11 @@ private static Stream> getSymbolPairs(DocumentCon private static boolean isSupported(Symbol symbol) { var symbolKind = symbol.getSymbolKind(); - switch (symbolKind) { - case Method: - return true; - case Variable: - return supportedVariableKinds.contains(((VariableSymbol) symbol).getKind()); - default: - return false; - } + return switch (symbolKind) { + case Method -> true; + case Variable -> SUPPORTED_VARIABLE_KINDS.contains(((VariableSymbol) symbol).getKind()); + default -> false; + }; } private static WorkspaceSymbol createWorkspaceSymbol(Pair symbolPair) { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/package-info.java index 173678bdfeb..39b3a8d0969 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/AbstractDetector.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/AbstractDetector.java index 69b0f70f292..768284bd6a8 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/AbstractDetector.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/AbstractDetector.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/BSLFootprint.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/BSLFootprint.java index 9c367429f50..1cd8935ce23 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/BSLFootprint.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/BSLFootprint.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/CamelCaseDetector.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/CamelCaseDetector.java index a236c769356..3ebc837c9a0 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/CamelCaseDetector.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/CamelCaseDetector.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/CodeRecognizer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/CodeRecognizer.java index 9c32d1b08b9..c64850cb92a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/CodeRecognizer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/CodeRecognizer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/ContainsDetector.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/ContainsDetector.java index ceea8e205a9..18b4c0bbe21 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/ContainsDetector.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/ContainsDetector.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/EndWithDetector.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/EndWithDetector.java index 737107c7a85..f94755dbb1a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/EndWithDetector.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/EndWithDetector.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/KeywordsDetector.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/KeywordsDetector.java index 46b2c053aa9..24d0cc94075 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/KeywordsDetector.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/KeywordsDetector.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/LanguageFootprint.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/LanguageFootprint.java index e45f9358de3..037c5d8d145 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/LanguageFootprint.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/LanguageFootprint.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/PatternDetector.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/PatternDetector.java index 13138431b73..f7bf4901e6c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/PatternDetector.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/PatternDetector.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/package-info.java index 0d3ed35fc8b..2e381867994 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/recognizer/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/AnnotationReferenceFinder.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/AnnotationReferenceFinder.java new file mode 100644 index 00000000000..982eabe14be --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/AnnotationReferenceFinder.java @@ -0,0 +1,223 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.references; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.FileType; +import com.github._1c_syntax.bsl.languageserver.context.ServerContext; +import com.github._1c_syntax.bsl.languageserver.context.events.DocumentContextContentChangedEvent; +import com.github._1c_syntax.bsl.languageserver.context.events.ServerContextPopulatedEvent; +import com.github._1c_syntax.bsl.languageserver.context.symbol.AnnotationParamSymbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.AnnotationSymbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.annotations.Annotation; +import com.github._1c_syntax.bsl.languageserver.references.model.Reference; +import com.github._1c_syntax.bsl.languageserver.utils.Methods; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.languageserver.utils.Trees; +import com.github._1c_syntax.bsl.parser.BSLParser; +import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; +import lombok.RequiredArgsConstructor; +import org.apache.commons.lang3.tuple.Pair; +import org.eclipse.lsp4j.Location; +import org.eclipse.lsp4j.Position; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +import java.net.URI; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +@Component +@RequiredArgsConstructor +public class AnnotationReferenceFinder implements ReferenceFinder { + + private final ServerContext serverContext; + private final Map registeredAnnotations = new ConcurrentHashMap<>(); + + @EventListener + public void handleContextRefresh(ServerContextPopulatedEvent event) { + registeredAnnotations.clear(); + serverContext.getDocuments() + .values() + .forEach(this::findAndRegisterAnnotation); + } + + @EventListener + public void handleDocumentContextChange(DocumentContextContentChangedEvent event) { + DocumentContext documentContext = event.getSource(); + var uri = documentContext.getUri(); + + registeredAnnotations.values() + .removeIf(annotationSymbol -> annotationSymbol.getOwner().getUri().equals(uri)); + + findAndRegisterAnnotation(documentContext); + } + + private void findAndRegisterAnnotation(DocumentContext documentContext) { + // In normal case this method may be called twice per each document context: + // 1. When the document context is created during the server context population or document opening + // 2. When server context is fully populated. + // This can lead to the situation when annotations registered from opened documents are cleared after populateContext step. + // Due to limitation of mechanism to only OS files, we can leave it as is for now, but it should be refactored in the future. + if (documentContext.getFileType() != FileType.OS) { + return; + } + + var symbolTree = documentContext.getSymbolTree(); + + Methods.getOscriptClassConstructor(symbolTree) + .flatMap(AnnotationReferenceFinder::findAnnotation) + .map(methodSymbolAnnotationPair -> AnnotationSymbol.from(getAnnotationName(methodSymbolAnnotationPair.getRight()), methodSymbolAnnotationPair.getLeft())) + .ifPresent(annotationSymbol -> registeredAnnotations.put(annotationSymbol.getName(), annotationSymbol)); + } + + @Override + public Optional findReference(URI uri, Position position) { + DocumentContext documentContext = serverContext.getDocument(uri); + if (documentContext == null || documentContext.getFileType() != FileType.OS) { + return Optional.empty(); + } + + var maybeTerminalNode = Trees.findTerminalNodeContainsPosition(documentContext.getAst(), position); + if (maybeTerminalNode.isEmpty()) { + return Optional.empty(); + } + + var terminalNode = maybeTerminalNode.get(); + var parent = terminalNode.getParent(); + if (!(parent instanceof BSLParserRuleContext parentContext)) { + return Optional.empty(); + } + + return Optional.of(parentContext) + .filter(BSLParser.AnnotationNameContext.class::isInstance) + .map(BSLParser.AnnotationNameContext.class::cast) + .flatMap(annotationName -> getReferenceToAnnotationSymbol(uri, annotationName, documentContext)) + + .or(() -> Optional.of(parentContext) + .filter(BSLParser.AnnotationParamNameContext.class::isInstance) + .map(BSLParser.AnnotationParamNameContext.class::cast) + .flatMap(annotationParamName -> getReferenceToAnnotationParamSymbol(annotationParamName, documentContext)) + ) + + .or(() -> Optional.of(parentContext) + .filter(BSLParser.ConstValueContext.class::isInstance) + .map(BSLParser.ConstValueContext.class::cast) + .flatMap(constValue -> getReferenceToAnnotationParamSymbol(constValue, documentContext)) + ) + + .or(() -> Optional.of(parentContext) + .map(BSLParserRuleContext::getParent) + .filter(BSLParser.ConstValueContext.class::isInstance) + .map(BSLParser.ConstValueContext.class::cast) + .flatMap(constValue -> getReferenceToAnnotationParamSymbol(constValue, documentContext)) + ) + + .or(() -> Optional.of(parentContext) + .map(BSLParserRuleContext::getParent) + .map(BSLParserRuleContext::getParent) + .filter(BSLParser.ConstValueContext.class::isInstance) + .map(BSLParser.ConstValueContext.class::cast) + .flatMap(constValue -> getReferenceToAnnotationParamSymbol(constValue, documentContext)) + ); + + } + + private Optional getReferenceToAnnotationSymbol(URI uri, BSLParser.AnnotationNameContext annotationName, DocumentContext documentContext) { + var annotationNode = (BSLParser.AnnotationContext) annotationName.getParent(); + + return getAnnotationSymbol(annotationName) + .map(annotationSymbol -> Reference.of( + documentContext.getSymbolTree().getModule(), + annotationSymbol, + new Location(uri.toString(), Ranges.create(annotationNode)) + )); + } + + private Optional getReferenceToAnnotationParamSymbol(BSLParser.AnnotationParamNameContext annotationParamName, DocumentContext documentContext) { + return Optional.of(annotationParamName) + .map(BSLParserRuleContext::getParent) // BSLParser.AnnotationParamContext + .map(BSLParser.AnnotationParamContext.class::cast) + .flatMap(annotationParamContext -> getReferenceToAnnotationParam(documentContext, Optional.of(annotationParamContext))); + } + + private Optional getReferenceToAnnotationParamSymbol(BSLParser.ConstValueContext constValue, DocumentContext documentContext) { + return Optional.of(constValue) + .map(BSLParserRuleContext::getParent) // BSLParser.AnnotationParamContext + .filter(BSLParser.AnnotationParamContext.class::isInstance) + .map(BSLParser.AnnotationParamContext.class::cast) + .flatMap(annotationParamContext -> getReferenceToAnnotationParam(documentContext, Optional.of(annotationParamContext))); + } + + private Optional getAnnotationSymbol(BSLParser.AnnotationNameContext annotationNode) { + var annotationName = annotationNode.getText(); + return Optional.ofNullable(registeredAnnotations.get(annotationName)); + } + + private Optional getReferenceToAnnotationParam( + DocumentContext documentContext, + Optional annotationParamContext + ) { + + var annotationParamName = annotationParamContext + .map(BSLParser.AnnotationParamContext::annotationParamName) + .map(BSLParserRuleContext::getText) + .orElse("Значение"); + + BSLParserRuleContext annotationParamLocation = annotationParamContext + .map(BSLParser.AnnotationParamContext::annotationParamName) + .map(BSLParserRuleContext.class::cast) + .or(() -> annotationParamContext.map(BSLParser.AnnotationParamContext::constValue)) + .orElseThrow(); + + return annotationParamContext + .map(BSLParserRuleContext::getParent) // BSLParser.AnnotationParamsContext + .map(BSLParserRuleContext::getParent) // BSLParser.AnnotationContext + .map(BSLParser.AnnotationContext.class::cast) + + .map(BSLParser.AnnotationContext::annotationName) + .flatMap(this::getAnnotationSymbol) + .flatMap(AnnotationSymbol::getParent) + .filter(MethodSymbol.class::isInstance) + .map(MethodSymbol.class::cast) + .map(annotationDefinitionMethodSymbol -> AnnotationParamSymbol.from(annotationParamName, annotationDefinitionMethodSymbol)) + .map(annotationParamSymbol -> Reference.of( + documentContext.getSymbolTree().getModule(), + annotationParamSymbol, + new Location(documentContext.getUri().toString(), Ranges.create(annotationParamLocation)) + )); + } + + private static Optional> findAnnotation(MethodSymbol methodSymbol) { + return methodSymbol.getAnnotations().stream() + .filter(annotation -> annotation.getName().equalsIgnoreCase("Аннотация")) + .findFirst() + .filter(annotation -> annotation.getParameters().size() == 1) + .map(annotation -> Pair.of(methodSymbol, annotation)); + } + + private static String getAnnotationName(Annotation annotation) { + return annotation.getParameters().get(0).getValue(); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceFinder.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceFinder.java index fcea00ffd6f..071c4f34a40 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceFinder.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceFinder.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndex.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndex.java index 8a06c63893d..edd7dd243d2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndex.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndex.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexFiller.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexFiller.java index 74f44f8fe66..38f539fefb3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexFiller.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexFiller.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -36,6 +36,7 @@ import com.github._1c_syntax.bsl.parser.BSLParserBaseVisitor; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; import com.github._1c_syntax.bsl.types.ModuleType; +import edu.umd.cs.findbugs.annotations.Nullable; import lombok.RequiredArgsConstructor; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.ParseTree; @@ -44,9 +45,7 @@ import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; -import javax.annotation.Nullable; import java.net.URI; -import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; @@ -54,8 +53,8 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; -import java.util.stream.Collectors; import java.util.function.Predicate; +import java.util.stream.Collectors; @Component @RequiredArgsConstructor @@ -105,7 +104,6 @@ public BSLParserRuleContext visitFuncDeclaration(BSLParser.FuncDeclarationContex @Override public BSLParserRuleContext visitCallStatement(BSLParser.CallStatementContext ctx) { - if (ctx.globalMethodCall() != null) { // see visitGlobalMethodCall return super.visitCallStatement(ctx); @@ -123,14 +121,12 @@ public BSLParserRuleContext visitCallStatement(BSLParser.CallStatementContext ct @Override public BSLParserRuleContext visitComplexIdentifier(BSLParser.ComplexIdentifierContext ctx) { - - String mdoRef = MdoRefBuilder.getMdoRef(documentContext, ctx); + var mdoRef = MdoRefBuilder.getMdoRef(documentContext, ctx); if (mdoRef.isEmpty()) { return super.visitComplexIdentifier(ctx); } Methods.getMethodName(ctx).ifPresent(methodName -> checkCall(mdoRef, methodName)); - return super.visitComplexIdentifier(ctx); } @@ -151,7 +147,7 @@ public BSLParserRuleContext visitGlobalMethodCall(BSLParser.GlobalMethodCallCont public BSLParserRuleContext visitNewExpression(BSLParser.NewExpressionContext ctx) { if (NotifyDescription.isNotifyDescription(ctx)) { final var doCallContext = ctx.doCall(); - if (doCallContext == null){ + if (doCallContext == null) { return super.visitNewExpression(ctx); } var callParamList = doCallContext.callParamList().callParam(); @@ -179,11 +175,11 @@ public BSLParserRuleContext visitNewExpression(BSLParser.NewExpressionContext ct @Override public BSLParserRuleContext visitLValue(BSLParser.LValueContext ctx) { final var identifier = ctx.IDENTIFIER(); - if (identifier != null){ + if (identifier != null) { final List modifiers = Optional.ofNullable(ctx.acceptor()) .map(BSLParser.AcceptorContext::modifier) .orElseGet(Collections::emptyList); - String mdoRef = MdoRefBuilder.getMdoRef(documentContext, identifier, modifiers); + var mdoRef = MdoRefBuilder.getMdoRef(documentContext, identifier, modifiers); if (!mdoRef.isEmpty()) { Methods.getMethodName(ctx).ifPresent(methodName -> checkCall(mdoRef, methodName)); } @@ -194,10 +190,10 @@ public BSLParserRuleContext visitLValue(BSLParser.LValueContext ctx) { private void checkCall(String mdoRef, Token methodName) { var methodNameText = Strings.trimQuotes(methodName.getText()); final var configuration = documentContext.getServerContext().getConfiguration(); - Map modules = configuration.getModulesByMDORef(mdoRef); + Map modules = configuration.mdoModuleTypes(mdoRef); for (ModuleType moduleType : modules.keySet()) { if (!DEFAULT_MODULE_TYPES.contains(moduleType) - || (moduleType == ModuleType.CommonModule && commonModuleMdoRefFromSubParams.contains(mdoRef))) { + || (moduleType == ModuleType.CommonModule && commonModuleMdoRefFromSubParams.contains(mdoRef))) { continue; } addMethodCall(mdoRef, moduleType, methodNameText, Ranges.create(methodName)); @@ -210,7 +206,7 @@ private void addMethodCall(String mdoRef, ModuleType moduleType, String methodNa private void addCallbackMethodCall(BSLParser.CallParamContext methodName, String mdoRef) { // todo: move this out of method - if (mdoRef.isEmpty()){ + if (mdoRef.isEmpty()) { return; } Methods.getMethodName(methodName).ifPresent((Token methodNameToken) -> { @@ -232,7 +228,7 @@ private String getModule(BSLParser.CallParamContext callParamContext) { .map(BSLParser.MemberContext::complexIdentifier) .filter(complexIdentifierContext -> complexIdentifierContext.IDENTIFIER() != null) .filter(complexIdentifierContext -> complexIdentifierContext.modifier().isEmpty()); - if (complexIdentifierContext1.isEmpty()){ + if (complexIdentifierContext1.isEmpty()) { return ""; } return complexIdentifierContext1 @@ -250,7 +246,7 @@ private Set calcParams(@Nullable BSLParser.ParamListContext paramList) { .map(BSLParser.ParamContext::IDENTIFIER) .filter(Objects::nonNull) .map(ParseTree::getText) - .map(configuration::getCommonModule) + .map(configuration::findCommonModule) .filter(Optional::isPresent) .flatMap(Optional::stream) .map(mdCommonModule -> mdCommonModule.getMdoReference().getMdoRef()) @@ -291,7 +287,7 @@ public BSLParserRuleContext visitSub(BSLParser.SubContext ctx) { .ifPresent(scope -> currentScope = scope); } - BSLParserRuleContext result = super.visitSub(ctx); + var result = super.visitSub(ctx); currentScope = documentContext.getSymbolTree().getModule(); return result; } @@ -324,7 +320,10 @@ public BSLParserRuleContext visitCallStatement(BSLParser.CallStatementContext ct var variableName = ctx.IDENTIFIER().getText(); findVariableSymbol(variableName) - .ifPresent(s -> addVariableUsage(s.getRootParent(SymbolKind.Method), variableName, Ranges.create(ctx.IDENTIFIER()), true)); + .ifPresent(s -> addVariableUsage( + s.getRootParent(SymbolKind.Method), variableName, Ranges.create(ctx.IDENTIFIER()), true + ) + ); return super.visitCallStatement(ctx); } @@ -336,7 +335,10 @@ public BSLParserRuleContext visitComplexIdentifier(BSLParser.ComplexIdentifierCo var variableName = ctx.IDENTIFIER().getText(); findVariableSymbol(variableName) - .ifPresent(s -> addVariableUsage(s.getRootParent(SymbolKind.Method), variableName, Ranges.create(ctx.IDENTIFIER()), true)); + .ifPresent(s -> addVariableUsage( + s.getRootParent(SymbolKind.Method), variableName, Ranges.create(ctx.IDENTIFIER()), true + ) + ); return super.visitComplexIdentifier(ctx); } @@ -396,7 +398,8 @@ private boolean notVariableInitialization(BSLParser.LValueContext ctx, VariableS return !Ranges.containsRange(variableSymbol.getRange(), Ranges.create(ctx)); } - private boolean notVariableInitialization(BSLParser.ModuleVarDeclarationContext ctx, VariableSymbol variableSymbol) { + private boolean notVariableInitialization(BSLParser.ModuleVarDeclarationContext ctx, + VariableSymbol variableSymbol) { return !Ranges.containsRange(variableSymbol.getRange(), Ranges.create(ctx)); } @@ -412,7 +415,7 @@ private void addVariableUsage(Optional methodSymbol, String variableName, Range range, boolean usage) { - String methodName = ""; + var methodName = ""; if (methodSymbol.isPresent()) { methodName = methodSymbol.get().getName(); @@ -428,7 +431,5 @@ private void addVariableUsage(Optional methodSymbol, !usage ); } - } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexReferenceFinder.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexReferenceFinder.java index a259a16b45f..ed7ad8e78f1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexReferenceFinder.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexReferenceFinder.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceResolver.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceResolver.java index c665ca2d221..e544f9ac085 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceResolver.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceResolver.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/SourceDefinedSymbolDeclarationReferenceFinder.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/SourceDefinedSymbolDeclarationReferenceFinder.java index d21f9e4bfc5..759f19db5a2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/SourceDefinedSymbolDeclarationReferenceFinder.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/SourceDefinedSymbolDeclarationReferenceFinder.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/Location.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/Location.java index 56254c17697..510265f37f2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/Location.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/Location.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/LocationRepository.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/LocationRepository.java index abe04f0659f..670cb0a03ec 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/LocationRepository.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/LocationRepository.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/OccurrenceType.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/OccurrenceType.java index 021066674c4..3b5acf2e34a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/OccurrenceType.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/OccurrenceType.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/Reference.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/Reference.java index 569e0132302..1b72ff3b7c2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/Reference.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/Reference.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/Symbol.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/Symbol.java index 54576ef3e4f..49b4ee582a6 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/Symbol.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/Symbol.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -26,7 +26,6 @@ import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Value; -import org.jetbrains.annotations.NotNull; import org.eclipse.lsp4j.SymbolKind; /** @@ -42,7 +41,7 @@ public class Symbol implements Comparable { private static GenericInterner interner = new GenericInterner<>(); /** - * Cсылка на объект метаданных в формате ВидОбъектаМетаданных.ИмяОбъекта, в котором расположен символ. + * Ссылка на объект метаданных в формате ВидОбъектаМетаданных.ИмяОбъекта, в котором расположен символ. */ String mdoRef; @@ -71,7 +70,7 @@ public Symbol intern() { } @Override - public int compareTo(@NotNull Symbol o) { + public int compareTo(Symbol o) { if (this.equals(o)) { return 0; } @@ -99,5 +98,4 @@ public int compareTo(@NotNull Symbol o) { compareResult = symbolName.compareTo(o.symbolName); return compareResult; } - } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/SymbolOccurrence.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/SymbolOccurrence.java index a0a62a297c1..7a9198110d3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/SymbolOccurrence.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/SymbolOccurrence.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -25,7 +25,6 @@ import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Value; -import org.jetbrains.annotations.NotNull; /** * Обращение к символу в файле. @@ -51,21 +50,21 @@ public class SymbolOccurrence implements Comparable { Location location; @Override - public int compareTo(@NotNull SymbolOccurrence o) { + public int compareTo(SymbolOccurrence o) { if (this.equals(o)) { return 0; } final var uriCompare = location.getUri().compareTo(o.location.getUri()); - if (uriCompare != 0){ + if (uriCompare != 0) { return uriCompare; } final var rangesCompare = Ranges.compare(location.getRange(), o.location.getRange()); - if (rangesCompare != 0){ + if (rangesCompare != 0) { return rangesCompare; } - final var occurenceCompare = occurrenceType.compareTo(o.occurrenceType); - if (occurenceCompare != 0){ - return occurenceCompare; + final var occurrenceCompare = occurrenceType.compareTo(o.occurrenceType); + if (occurrenceCompare != 0) { + return occurrenceCompare; } return symbol.compareTo(o.symbol); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/SymbolOccurrenceRepository.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/SymbolOccurrenceRepository.java index 72ce7d4e818..d56670324cb 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/SymbolOccurrenceRepository.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/SymbolOccurrenceRepository.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/package-info.java index 709aa73ae9d..f17fd0b4d6d 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/model/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,7 +22,8 @@ /** * DTO и хранилища данных индекса ссылок. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.references.model; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/package-info.java index a875e8bd46b..a79bdc6976a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/references/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,7 +22,8 @@ /** * Разрешение ссылок на символы. */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.references; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReportEntry.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReportEntry.java new file mode 100644 index 00000000000..9cb3965050b --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReportEntry.java @@ -0,0 +1,120 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.reporters; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.ToString; +import org.eclipse.lsp4j.Diagnostic; + +import java.util.Map; + +import static org.apache.commons.codec.digest.DigestUtils.sha256Hex; + +@Getter +@AllArgsConstructor +public class CodeQualityReportEntry { + + private static final Map SEVERITY_MAP = Map.of( + DiagnosticSeverity.BLOCKER, Severity.BLOCKER, + DiagnosticSeverity.CRITICAL, Severity.CRITICAL, + DiagnosticSeverity.MAJOR, Severity.MAJOR, + DiagnosticSeverity.MINOR, Severity.MINOR, + DiagnosticSeverity.INFO, Severity.INFO + ); + + /** + * A human-readable description of the code quality violation. + */ + private final String description; + + /** + * A unique name representing the check, or rule, associated with this violation. + */ + @JsonProperty("check_name") + private final String checkName; + + /** + * A unique fingerprint to identify this specific code quality violation, such as a hash of its contents. + */ + private final String fingerprint; + + /** + * The severity of the violation. + */ + private final Severity severity; + + private final Location location; + + public CodeQualityReportEntry(String path, Diagnostic diagnostic, DiagnosticInfo diagnosticInfo) { + this.description = diagnostic.getMessage(); + this.checkName = diagnosticInfo.getCode().getStringValue(); + var fingerprintData = path + "//" + this.checkName + "//" + diagnostic.getRange(); + this.fingerprint = sha256Hex(fingerprintData); + this.severity = SEVERITY_MAP.get(diagnosticInfo.getSeverity()); + this.location = new Location(); + this.location.path = path; + this.location.lines = new Lines(); + this.location.lines.begin = diagnostic.getRange().getStart().getLine() + 1; + } + + @Getter + @AllArgsConstructor + @NoArgsConstructor + @ToString + public static class Location { + + /** + * The file containing the code quality violation, expressed as a relative path in the repository. + */ + private String path; + private Lines lines; + } + + @Getter + @AllArgsConstructor + @NoArgsConstructor + @ToString + public static class Lines { + /** + * The line on which the code quality violation occurred (1-based). + */ + private int begin; + } + + public enum Severity { + @JsonProperty("blocker") + BLOCKER, + @JsonProperty("critical") + CRITICAL, + @JsonProperty("major") + MAJOR, + @JsonProperty("minor") + MINOR, + @JsonProperty("info") + INFO + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReporter.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReporter.java new file mode 100644 index 00000000000..92267ca3640 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReporter.java @@ -0,0 +1,82 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.reporters; + +import com.fasterxml.jackson.core.util.DefaultIndenter; +import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticCode; +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.reporters.data.AnalysisInfo; +import com.github._1c_syntax.bsl.languageserver.reporters.data.FileInfo; +import lombok.RequiredArgsConstructor; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.lsp4j.Diagnostic; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@Slf4j +@Component +@RequiredArgsConstructor +public class CodeQualityReporter implements DiagnosticReporter { + + private final Map diagnosticInfosByCode; + + @Override + public String key() { + return "code-quality"; + } + + @Override + @SneakyThrows + public void report(AnalysisInfo analysisInfo, Path outputDir) { + List report = new ArrayList<>(); + for (FileInfo fileInfo : analysisInfo.getFileinfos()) { + for (Diagnostic diagnostic : fileInfo.getDiagnostics()) { + var diagnosticInfo = diagnosticInfosByCode.get(DiagnosticCode.getStringValue(diagnostic.getCode())); + var path = fileInfo.getPath().toString().replace("\\", "/"); + var entry = new CodeQualityReportEntry(path, diagnostic, diagnosticInfo); + report.add(entry); + } + } + + var mapper = new ObjectMapper(); + mapper.enable(SerializationFeature.INDENT_OUTPUT); + + var indenter = new DefaultIndenter().withLinefeed("\n"); + var printer = new DefaultPrettyPrinter() + .withObjectIndenter(indenter); + ObjectWriter writer = mapper.writer(printer); + + var reportFile = new File(outputDir.toFile(), "./bsl-code-quality.json"); + writer.writeValue(reportFile, report); + LOGGER.info("CodeQuality report saved to {}", reportFile.getAbsolutePath()); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/ConsoleReporter.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/ConsoleReporter.java index df207af0f7b..f31e209f418 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/ConsoleReporter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/ConsoleReporter.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/DiagnosticReporter.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/DiagnosticReporter.java index becb34586d7..5c36b7ae0c9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/DiagnosticReporter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/DiagnosticReporter.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/GenericIssueReport.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/GenericIssueReport.java index bf192b60e92..f7b8c745032 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/GenericIssueReport.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/GenericIssueReport.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -26,12 +26,10 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType; import com.github._1c_syntax.bsl.languageserver.reporters.data.AnalysisInfo; -import com.github._1c_syntax.bsl.languageserver.reporters.data.FileInfo; import lombok.Getter; import lombok.Value; import org.eclipse.lsp4j.Diagnostic; import org.eclipse.lsp4j.DiagnosticRelatedInformation; -import org.eclipse.lsp4j.Position; import org.eclipse.lsp4j.Range; import java.net.URI; @@ -62,9 +60,9 @@ public GenericIssueReport( public GenericIssueReport(AnalysisInfo analysisInfo, Map diagnosticInfos) { issues = new ArrayList<>(); - for (FileInfo fileInfo : analysisInfo.getFileinfos()) { - for (Diagnostic diagnostic : fileInfo.getDiagnostics()) { - GenericIssueEntry entry = new GenericIssueEntry( + for (var fileInfo : analysisInfo.getFileinfos()) { + for (var diagnostic : fileInfo.getDiagnostics()) { + var entry = new GenericIssueEntry( fileInfo.getPath().toString(), diagnostic, diagnosticInfos.get(DiagnosticCode.getStringValue(diagnostic.getCode())) @@ -111,7 +109,7 @@ public GenericIssueEntry(String fileName, Diagnostic diagnostic, DiagnosticInfo primaryLocation = new Location(fileName, diagnostic); effortMinutes = diagnosticInfo.getMinutesToFix(); - List relatedInformation = diagnostic.getRelatedInformation(); + var relatedInformation = diagnostic.getRelatedInformation(); if (relatedInformation == null) { secondaryLocations = new ArrayList<>(); } else { @@ -172,8 +170,8 @@ public TextRange( } public TextRange(Range range) { - Position startPosition = range.getStart(); - Position endPosition = range.getEnd(); + var startPosition = range.getStart(); + var endPosition = range.getEnd(); startLine = startPosition.getLine() + 1; startColumn = startPosition.getCharacter(); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/GenericIssueReporter.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/GenericIssueReporter.java index 2d23e321654..c26c0633cdb 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/GenericIssueReporter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/GenericIssueReporter.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/JUnitReporter.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/JUnitReporter.java index 03406dca2cb..7215af10d3f 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/JUnitReporter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/JUnitReporter.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/JUnitTestSuites.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/JUnitTestSuites.java index 189c7586942..773631520a7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/JUnitTestSuites.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/JUnitTestSuites.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -39,13 +39,11 @@ import lombok.Value; import org.eclipse.lsp4j.Diagnostic; import org.eclipse.lsp4j.Position; -import org.eclipse.lsp4j.jsonrpc.messages.Either; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; -import java.util.Map; import java.util.stream.Collectors; @JacksonXmlRootElement(localName = "testsuites") @@ -66,7 +64,7 @@ public JUnitTestSuites(AnalysisInfo analysisInfo) { testsuite = analysisInfo.getFileinfos().stream() .filter(fileInfo -> !fileInfo.getDiagnostics().isEmpty()) .map(JUnitTestSuite::new) - .collect(Collectors.toList()); + .toList(); } public JUnitTestSuites( @@ -91,7 +89,7 @@ public JUnitTestSuite(FileInfo fileInfo) { this.testcase = new ArrayList<>(); List diagnostics = fileInfo.getDiagnostics(); - Map, List> groupedDiagnostics = diagnostics.stream() + var groupedDiagnostics = diagnostics.stream() .collect(Collectors.groupingBy( Diagnostic::getCode, Collectors.toList()) @@ -128,8 +126,8 @@ public JUnitTestCase(List diagnostics, String name, String classname this.classname = classname; List value = new ArrayList<>(); - String type = ""; - String message = ""; + var type = ""; + var message = ""; for (Diagnostic diagnostic : diagnostics) { type = diagnostic.getSeverity().toString().toLowerCase(Locale.ENGLISH); @@ -178,9 +176,9 @@ static class JUnitFailureDeserializer extends JsonDeserializer { public JUnitFailure deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode node = jp.getCodec().readTree(jp); - String type = node.get("type").asText(""); - String message = node.get("message").asText(""); - String value = node.get("").asText(""); + var type = node.get("type").asText(""); + var message = node.get("message").asText(""); + var value = node.get("").asText(""); return new JUnitFailure(type, message, value); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/JsonReporter.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/JsonReporter.java index d2e7b4b1796..456db8c9b85 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/JsonReporter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/JsonReporter.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/ReportersAggregator.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/ReportersAggregator.java index c7d4ce204a4..74c15dc4f05 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/ReportersAggregator.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/ReportersAggregator.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -37,13 +37,13 @@ public class ReportersAggregator { @Autowired - private final List reporters; + private List reporters; @Autowired @Qualifier("filteredReporters") @Lazy // Don't remove @Autowired annotation. It's needed for injecting filteredReporters bean correctly. - private final List filteredReporters; + private List filteredReporters; public void report(AnalysisInfo analysisInfo, Path outputDir) { filteredReporters.forEach(diagnosticReporter -> diagnosticReporter.report(analysisInfo, outputDir)); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/SarifReporter.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/SarifReporter.java index 321fed62b63..4f42460db1a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/SarifReporter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/SarifReporter.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/TSLintReportEntry.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/TSLintReportEntry.java index e259eabc5a2..a447d5ab0d6 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/TSLintReportEntry.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/TSLintReportEntry.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -30,27 +30,23 @@ import java.util.EnumMap; import java.util.Map; +@Getter class TSLintReportEntry { - @Getter + + private static final Map SEVERITY_MAP = new EnumMap<>(DiagnosticSeverity.class); + private final EntryPosition startPosition; - @Getter private final EntryPosition endPosition; - @Getter private final String failure; - @Getter private final String name; - @Getter private final String ruleName; - @Getter private final String ruleSeverity; - private static final Map severityMap = new EnumMap<>(DiagnosticSeverity.class); - static { - severityMap.put(DiagnosticSeverity.Error, "error"); - severityMap.put(DiagnosticSeverity.Hint, "warn"); - severityMap.put(DiagnosticSeverity.Information, "warn"); - severityMap.put(DiagnosticSeverity.Warning, "warn"); + SEVERITY_MAP.put(DiagnosticSeverity.Error, "error"); + SEVERITY_MAP.put(DiagnosticSeverity.Hint, "warn"); + SEVERITY_MAP.put(DiagnosticSeverity.Information, "warn"); + SEVERITY_MAP.put(DiagnosticSeverity.Warning, "warn"); } TSLintReportEntry(String fileName, Diagnostic diagnostic) { @@ -58,7 +54,7 @@ class TSLintReportEntry { failure = diagnostic.getMessage(); name = fileName; ruleName = DiagnosticCode.getStringValue(diagnostic.getCode()); - ruleSeverity = severityMap.get(diagnostic.getSeverity()); + ruleSeverity = SEVERITY_MAP.get(diagnostic.getSeverity()); startPosition = new EntryPosition(diagnostic.getRange().getStart()); } @@ -78,12 +74,10 @@ public TSLintReportEntry( this.ruleSeverity = ruleSeverity; } + @Getter static class EntryPosition { - @Getter private final int character; - @Getter private final int line; - @Getter private final int position; EntryPosition(org.eclipse.lsp4j.Position position) { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/TSLintReporter.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/TSLintReporter.java index 1003460a966..e8bdf99700e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/TSLintReporter.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/TSLintReporter.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/data/AnalysisInfo.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/data/AnalysisInfo.java index 3d8890b3185..60cbb34c428 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/data/AnalysisInfo.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/data/AnalysisInfo.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/data/FileInfo.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/data/FileInfo.java index 65e375d0b13..e71bd5c9f9e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/data/FileInfo.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/data/FileInfo.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,17 +24,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.context.MetricStorage; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; import com.github._1c_syntax.utils.Absolute; import lombok.AllArgsConstructor; import lombok.Value; import org.eclipse.lsp4j.Diagnostic; -import java.net.URI; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; -import java.util.Optional; @Value @AllArgsConstructor @@ -46,13 +43,13 @@ public class FileInfo { MetricStorage metrics; public FileInfo(String sourceDir, DocumentContext documentContext, List diagnostics) { - URI uri = documentContext.getUri(); + var uri = documentContext.getUri(); path = Absolute.path(sourceDir).relativize(Absolute.path(uri)); this.diagnostics = new ArrayList<>(diagnostics); metrics = documentContext.getMetrics(); - Optional mdObjectBase = documentContext.getMdObject(); - if (mdObjectBase.isPresent()) { - mdoRef = mdObjectBase.get().getMdoReference().getMdoRef(); + var mdo = documentContext.getMdObject(); + if (mdo.isPresent()) { + mdoRef = mdo.get().getMdoReference().getMdoRef(); } else { mdoRef = ""; } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/data/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/data/package-info.java index 9d7aa7b30b4..58ae255913b 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/data/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/data/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/AnalysisInfoObjectMapper.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/AnalysisInfoObjectMapper.java index a5a75830be8..77666fe4701 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/AnalysisInfoObjectMapper.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/AnalysisInfoObjectMapper.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/DiagnosticCodeDeserializer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/DiagnosticCodeDeserializer.java index d635402584d..23c9e63f4c4 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/DiagnosticCodeDeserializer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/DiagnosticCodeDeserializer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/DiagnosticCodeSerializer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/DiagnosticCodeSerializer.java index 226da02f4e0..28e7f478d13 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/DiagnosticCodeSerializer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/DiagnosticCodeSerializer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/DiagnosticMixIn.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/DiagnosticMixIn.java index 8b76cfc3ef8..8ee85435d0c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/DiagnosticMixIn.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/DiagnosticMixIn.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/package-info.java index 3622738237c..033cec6fab7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/databind/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/infrastructure/ReportersConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/infrastructure/ReportersConfiguration.java index 0eb876cdb90..ed5cb0f1d71 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/infrastructure/ReportersConfiguration.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/infrastructure/ReportersConfiguration.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/package-info.java index 38b09faf55c..88d0e687dc2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/reporters/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/AbstractObjectPool.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/AbstractObjectPool.java index f90c9c2103d..36917211af2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/AbstractObjectPool.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/AbstractObjectPool.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/DiagnosticHelper.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/DiagnosticHelper.java index d56a04b42af..627fb8a5965 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/DiagnosticHelper.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/DiagnosticHelper.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -30,7 +30,6 @@ import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; import org.antlr.v4.runtime.tree.Tree; -import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.HashSet; @@ -140,7 +139,7 @@ public static void configureDiagnostic(BSLDiagnostic diagnostic, * @param words Строка со словами * @return Созданный паттерн */ - public static Pattern createPatternFromString(@NotNull String words) { + public static Pattern createPatternFromString(String words) { return createPatternFromString(words, ","); } @@ -151,7 +150,7 @@ public static Pattern createPatternFromString(@NotNull String words) { * @param words Строка со словами * @return Созданный паттерн */ - public static Pattern createPatternFromString(@NotNull String words, String delimiter) { + public static Pattern createPatternFromString(String words, String delimiter) { StringJoiner stringJoiner = new StringJoiner("|"); for (String elem : words.split(delimiter)) { stringJoiner.add(Pattern.quote(elem.trim())); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Keywords.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Keywords.java index 9e755ba7f6a..bf7905fa1eb 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Keywords.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Keywords.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MdoRefBuilder.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MdoRefBuilder.java index ee24a7efe4b..b97259968d7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MdoRefBuilder.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MdoRefBuilder.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,20 +22,19 @@ package com.github._1c_syntax.bsl.languageserver.utils; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.mdo.CommonModule; +import com.github._1c_syntax.bsl.mdo.MD; +import com.github._1c_syntax.bsl.mdo.support.ScriptVariant; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.types.MDOType; import com.github._1c_syntax.bsl.types.MdoReference; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; -import com.github._1c_syntax.mdclasses.utils.MDOUtils; import com.github._1c_syntax.utils.StringInterner; +import edu.umd.cs.findbugs.annotations.Nullable; import lombok.experimental.UtilityClass; import org.antlr.v4.runtime.tree.ParseTree; import org.antlr.v4.runtime.tree.TerminalNode; -import javax.annotation.Nullable; -import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; @@ -55,7 +54,7 @@ public String getMdoRef(DocumentContext documentContext, BSLParser.CallStatement public static String getMdoRef(DocumentContext documentContext) { var mdoRef = documentContext.getMdObject() - .map(AbstractMDObjectBase::getMdoReference) + .map(MD::getMdoReference) .map(MdoReference::getMdoRef) .orElseGet(() -> documentContext.getUri().toString()); return stringInterner.intern(mdoRef); @@ -68,7 +67,7 @@ public String getMdoRef(DocumentContext documentContext, BSLParser.ComplexIdenti public String getMdoRef( DocumentContext documentContext, @Nullable - TerminalNode identifier, + TerminalNode identifier, List modifiers ) { @@ -81,8 +80,7 @@ public String getMdoRef( Optional.ofNullable(identifier) .map(ParseTree::getText) .flatMap(MDOType::fromValue) - .filter(mdoType -> MDOUtils.getModuleTypesForMdoTypes() - .getOrDefault(mdoType, Collections.emptySet()) + .filter(mdoType -> ModuleType.byMDOType(mdoType) .contains(ModuleType.ManagerModule)) .map(mdoType -> getMdoRef(mdoType, getMdoName(modifiers))) ) @@ -91,11 +89,44 @@ public String getMdoRef( return stringInterner.intern(mdoRef.get()); } + /** + * Получить mdoRef в языке конфигурации + * + * @param documentContext the document context + * @param mdo the mdo + * @return the locale mdoRef + */ + public String getLocaleMdoRef(DocumentContext documentContext, MD mdo) { + final var mdoReference = mdo.getMdoReference(); + final String result; + if (documentContext.getServerContext().getConfiguration().getScriptVariant() == ScriptVariant.ENGLISH) { + result = mdoReference.getMdoRef(); + } else { + result = mdoReference.getMdoRefRu(); + } + return stringInterner.intern(result); + } + + /** + * Получить имя родителя метаданного в языке конфигурации. + * + * @param documentContext the document context + * @param mdo the mdo + * @return the locale owner mdo name + */ + public String getLocaleOwnerMdoName(DocumentContext documentContext, MD mdo) { + final var names = getLocaleMdoRef(documentContext, mdo).split("\\."); + if (names.length <= 1) { + return ""; + } + return stringInterner.intern(names[0].concat(".").concat(names[1])); + } + private Optional getCommonModuleMdoRef(DocumentContext documentContext, String commonModuleName) { return documentContext.getServerContext() .getConfiguration() - .getCommonModule(commonModuleName) - .map(MDCommonModule::getMdoReference) + .findCommonModule(commonModuleName) + .map(CommonModule::getMdoReference) .map(MdoReference::getMdoRef); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Methods.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Methods.java index 626404e2b3e..0fed42a0080 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Methods.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Methods.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,6 +21,8 @@ */ package com.github._1c_syntax.bsl.languageserver.utils; +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import com.github._1c_syntax.bsl.languageserver.context.symbol.SymbolTree; import com.github._1c_syntax.bsl.parser.BSLParser; import lombok.experimental.UtilityClass; import org.antlr.v4.runtime.Token; @@ -82,4 +84,9 @@ public static Optional getMethodName(BSLParser.LValueContext lValueContex .flatMap(Methods::getMethodName); } + public static Optional getOscriptClassConstructor(SymbolTree symbolTree) { + return symbolTree.getMethodSymbol("ПриСозданииОбъекта") + .or(() -> symbolTree.getMethodSymbol("OnObjectCreate")); + } + } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Modules.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Modules.java index 4817e47c929..6defa1c2f80 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Modules.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Modules.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MultilingualStringAnalyser.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MultilingualStringAnalyser.java index 5b144711656..3082000cdb1 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MultilingualStringAnalyser.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/MultilingualStringAnalyser.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/NamedForkJoinWorkerThreadFactory.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/NamedForkJoinWorkerThreadFactory.java new file mode 100644 index 00000000000..e14ae169d92 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/NamedForkJoinWorkerThreadFactory.java @@ -0,0 +1,52 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.utils; + +import lombok.RequiredArgsConstructor; + +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.ForkJoinWorkerThread; +import java.util.concurrent.atomic.AtomicLong; + +/** + * Фабрика тредов для ForkJoinPool, автоматически добаляющая префикс к имени треда. + */ +@RequiredArgsConstructor +public class NamedForkJoinWorkerThreadFactory implements ForkJoinPool.ForkJoinWorkerThreadFactory { + + private static final AtomicLong index = new AtomicLong(); + + /** + * Префикс для добавления к имени треда. + */ + private final String prefix; + + /** + * {@inheritDoc} + */ + @Override + public ForkJoinWorkerThread newThread(ForkJoinPool pool) { + var worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool); + worker.setName(prefix + index.incrementAndGet()); + return worker; + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/NotifyDescription.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/NotifyDescription.java index 9881aab0741..d9f9431517e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/NotifyDescription.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/NotifyDescription.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Ranges.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Ranges.java index 867260ee033..82be119230e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Ranges.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Ranges.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -30,6 +30,8 @@ import org.antlr.v4.runtime.tree.TerminalNode; import org.eclipse.lsp4j.Position; import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.jsonrpc.util.Preconditions; +import org.eclipse.lsp4j.util.Positions; import java.util.Collection; import java.util.List; @@ -144,7 +146,11 @@ public boolean containsRange(Range bigger, Range smaller) { } public boolean containsPosition(Range range, Position position) { - return org.eclipse.lsp4j.util.Ranges.containsPosition(range, position); + Preconditions.checkNotNull(range, "range"); + Preconditions.checkNotNull(position, "position"); + return range.getStart().equals(position) + || (Positions.isBefore(range.getStart(), position) + && Positions.isBefore(position, range.getEnd())); } /** diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Regions.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Regions.java index 45a86e43df2..36535c201f9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Regions.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Regions.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/RelatedInformation.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/RelatedInformation.java index cb0d5800995..fca1b34aba3 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/RelatedInformation.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/RelatedInformation.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Resources.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Resources.java index 409770f7a3b..eac969f5b64 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Resources.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Resources.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,8 +22,10 @@ package com.github._1c_syntax.bsl.languageserver.utils; import com.github._1c_syntax.bsl.languageserver.configuration.Language; +import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.utils.StringInterner; -import lombok.experimental.UtilityClass; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; import java.util.Locale; import java.util.ResourceBundle; @@ -31,10 +33,32 @@ /** * Вспомогательный класс для оптимизированного чтения ресурсов прикладных классов с учетом {@link Language}. */ -@UtilityClass +@Component +@RequiredArgsConstructor public class Resources { - private final StringInterner stringInterner = new StringInterner(); + private static final StringInterner stringInterner = new StringInterner(); + + private final LanguageServerConfiguration configuration; + + /** + * @param clazz Класс, ресурсы которого необходимо прочитать. + * @param key Ключ из {@link ResourceBundle}. + * @return Содержимое ресурса. + */ + public String getResourceString(Class clazz, String key) { + return getResourceString(configuration.getLanguage().getLocale(), clazz, key); + } + + /** + * @param clazz Класс, ресурсы которого необходимо прочитать. + * @param key Ключ из {@link ResourceBundle}. + * @param args Аргументы для форматирования ресурсной строки. + * @return Содержимое ресурса. + */ + public String getResourceString(Class clazz, String key, Object... args) { + return getResourceString(configuration.getLanguage().getLocale(), clazz, key, args); + } /** * @param language Язык получения ресурсной строки. @@ -42,7 +66,7 @@ public class Resources { * @param key Ключ из {@link ResourceBundle}. * @return Содержимое ресурса. */ - public String getResourceString(Language language, Class clazz, String key) { + public static String getResourceString(Language language, Class clazz, String key) { return getResourceString(language.getLocale(), clazz, key); } @@ -52,7 +76,7 @@ public String getResourceString(Language language, Class clazz, String key) { * @param key Ключ из {@link ResourceBundle}. * @return Содержимое ресурса. */ - public String getResourceString(Locale locale, Class clazz, String key) { + public static String getResourceString(Locale locale, Class clazz, String key) { var resourceString = ResourceBundle.getBundle(clazz.getName(), locale, new UTF8Control()).getString(key); return stringInterner.intern(resourceString); } @@ -64,7 +88,7 @@ public String getResourceString(Locale locale, Class clazz, String key) { * @param args Аргументы для форматирования ресурсной строки. * @return Содержимое ресурса. */ - public String getResourceString(Language language, Class clazz, String key, Object... args) { + public static String getResourceString(Language language, Class clazz, String key, Object... args) { return getResourceString(language.getLocale(), clazz, key, args); } @@ -75,7 +99,7 @@ public String getResourceString(Language language, Class clazz, String key, O * @param args Аргументы для форматирования ресурсной строки. * @return Содержимое ресурса. */ - public String getResourceString(Locale locale, Class clazz, String key, Object... args) { + public static String getResourceString(Locale locale, Class clazz, String key, Object... args) { var resourceString = String.format(getResourceString(locale, clazz, key), args); return stringInterner.intern(resourceString); } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Strings.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Strings.java index 5a2391fc78e..5be79f26cff 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Strings.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Strings.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/ThrowingSupplier.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/ThrowingSupplier.java index cac916617e5..0d775c5adf5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/ThrowingSupplier.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/ThrowingSupplier.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java index 29fc428fa20..78876ebab6a 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/Trees.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,6 +23,7 @@ import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserRuleContext; +import edu.umd.cs.findbugs.annotations.Nullable; import lombok.experimental.UtilityClass; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.Token; @@ -32,7 +33,6 @@ import org.eclipse.lsp4j.Position; import org.eclipse.lsp4j.util.Positions; -import javax.annotation.CheckForNull; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -82,12 +82,11 @@ public static List getChildren(Tree t) { * @return Список токенов */ public static List getTokens(ParseTree tree) { - if (tree instanceof BSLParserRuleContext) { - return ((BSLParserRuleContext) tree).getTokens(); + if (tree instanceof BSLParserRuleContext parserRuleContext) { + return parserRuleContext.getTokens(); } - if (tree instanceof TerminalNode) { - TerminalNode node = (TerminalNode) tree; + if (tree instanceof TerminalNode node) { var token = node.getSymbol(); return List.of(token); } @@ -104,8 +103,7 @@ public static List getTokens(ParseTree tree) { private static void getTokensFromParseTree(ParseTree tree, List tokens) { for (var i = 0; i < tree.getChildCount(); i++) { ParseTree child = tree.getChild(i); - if (child instanceof TerminalNode) { - TerminalNode node = (TerminalNode) child; + if (child instanceof TerminalNode node) { var token = node.getSymbol(); tokens.add(token); } else { @@ -138,8 +136,8 @@ private static void flatten(ParseTree t, List flatList) { */ private static int getRuleIndex(ParseTree node) { - if (node instanceof TerminalNode) { - return ((TerminalNode) node).getSymbol().getType(); + if (node instanceof TerminalNode terminalNode) { + return terminalNode.getSymbol().getType(); } else { return ((BSLParserRuleContext) node).getRuleIndex(); } @@ -153,9 +151,8 @@ private static List getDescendantsWithFilter(ParseTree parent, ParseT descendants = org.antlr.v4.runtime.tree.Trees.getDescendants(parent) .stream() .filter(BSLParserRuleContext.class::isInstance) - .filter(node -> (node.equals(tnc) - || getRuleIndex(node) == ruleindex)) - .collect(Collectors.toList()); + .filter(node -> (node.equals(tnc) || getRuleIndex(node) == ruleindex)) + .toList(); } return descendants; } @@ -165,7 +162,7 @@ private static List getDescendantsWithFilter(ParseTree parent, ParseT * Пример: * BSLParserRuleContext parent = Trees.getAncestorByRuleIndex(ctx, BSLParser.RULE_statement); */ - @CheckForNull + @Nullable public static BSLParserRuleContext getAncestorByRuleIndex(BSLParserRuleContext element, int type) { var parent = element.getParent(); if (parent == null) { @@ -204,14 +201,11 @@ public static boolean nodeContainsErrors(ParseTree tnc) { * @return tnc - если предыдущая нода не найдена, вернет текущую */ public static ParseTree getPreviousNode(ParseTree parent, ParseTree tnc, int ruleindex) { - List descendants = getDescendantsWithFilter(parent, tnc, ruleindex); - int pos = descendants.indexOf(tnc); if (pos > 0) { return descendants.get(pos - 1); } - return tnc; } @@ -266,14 +260,11 @@ public static Optional getPreviousTokenFromDefaultChannel(List tok * @return tnc - если следующая нода не найдена, вернет текущую */ public static ParseTree getNextNode(ParseTree parent, ParseTree tnc, int ruleindex) { - List descendants = getDescendantsWithFilter(parent, tnc, ruleindex); - int pos = descendants.indexOf(tnc); if (pos + 1 < descendants.size()) { return descendants.get(pos + 1); } - return tnc; } @@ -284,7 +275,6 @@ public static BSLParserRuleContext getRootParent(BSLParserRuleContext tnc) { if (tnc.getParent() != null) { return getRootParent(tnc.getParent()); } - return tnc; } @@ -295,7 +285,7 @@ public static BSLParserRuleContext getRootParent(BSLParserRuleContext tnc) { * @param ruleindex - BSLParser.RULE_* * @return tnc - если родитель не найден, вернет null */ - @CheckForNull + @Nullable public static BSLParserRuleContext getRootParent(BSLParserRuleContext tnc, int ruleindex) { final var parent = tnc.getParent(); if (parent == null) { @@ -316,7 +306,7 @@ public static BSLParserRuleContext getRootParent(BSLParserRuleContext tnc, int r * @param indexes - Collection of BSLParser.RULE_* * @return tnc - если родитель не найден, вернет null */ - @CheckForNull + @Nullable public static BSLParserRuleContext getRootParent(BSLParserRuleContext tnc, Collection indexes) { final var parent = tnc.getParent(); if (parent == null) { @@ -354,9 +344,7 @@ private static Stream getChildrenStream(Tree t, Integer[] List indexes = Arrays.asList(ruleIndex); return IntStream.range(0, t.getChildCount()) .mapToObj(t::getChild) - .filter((Tree child) -> - child instanceof BSLParserRuleContext - && indexes.contains(((BSLParserRuleContext) child).getRuleIndex())) + .filter(child -> child instanceof BSLParserRuleContext rule && indexes.contains(rule.getRuleIndex())) .map(BSLParserRuleContext.class::cast); } @@ -364,29 +352,67 @@ private static Stream getChildrenStream(Tree t, Integer[] * Получает дочерние ноды с нужными типами */ public static Collection findAllRuleNodes(ParseTree t, Integer... index) { + return findAllRuleNodes(t, Arrays.asList(index)); + } + + /** + * Получает дочерние ноды с нужными типами + */ + public static Collection findAllRuleNodes(ParseTree t, Collection indexes) { List nodes = new ArrayList<>(); - List indexes = Arrays.asList(index); - if (t instanceof ParserRuleContext - && indexes.contains(((ParserRuleContext) t).getRuleIndex())) { + if (t instanceof ParserRuleContext parserRuleContext && indexes.contains(parserRuleContext.getRuleIndex())) { nodes.add((ParserRuleContext) t); } IntStream.range(0, t.getChildCount()) - .mapToObj(i -> findAllRuleNodes(t.getChild(i), index)) + .mapToObj(i -> findAllRuleNodes(t.getChild(i), indexes)) .forEachOrdered(nodes::addAll); return nodes; } + /** + * Получает "первые" дочерние ноды с нужными типами + * ВАЖНО: поиск вглубь найденной ноды с нужными индексами не выполняется + * Например, если указать RULE_codeBlock, то найдется только самый верхнеуровневый блок кода, все + * вложенные найдены не будут + * ВАЖНО: начальная нода не проверяется на условие, т.к. тогда она единственная и вернется в результате + * + * @param root - начальный узел дерева + * @param indexes - коллекция индексов + * @return найденные узлы + */ + public static Collection findAllTopLevelDescendantNodes(ParserRuleContext root, + Collection indexes) { + var result = new ArrayList(); + root.children.stream() + .map(node -> findAllTopLevelDescendantNodesInner(node, indexes)) + .forEach(result::addAll); + return result; + } + + private static Collection findAllTopLevelDescendantNodesInner(ParseTree root, + Collection indexes) { + if (root instanceof ParserRuleContext rule && indexes.contains(rule.getRuleIndex())) { + return List.of(rule); + } + + List result = new ArrayList<>(); + IntStream.range(0, root.getChildCount()) + .mapToObj(i -> findAllTopLevelDescendantNodesInner(root.getChild(i), indexes)) + .forEachOrdered(result::addAll); + + return result; + } + /** * Проверяет наличие дочерней ноды с указанным типом */ public static boolean nodeContains(ParseTree t, Integer... index) { Set indexes = new HashSet<>(Arrays.asList(index)); - if (t instanceof ParserRuleContext - && indexes.contains(((ParserRuleContext) t).getRuleIndex())) { + if (t instanceof ParserRuleContext rule && indexes.contains(rule.getRuleIndex())) { return true; } @@ -400,9 +426,7 @@ public static boolean nodeContains(ParseTree t, Integer... index) { public static boolean nodeContains(ParseTree t, ParseTree exclude, Integer... index) { Set indexes = new HashSet<>(Arrays.asList(index)); - if (t instanceof ParserRuleContext - && !t.equals(exclude) - && indexes.contains(((ParserRuleContext) t).getRuleIndex())) { + if (t instanceof ParserRuleContext rule && !t.equals(exclude) && indexes.contains(rule.getRuleIndex())) { return true; } @@ -413,11 +437,12 @@ public static boolean nodeContains(ParseTree t, ParseTree exclude, Integer... in /** * Получение ноды в дереве по позиции в документе. * - * @param tree - дерево, в котором ищем + * @param tree - дерево, в котором ищем * @param position - искомая позиция * @return терминальная нода на указанной позиции, если есть */ - public static Optional findTerminalNodeContainsPosition(BSLParserRuleContext tree, Position position) { + public static Optional findTerminalNodeContainsPosition(BSLParserRuleContext tree, + Position position) { if (tree.getTokens().isEmpty()) { return Optional.empty(); @@ -433,8 +458,7 @@ public static Optional findTerminalNodeContainsPosition(BSLParserR var children = Trees.getChildren(tree); for (Tree child : children) { - if (child instanceof TerminalNode) { - var terminalNode = (TerminalNode) child; + if (child instanceof TerminalNode terminalNode) { var token = terminalNode.getSymbol(); if (tokenContainsPosition(token, position)) { return Optional.of(terminalNode); @@ -490,15 +514,12 @@ public static List getComments(List tokens, Token token) { } private static void fillCommentsCollection(List tokens, Token currentToken, List lines) { - int index = currentToken.getTokenIndex(); - if (index == 0) { return; } var previousToken = tokens.get(index - 1); - if (abortSearchComments(previousToken, currentToken)) { return; } @@ -522,12 +543,10 @@ private static boolean isBlankLine(Token previousToken, Token currentToken) { } private static boolean treeContainsErrors(ParseTree tnc, boolean recursive) { - if (!(tnc instanceof BSLParserRuleContext)) { + if (!(tnc instanceof BSLParserRuleContext ruleContext)) { return false; } - BSLParserRuleContext ruleContext = (BSLParserRuleContext) tnc; - if (ruleContext.exception != null) { return true; } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/UTF8Control.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/UTF8Control.java index 6fdf964bcbe..566540f0f29 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/UTF8Control.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/UTF8Control.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/bsl/Constructors.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/bsl/Constructors.java new file mode 100644 index 00000000000..cea788b8735 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/bsl/Constructors.java @@ -0,0 +1,72 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.utils.bsl; + +import com.github._1c_syntax.bsl.languageserver.utils.Strings; +import com.github._1c_syntax.bsl.parser.BSLParser; +import lombok.experimental.UtilityClass; +import org.antlr.v4.runtime.RuleContext; + +import java.util.List; +import java.util.Optional; + +/** + * Набор методов для работы с конструкторами объектов 1С + */ +@UtilityClass +public class Constructors { + + /** + * Вычисляет имя типа создаваемого объекта, работает с + * Новый ТипОбъекта; + * Новый("ТипОбъекта") + * @param newExpression контекст выражения + * @return имя типа объекта + */ + public static Optional typeName(BSLParser.NewExpressionContext newExpression) { + return Optional.ofNullable(newExpression.typeName()) + .map(RuleContext::getText) + .or(() -> getTypeNameFromArgs(newExpression)); + } + + private static Optional getTypeNameFromArgs(BSLParser.NewExpressionContext newExpression){ + return Optional.ofNullable(newExpression.doCall()) + .map(BSLParser.DoCallContext::callParamList) + .map(BSLParser.CallParamListContext::callParam) + .flatMap(Constructors::first) + .map(BSLParser.CallParamContext::expression) + .map(BSLParser.ExpressionContext::member) + .flatMap(Constructors::first) + .map(BSLParser.MemberContext::constValue) + .filter(constValue -> constValue.string() != null) + .map(RuleContext::getText) + .map(Strings::trimQuotes); + } + + private static Optional first(List list) { + if (list.isEmpty()) { + return Optional.empty(); + } else { + return Optional.of(list.get(0)); + } + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/AbstractCallNode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/AbstractCallNode.java index 62661cd99b5..f3d5b452357 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/AbstractCallNode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/AbstractCallNode.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BinaryOperationNode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BinaryOperationNode.java index 8f4b781b850..cdd479ae6e7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BinaryOperationNode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BinaryOperationNode.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,16 +22,16 @@ package com.github._1c_syntax.bsl.languageserver.utils.expressiontree; import lombok.EqualsAndHashCode; +import lombok.Getter; import lombok.ToString; -import lombok.Value; import org.antlr.v4.runtime.tree.ParseTree; -@Value +@Getter @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class BinaryOperationNode extends BslOperationNode { - BslExpression left; - BslExpression right; + private final BslExpression left; + private final BslExpression right; private BinaryOperationNode(BslOperator operator, BslExpression left, BslExpression right, ParseTree actualSourceCode) { super(ExpressionNodeType.BINARY_OP, operator, actualSourceCode); diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BslExpression.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BslExpression.java index 88251bb9e18..21c4e076e74 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BslExpression.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BslExpression.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,18 +24,22 @@ import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Data; -import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; +import lombok.Setter; +import lombok.ToString; import org.antlr.v4.runtime.tree.ParseTree; @Data @RequiredArgsConstructor(access = AccessLevel.PROTECTED) @AllArgsConstructor(access = AccessLevel.PROTECTED) -@NoArgsConstructor(access = AccessLevel.PRIVATE, force = true) public abstract class BslExpression { private final ExpressionNodeType nodeType; private ParseTree representingAst; + @ToString.Exclude + @Setter(AccessLevel.PACKAGE) + private BslExpression parent; + /** * Синтаксический-помощник для более удобных downcast-ов * @param тип, к которому надо привести данный узел diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BslOperationNode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BslOperationNode.java index ef0a2afe4df..a43264240b4 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BslOperationNode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BslOperationNode.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -36,7 +36,7 @@ public abstract class BslOperationNode extends BslExpression { BslOperator operator; protected BslOperationNode(ExpressionNodeType type, BslOperator operator, ParseTree sourceCodeOperator) { - super(type, sourceCodeOperator); + super(type, sourceCodeOperator, null); this.operator = operator; } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BslOperator.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BslOperator.java index 2c2485f18d5..7aec2ce02de 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BslOperator.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/BslOperator.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ConstructorCallNode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ConstructorCallNode.java index 7ac4b0578f3..8618e3c84a8 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ConstructorCallNode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ConstructorCallNode.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/DefaultNodeEqualityComparer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/DefaultNodeEqualityComparer.java index 9f299a1d4d3..ed8d2b95125 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/DefaultNodeEqualityComparer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/DefaultNodeEqualityComparer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -40,30 +40,22 @@ public boolean areEqual(BslExpression first, BslExpression second) { return false; } - switch (first.getNodeType()) { - case LITERAL: - return literalsEqual((TerminalSymbolNode) first, (TerminalSymbolNode) second); - case IDENTIFIER: - return identifiersEqual((TerminalSymbolNode) first, (TerminalSymbolNode) second); - case BINARY_OP: - return binaryOperationsEqual((BinaryOperationNode) first, (BinaryOperationNode) second); - case UNARY_OP: - return unaryOperationsEqual((UnaryOperationNode) first, (UnaryOperationNode) second); - case TERNARY_OP: - return ternaryOperatorsEqual((TernaryOperatorNode) first, (TernaryOperatorNode) second); - case SKIPPED_CALL_ARG: - return true; - case CALL: - return callStatementsEqual((AbstractCallNode) first, (AbstractCallNode) second); - default: - throw new IllegalStateException(); - } + return switch (first.getNodeType()) { + case LITERAL -> literalsEqual((TerminalSymbolNode) first, (TerminalSymbolNode) second); + case IDENTIFIER -> identifiersEqual((TerminalSymbolNode) first, (TerminalSymbolNode) second); + case BINARY_OP -> binaryOperationsEqual((BinaryOperationNode) first, (BinaryOperationNode) second); + case UNARY_OP -> unaryOperationsEqual((UnaryOperationNode) first, (UnaryOperationNode) second); + case TERNARY_OP -> ternaryOperatorsEqual((TernaryOperatorNode) first, (TernaryOperatorNode) second); + case SKIPPED_CALL_ARG -> true; + case CALL -> callStatementsEqual((AbstractCallNode) first, (AbstractCallNode) second); + default -> throw new IllegalStateException(); + }; } protected boolean callStatementsEqual(AbstractCallNode first, AbstractCallNode second) { - if (first instanceof MethodCallNode) { - return methodCallsEqual((MethodCallNode) first, (MethodCallNode) second); + if (first instanceof MethodCallNode methodCallNode) { + return methodCallsEqual(methodCallNode, (MethodCallNode) second); } else { return constructorCallsEqual((ConstructorCallNode) first, (ConstructorCallNode) second); } @@ -94,9 +86,9 @@ protected boolean methodCallsEqual(MethodCallNode first, MethodCallNode second) } protected boolean ternaryOperatorsEqual(TernaryOperatorNode first, TernaryOperatorNode second) { - return areEqual(first.getCondition(), second.getCondition()) && - areEqual(first.getTruePart(), second.getTruePart()) && - areEqual(first.getFalsePart(), second.getFalsePart()); + return areEqual(first.getCondition(), second.getCondition()) + && areEqual(first.getTruePart(), second.getTruePart()) + && areEqual(first.getFalsePart(), second.getFalsePart()); } protected boolean unaryOperationsEqual(UnaryOperationNode first, UnaryOperationNode second) { @@ -117,7 +109,6 @@ protected boolean binaryOperationsEqual(BinaryOperationNode first, BinaryOperati } return areEqual(first.getLeft(), second.getLeft()) && areEqual(first.getRight(), second.getRight()); - } protected boolean identifiersEqual(TerminalSymbolNode first, TerminalSymbolNode second) { diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionNodeType.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionNodeType.java index effb8396792..c4761894561 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionNodeType.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionNodeType.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeBuildingVisitor.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeBuildingVisitor.java index 5e826fad36e..2aef501691c 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeBuildingVisitor.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeBuildingVisitor.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -20,6 +20,7 @@ * License along with BSL Language Server. */ package com.github._1c_syntax.bsl.languageserver.utils.expressiontree; + import com.github._1c_syntax.bsl.parser.BSLLexer; import com.github._1c_syntax.bsl.parser.BSLParser; import com.github._1c_syntax.bsl.parser.BSLParserBaseVisitor; @@ -31,13 +32,13 @@ import java.util.Collections; import java.util.Deque; import java.util.List; -import java.util.stream.Collectors; +import java.util.Objects; /** - * внутренний, неэкспортируемый класс. + * Посетитель AST, который находит выражения и преобразует их в Expression Tree */ -class ExpressionTreeBuildingVisitor extends BSLParserBaseVisitor { +public final class ExpressionTreeBuildingVisitor extends BSLParserBaseVisitor { @Value private static class OperatorInCode { @@ -55,6 +56,18 @@ public int getPriority() { private BslExpression resultExpression; private int recursionLevel = -1; + /** + * Хелпер построения дерева выражения на основе готового AST выражения + * + * @param ctx AST выражения + * @return дерево вычисления выражения + */ + public static BslExpression buildExpressionTree(BSLParser.ExpressionContext ctx) { + var instance = new ExpressionTreeBuildingVisitor(); + instance.visitExpression(ctx); + return instance.getExpressionTree(); + } + /** * @return результирующее выражение в виде дерева вычисления операций */ @@ -97,7 +110,11 @@ public ParseTree visitExpression(BSLParser.ExpressionContext ctx) { } var operation = operands.peek(); - assert operation != null; // для спокойствия сонара + // В случае ошибок парсинга выражения, operation может быть null + if (operation == null) { + recursionLevel--; + return ctx; + } if (operation.getRepresentingAst() == null) { operation.setRepresentingAst(ctx); @@ -114,12 +131,18 @@ public ParseTree visitExpression(BSLParser.ExpressionContext ctx) { @Override public ParseTree visitMember(BSLParser.MemberContext ctx) { + // В случае ошибки парсинга member может быть пустой. + if (ctx.getChildCount() == 0) { + return ctx; + } + // нужен ручной dispatch на конкретного child, // т.к. нет отдельного правила для подвыражения в скобках // constValue - // | complexIdentifier - // | (( LPAREN expression RPAREN ) modifier*) // нечего оверрайдить ! - // | (WAIT_KEYWORD (IDENTIFIER | globalMethodCall)) + // | complexIdentifier + // | (( LPAREN expression RPAREN ) modifier*) // нечего оверрайдить ! + // | (IDENTIFIER | globalMethodCall) // нечего оверрайдить ! + // | waitExpression var unaryModifier = ctx.unaryModifier(); var childIndex = 0; @@ -128,34 +151,31 @@ public ParseTree visitMember(BSLParser.MemberContext ctx) { childIndex = 1; } + if (ctx.waitExpression() != null) { + return visitWaitExpression(ctx.waitExpression()); + } + var dispatchChild = ctx.getChild(childIndex); - if (dispatchChild instanceof TerminalNode) { - var token = ((TerminalNode) dispatchChild).getSymbol().getType(); + if (dispatchChild instanceof TerminalNode terminalNode) { + var token = terminalNode.getSymbol().getType(); // ручная диспетчеризация switch (token) { case BSLLexer.LPAREN: visitParenthesis(ctx.expression(), ctx.modifier()); break; - case BSLLexer.AWAIT_KEYWORD: - visitAwaitedMember(ctx.getChild(childIndex + 1)); - break; default: throw new IllegalStateException("Unexpected rule " + dispatchChild); } - } else { dispatchChild.accept(this); } - if (unaryModifier != null) { - buildOperation(); - } - return ctx; } - private void visitParenthesis(BSLParser.ExpressionContext expression, List modifiers) { + private void visitParenthesis(BSLParser.ExpressionContext expression, + List modifiers) { var subExpr = makeSubexpression(expression); operands.push(subExpr); @@ -163,7 +183,6 @@ private void visitParenthesis(BSLParser.ExpressionContext expression, List operator.getPriority()) { + while (hasHigherPriorityOperatorsInFly(operator)) { buildOperation(); } operatorsInFly.push(operator); } + private boolean hasHigherPriorityOperatorsInFly(OperatorInCode operator) { + var lastSeenOperator = operatorsInFly.peek(); + if (lastSeenOperator == null) { + return false; + } + + return lastSeenOperator.getPriority() > operator.getPriority(); + } + private static BslOperator getOperator(BSLParser.OperationContext ctx) { if (ctx.PLUS() != null) { return BslOperator.ADD; @@ -236,7 +260,6 @@ private static BslOperator getOperator(BSLParser.OperationContext ctx) { @Override public ParseTree visitConstValue(BSLParser.ConstValueContext ctx) { - var node = TerminalSymbolNode.literal(ctx); operands.push(node); return ctx; @@ -247,21 +270,12 @@ public ParseTree visitUnaryModifier(BSLParser.UnaryModifierContext ctx) { var child = (TerminalNode) ctx.getChild(0); var token = (child).getSymbol().getType(); - BslOperator operator; - - switch (token) { - case BSLLexer.PLUS: - operator = BslOperator.UNARY_PLUS; - break; - case BSLLexer.MINUS: - operator = BslOperator.UNARY_MINUS; - break; - case BSLLexer.NOT_KEYWORD: - operator = BslOperator.NOT; - break; - default: - throw new IllegalArgumentException(); - } + var operator = switch (token) { + case BSLLexer.PLUS -> BslOperator.UNARY_PLUS; + case BSLLexer.MINUS -> BslOperator.UNARY_MINUS; + case BSLLexer.NOT_KEYWORD -> BslOperator.NOT; + default -> throw new IllegalArgumentException(); + }; operatorsInFly.push(new OperatorInCode(operator, child)); @@ -287,7 +301,6 @@ public ParseTree visitComplexIdentifier(BSLParser.ComplexIdentifierContext ctx) @Override public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) { - var name = ctx.methodName().IDENTIFIER(); var callNode = MethodCallNode.create(name); callNode.setRepresentingAst(ctx); @@ -314,7 +327,7 @@ public ParseTree visitNewExpression(BSLParser.NewExpressionContext ctx) { if (typeName == null) { // function style var typeNameArg = args.get(0); - args = args.stream().skip(1).collect(Collectors.toList()); + args = args.stream().skip(1).toList(); callNode = ConstructorCallNode.createDynamic(makeSubexpression(typeNameArg.expression())); } else { // static style @@ -323,9 +336,7 @@ public ParseTree visitNewExpression(BSLParser.NewExpressionContext ctx) { } callNode.setRepresentingAst(ctx); - addCallArguments(callNode, args); - operands.push(callNode); return ctx; } @@ -345,9 +356,7 @@ public ParseTree visitAccessProperty(BSLParser.AccessPropertyContext ctx) { @Override public ParseTree visitAccessIndex(BSLParser.AccessIndexContext ctx) { var target = operands.pop(); - var expressionArg = makeSubexpression(ctx.expression()); - var indexOperation = BinaryOperationNode.create(BslOperator.INDEX_ACCESS, target, expressionArg, ctx); operands.push(indexOperation); return ctx; @@ -366,7 +375,6 @@ public ParseTree visitAccessCall(BSLParser.AccessCallContext ctx) { @Override public ParseTree visitTernaryOperator(BSLParser.TernaryOperatorContext ctx) { - var ternary = TernaryOperatorNode.create( makeSubexpression(ctx.expression(0)), makeSubexpression(ctx.expression(1)), @@ -380,11 +388,11 @@ public ParseTree visitTernaryOperator(BSLParser.TernaryOperatorContext ctx) { } private static BslExpression makeSubexpression(BSLParser.ExpressionContext ctx) { - return ExpressionParseTreeRewriter.buildExpressionTree(ctx); + return buildExpressionTree(ctx); } private static void addCallArguments(AbstractCallNode callNode, List args) { - for (BSLParser.CallParamContext parameter : args) { + for (var parameter : args) { if (parameter.expression() == null) { callNode.addArgument(new SkippedCallArgumentNode()); } else { @@ -399,19 +407,23 @@ private void buildOperation() { } var operator = operatorsInFly.pop(); - switch (operator.getOperator()) { - case UNARY_MINUS: - case UNARY_PLUS: - case NOT: - var operand = operands.pop(); - var operation = UnaryOperationNode.create(operator.getOperator(), operand, operator.getActualSourceCode()); - operands.push(operation); - break; - default: - var right = operands.pop(); - var left = operands.pop(); - var binaryOp = BinaryOperationNode.create(operator.getOperator(), left, right, operator.getActualSourceCode()); - operands.push(binaryOp); + if (Objects.requireNonNull(operator.getOperator()) == BslOperator.UNARY_MINUS + || operator.getOperator() == BslOperator.NOT + || operator.getOperator() == BslOperator.UNARY_PLUS) { + + var operand = operands.pop(); + var operation = UnaryOperationNode.create(operator.getOperator(), operand, operator.getActualSourceCode()); + operand.setParent(operation); + operands.push(operation); + } else { + var right = operands.pop(); + var left = operands.pop(); + var binaryOp = BinaryOperationNode.create(operator.getOperator(), left, right, operator.getActualSourceCode()); + + left.setParent(binaryOp); + right.setParent(binaryOp); + + operands.push(binaryOp); } } } diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeVisitor.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeVisitor.java new file mode 100644 index 00000000000..43306fd2bf0 --- /dev/null +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/ExpressionTreeVisitor.java @@ -0,0 +1,74 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.utils.expressiontree; + +/** + * Обходчик дерева выражений + */ +public class ExpressionTreeVisitor { + + private void visit(BslExpression node) { + switch (node.getNodeType()) { + case CALL: + visitAbstractCall((AbstractCallNode) node); + break; + case UNARY_OP: + visitUnaryOperation((UnaryOperationNode) node); + break; + case TERNARY_OP: + var ternary = (TernaryOperatorNode) node; + visitTernaryOperator(ternary); + break; + case BINARY_OP: + visitBinaryOperation((BinaryOperationNode)node); + break; + + default: + break; // для спокойствия сонара + } + } + + protected void visitTopLevelExpression(BslExpression node) { + visit(node); + } + + protected void visitAbstractCall(AbstractCallNode node) { + for (var expr : node.arguments()) { + visit(expr); + } + } + + protected void visitUnaryOperation(UnaryOperationNode node) { + visit(node.getOperand()); + } + + protected void visitBinaryOperation(BinaryOperationNode node) { + visit(node.getLeft()); + visit(node.getRight()); + } + + protected void visitTernaryOperator(TernaryOperatorNode node) { + visit(node.getCondition()); + visit(node.getTruePart()); + visit(node.getFalsePart()); + } +} diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/MethodCallNode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/MethodCallNode.java index e71bd769c38..e75cf0ea1d5 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/MethodCallNode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/MethodCallNode.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/NodeEqualityComparer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/NodeEqualityComparer.java index 4bb42a0b4c6..e00306cbf9e 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/NodeEqualityComparer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/NodeEqualityComparer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/SkippedCallArgumentNode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/SkippedCallArgumentNode.java index 6aa603ea243..2a82de601a7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/SkippedCallArgumentNode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/SkippedCallArgumentNode.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/TerminalSymbolNode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/TerminalSymbolNode.java index 97d0fed59c5..60d2ad832e2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/TerminalSymbolNode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/TerminalSymbolNode.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -30,7 +30,7 @@ */ public class TerminalSymbolNode extends BslExpression { private TerminalSymbolNode(ExpressionNodeType type, ParseTree representingAst) { - super(type, representingAst); + super(type, representingAst, null); } /** diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/TernaryOperatorNode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/TernaryOperatorNode.java index 10429a442a6..268ffeafe85 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/TernaryOperatorNode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/TernaryOperatorNode.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/TransitiveOperationsIgnoringComparer.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/TransitiveOperationsIgnoringComparer.java index 47f7609f7ea..a1632c1d9f7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/TransitiveOperationsIgnoringComparer.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/TransitiveOperationsIgnoringComparer.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/UnaryOperationNode.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/UnaryOperationNode.java index 78e56acf07d..065b81cdfc9 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/UnaryOperationNode.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/UnaryOperationNode.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/package-info.java index ad2c4e46c74..84d295da2a7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/expressiontree/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,7 +22,8 @@ /** * Преобразователь дерева разбора в берево вычисления выражений с учетом приоритетов операций */ -@ParametersAreNonnullByDefault +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.utils.expressiontree; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/package-info.java index 15690e18753..df623b84958 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/utils/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -19,4 +19,8 @@ * You should have received a copy of the GNU Lesser General Public * License along with BSL Language Server. */ +@DefaultAnnotation(NonNull.class) package com.github._1c_syntax.bsl.languageserver.utils; + +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/websocket/LSPWebSocketEndpoint.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/websocket/LSPWebSocketEndpoint.java index 62f8bdd8e66..c7751dbdca6 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/websocket/LSPWebSocketEndpoint.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/websocket/LSPWebSocketEndpoint.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -26,7 +26,7 @@ import org.eclipse.lsp4j.services.LanguageClient; import org.eclipse.lsp4j.services.LanguageClientAware; import org.eclipse.lsp4j.services.LanguageServer; -import org.eclipse.lsp4j.websocket.WebSocketEndpoint; +import org.eclipse.lsp4j.websocket.jakarta.WebSocketEndpoint; import org.springframework.stereotype.Component; import java.util.Collection; diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/websocket/WebSocketConfiguration.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/websocket/WebSocketConfiguration.java index aa60bc989a5..02895f419a7 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/websocket/WebSocketConfiguration.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/websocket/WebSocketConfiguration.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,8 +21,9 @@ */ package com.github._1c_syntax.bsl.languageserver.websocket; +import jakarta.websocket.server.ServerEndpointConfig; import org.eclipse.lsp4j.services.LanguageClient; -import org.eclipse.lsp4j.websocket.WebSocketEndpoint; +import org.eclipse.lsp4j.websocket.jakarta.WebSocketEndpoint; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.context.annotation.Bean; @@ -31,8 +32,6 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter; import org.springframework.web.socket.server.standard.ServerEndpointRegistration; -import javax.websocket.server.ServerEndpointConfig; - /** * Конфигурация модуля веб-сокетов. */ diff --git a/src/main/java/com/github/_1c_syntax/bsl/languageserver/websocket/package-info.java b/src/main/java/com/github/_1c_syntax/bsl/languageserver/websocket/package-info.java index b3a81b752fa..0bedf5c0bb2 100644 --- a/src/main/java/com/github/_1c_syntax/bsl/languageserver/websocket/package-info.java +++ b/src/main/java/com/github/_1c_syntax/bsl/languageserver/websocket/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index b8fb1c1f81a..02bc3c4e444 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,6 +1,7 @@ server.port=8025 spring.main.banner-mode=off spring.main.log-startup-info=false +spring.cache.cache-names=testIds,testSources logging.level.org.springframework.boot.autoconfigure.logging=INFO logging.level.org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler=warn logging.level.com.zaxxer.hikari=warn @@ -9,12 +10,14 @@ logging.level.org.hibernate.engine.jdbc.spi.SqlExceptionHelper=fatal logging.level.org.springframework.data.repository.config.RepositoryConfigurationDelegate=warn logging.level.org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean=warn logging.level.org.springframework.context.support.PostProcessorRegistrationDelegate=warn +logging.level.org.springframework.core.LocalVariableTableParameterNameDiscoverer=error spring.application.name=BSL Language Server app.globalConfiguration.path=${user.home}/.bsl-language-server.json app.configuration.path=.bsl-language-server.json +logging.level.org.eclipse.lsp4j.jsonrpc.RemoteEndpoint=fatal + app.websocket.lsp-path=/lsp sentry.dsn=https://03ebc809fae749d297327b8140d3cad0@o745542.ingest.sentry.io/5790531 sentry.environment=production -sentry.attach-server-name=false -sentry.logging.minimum-breadcrumb-level=debug +sentry.use-git-commit-id-as-release=false picocli.disable.closures=true diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect_en.properties new file mode 100644 index 00000000000..53f9f7a5932 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect_en.properties @@ -0,0 +1 @@ +logMessage=Error info was sent to Sentry. Sentry ID: %s \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect_ru.properties new file mode 100644 index 00000000000..cabfe2614c7 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/aop/SentryAspect_ru.properties @@ -0,0 +1 @@ +logMessage=Информация об ошибке была отправлена в Sentry. Sentry ID: %s \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codeactions/ExtractStructureConstructorSupplier_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codeactions/ExtractStructureConstructorSupplier_en.properties new file mode 100644 index 00000000000..7698b450dd8 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codeactions/ExtractStructureConstructorSupplier_en.properties @@ -0,0 +1,2 @@ +insert=Insert +title=Unwrap constructor \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codeactions/ExtractStructureConstructorSupplier_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codeactions/ExtractStructureConstructorSupplier_ru.properties new file mode 100644 index 00000000000..2b01795e857 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codeactions/ExtractStructureConstructorSupplier_ru.properties @@ -0,0 +1,2 @@ +insert=Вставить +title=Развернуть конструктор \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codelenses/RunAllTestsCodeLensSupplier_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codelenses/RunAllTestsCodeLensSupplier_en.properties new file mode 100644 index 00000000000..35fe7122219 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codelenses/RunAllTestsCodeLensSupplier_en.properties @@ -0,0 +1 @@ +runAllTests=⏩ Run all tests \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codelenses/RunAllTestsCodeLensSupplier_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codelenses/RunAllTestsCodeLensSupplier_ru.properties new file mode 100644 index 00000000000..1c2834656dd --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codelenses/RunAllTestsCodeLensSupplier_ru.properties @@ -0,0 +1 @@ +runAllTests=⏩ Запустить все тесты \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codelenses/RunTestCodeLensSupplier_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codelenses/RunTestCodeLensSupplier_en.properties new file mode 100644 index 00000000000..6a7c196effa --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codelenses/RunTestCodeLensSupplier_en.properties @@ -0,0 +1 @@ +runTest=⏵ Run test \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codelenses/RunTestCodeLensSupplier_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codelenses/RunTestCodeLensSupplier_ru.properties new file mode 100644 index 00000000000..2c5a8243a84 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/codelenses/RunTestCodeLensSupplier_ru.properties @@ -0,0 +1 @@ +runTest=⏵ Запустить тест \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json index 7eb26253098..3a20edf4672 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/parameters-schema.json @@ -47,6 +47,12 @@ ], "title": "Prohibited words", "properties": { + "findInComments": { + "description": "Find in comments", + "default": true, + "type": "boolean", + "title": "Find in comments" + }, "badWords": { "description": "Regular expression for prohibited words.", "default": "", @@ -420,6 +426,16 @@ "title": "Deleting an item when iterating through collection using the operator \"For each ... In ... Do\"", "$id": "#/definitions/DeletingCollectionItem" }, + "DenyIncompleteValues": { + "description": "Deny incomplete values for dimensions", + "default": false, + "type": [ + "boolean", + "object" + ], + "title": "Deny incomplete values for dimensions", + "$id": "#/definitions/DenyIncompleteValues" + }, "DeprecatedAttributes8312": { "description": "Deprecated 8.3.12 platform features.", "default": true, @@ -500,6 +516,26 @@ "title": "Deprecated ManagedForm type", "$id": "#/definitions/DeprecatedTypeManagedForm" }, + "DisableSafeMode": { + "description": "Disable safe mode", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Disable safe mode", + "$id": "#/definitions/DisableSafeMode" + }, + "DoubleNegatives": { + "description": "Double negatives", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Double negatives", + "$id": "#/definitions/DoubleNegatives" + }, "DuplicateRegion": { "description": "Duplicate regions", "default": true, @@ -546,6 +582,24 @@ }, "$id": "#/definitions/DuplicateStringLiteral" }, + "DuplicatedInsertionIntoCollection": { + "description": "Duplicate adding or pasting a value to a collection", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Duplicate adding or pasting a value to a collection", + "properties": { + "isAllowedMethodADD": { + "description": "Analysis of methods named \"Add\" is allowed - both useful and false issues may appear", + "default": true, + "type": "boolean", + "title": "Analysis of methods named \"Add\" is allowed - both useful and false issues may appear" + } + }, + "$id": "#/definitions/DuplicatedInsertionIntoCollection" + }, "EmptyCodeBlock": { "description": "Empty code block", "default": true, @@ -624,6 +678,30 @@ "title": "Ban export global module variables", "$id": "#/definitions/ExportVariables" }, + "ExternalAppStarting": { + "description": "External applications starting", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "External applications starting", + "properties": { + "checkGotoUrl": { + "description": "Check navigation links", + "default": false, + "type": "boolean", + "title": "Check navigation links" + }, + "userPatternString": { + "description": "User regex pattern", + "default": "\u041a\u043e\u043c\u0430\u043d\u0434\u0430\u0421\u0438\u0441\u0442\u0435\u043c\u044b|System|\u0417\u0430\u043f\u0443\u0441\u0442\u0438\u0442\u044c\u0421\u0438\u0441\u0442\u0435\u043c\u0443|RunSystem|\u0417\u0430\u043f\u0443\u0441\u0442\u0438\u0442\u044c\u041f\u0440\u0438\u043b\u043e\u0436\u0435\u043d\u0438\u0435|RunApp|\u041d\u0430\u0447\u0430\u0442\u044c\u0417\u0430\u043f\u0443\u0441\u043a\u041f\u0440\u0438\u043b\u043e\u0436\u0435\u043d\u0438\u044f|BeginRunningApplication|\u0417\u0430\u043f\u0443\u0441\u0442\u0438\u0442\u044c\u041f\u0440\u0438\u043b\u043e\u0436\u0435\u043d\u0438\u0435\u0410\u0441\u0438\u043d\u0445|RunAppAsync|\u0417\u0430\u043f\u0443\u0441\u0442\u0438\u0442\u044c\u041f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0443|\u041e\u0442\u043a\u0440\u044b\u0442\u044c\u041f\u0440\u043e\u0432\u043e\u0434\u043d\u0438\u043a|\u041e\u0442\u043a\u0440\u044b\u0442\u044c\u0424\u0430\u0439\u043b", + "type": "string", + "title": "User regex pattern" + } + }, + "$id": "#/definitions/ExternalAppStarting" + }, "ExtraCommas": { "description": "Commas without a parameter at the end of a method call", "default": true, @@ -644,6 +722,30 @@ "title": "No NULL checks for fields from joined tables", "$id": "#/definitions/FieldsFromJoinsWithoutIsNull" }, + "FileSystemAccess": { + "description": "File system access", + "default": false, + "type": [ + "boolean", + "object" + ], + "title": "File system access", + "properties": { + "globalMethods": { + "description": "Global methods pattern (regex)", + "default": "\u0417\u043d\u0430\u0447\u0435\u043d\u0438\u0435\u0412\u0424\u0430\u0439\u043b|ValueToFile|\u041a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u0442\u044c\u0424\u0430\u0439\u043b|FileCopy|\u041e\u0431\u044a\u0435\u0434\u0438\u043d\u0438\u0442\u044c\u0424\u0430\u0439\u043b\u044b|MergeFiles|\u041f\u0435\u0440\u0435\u043c\u0435\u0441\u0442\u0438\u0442\u044c\u0424\u0430\u0439\u043b|MoveFile|\u0420\u0430\u0437\u0434\u0435\u043b\u0438\u0442\u044c\u0424\u0430\u0439\u043b|SplitFile|\u0421\u043e\u0437\u0434\u0430\u0442\u044c\u041a\u0430\u0442\u0430\u043b\u043e\u0433|CreateDirectory|\u0423\u0434\u0430\u043b\u0438\u0442\u044c\u0424\u0430\u0439\u043b\u044b|DeleteFiles|\u041a\u0430\u0442\u0430\u043b\u043e\u0433\u041f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u044b|BinDir|\u041a\u0430\u0442\u0430\u043b\u043e\u0433\u0412\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0445\u0424\u0430\u0439\u043b\u043e\u0432|TempFilesDir|\u041a\u0430\u0442\u0430\u043b\u043e\u0433\u0414\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u043e\u0432|DocumentsDir|\u0420\u0430\u0431\u043e\u0447\u0438\u0439\u041a\u0430\u0442\u0430\u043b\u043e\u0433\u0414\u0430\u043d\u043d\u044b\u0445\u041f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044f|UserDataWorkDir|\u041d\u0430\u0447\u0430\u0442\u044c\u041f\u043e\u0434\u043a\u043b\u044e\u0447\u0435\u043d\u0438\u0435\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043d\u0438\u044f\u0420\u0430\u0431\u043e\u0442\u044b\u0421\u0424\u0430\u0439\u043b\u0430\u043c\u0438|BeginAttachingFileSystemExtension|\u041d\u0430\u0447\u0430\u0442\u044c\u0423\u0441\u0442\u0430\u043d\u043e\u0432\u043a\u0443\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043d\u0438\u044f\u0420\u0430\u0431\u043e\u0442\u044b\u0421\u0424\u0430\u0439\u043b\u0430\u043c\u0438|BeginInstallFileSystemExtension|\u0423\u0441\u0442\u0430\u043d\u043e\u0432\u0438\u0442\u044c\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043d\u0438\u0435\u0420\u0430\u0431\u043e\u0442\u044b\u0421\u0424\u0430\u0439\u043b\u0430\u043c\u0438|InstallFileSystemExtension|\u0423\u0441\u0442\u0430\u043d\u043e\u0432\u0438\u0442\u044c\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043d\u0438\u0435\u0420\u0430\u0431\u043e\u0442\u044b\u0421\u0424\u0430\u0439\u043b\u0430\u043c\u0438\u0410\u0441\u0438\u043d\u0445|InstallFileSystemExtensionAsync|\u041f\u043e\u0434\u043a\u043b\u044e\u0447\u0438\u0442\u044c\u0420\u0430\u0441\u0448\u0438\u0440\u0435\u043d\u0438\u0435\u0420\u0430\u0431\u043e\u0442\u044b\u0421\u0424\u0430\u0439\u043b\u0430\u043c\u0438\u0410\u0441\u0438\u043d\u0445|AttachFileSystemExtensionAsync|\u041a\u0430\u0442\u0430\u043b\u043e\u0433\u0412\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0445\u0424\u0430\u0439\u043b\u043e\u0432\u0410\u0441\u0438\u043d\u0445|TempFilesDirAsync|\u041a\u0430\u0442\u0430\u043b\u043e\u0433\u0414\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u043e\u0432\u0410\u0441\u0438\u043d\u0445|DocumentsDirAsync|\u041d\u0430\u0447\u0430\u0442\u044c\u041f\u043e\u043b\u0443\u0447\u0435\u043d\u0438\u0435\u041a\u0430\u0442\u0430\u043b\u043e\u0433\u0430\u0412\u0440\u0435\u043c\u0435\u043d\u043d\u044b\u0445\u0424\u0430\u0439\u043b\u043e\u0432|BeginGettingTempFilesDir|\u041d\u0430\u0447\u0430\u0442\u044c\u041f\u043e\u043b\u0443\u0447\u0435\u043d\u0438\u0435\u041a\u0430\u0442\u0430\u043b\u043e\u0433\u0430\u0414\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u043e\u0432|BeginGettingDocumentsDir|\u041d\u0430\u0447\u0430\u0442\u044c\u041f\u043e\u043b\u0443\u0447\u0435\u043d\u0438\u0435\u0420\u0430\u0431\u043e\u0447\u0435\u0433\u043e\u041a\u0430\u0442\u0430\u043b\u043e\u0433\u0430\u0414\u0430\u043d\u043d\u044b\u0445\u041f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044f|BeginGettingUserDataWorkDir|\u0420\u0430\u0431\u043e\u0447\u0438\u0439\u041a\u0430\u0442\u0430\u043b\u043e\u0433\u0414\u0430\u043d\u043d\u044b\u0445\u041f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044f\u0410\u0441\u0438\u043d\u0445|UserDataWorkDirAsync|\u041a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u0442\u044c\u0424\u0430\u0439\u043b\u0410\u0441\u0438\u043d\u0445|CopyFileAsync|\u041d\u0430\u0439\u0442\u0438\u0424\u0430\u0439\u043b\u044b\u0410\u0441\u0438\u043d\u0445|FindFilesAsync|\u041d\u0430\u0447\u0430\u0442\u044c\u041a\u043e\u043f\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435\u0424\u0430\u0439\u043b\u0430|BeginCopyingFile|\u041d\u0430\u0447\u0430\u0442\u044c\u041f\u0435\u0440\u0435\u043c\u0435\u0449\u0435\u043d\u0438\u0435\u0424\u0430\u0439\u043b\u0430|BeginMovingFile|\u041d\u0430\u0447\u0430\u0442\u044c\u041f\u043e\u0438\u0441\u043a\u0424\u0430\u0439\u043b\u043e\u0432|BeginFindingFiles|\u041d\u0430\u0447\u0430\u0442\u044c\u0421\u043e\u0437\u0434\u0430\u043d\u0438\u0435\u0414\u0432\u043e\u0438\u0447\u043d\u044b\u0445\u0414\u0430\u043d\u043d\u044b\u0445\u0418\u0437\u0424\u0430\u0439\u043b\u0430|BeginCreateBinaryDataFromFile|\u041d\u0430\u0447\u0430\u0442\u044c\u0421\u043e\u0437\u0434\u0430\u043d\u0438\u0435\u041a\u0430\u0442\u0430\u043b\u043e\u0433\u0430|BeginCreatingDirectory|\u041d\u0430\u0447\u0430\u0442\u044c\u0423\u0434\u0430\u043b\u0435\u043d\u0438\u0435\u0424\u0430\u0439\u043b\u043e\u0432|BeginDeletingFiles|\u041f\u0435\u0440\u0435\u043c\u0435\u0441\u0442\u0438\u0442\u044c\u0424\u0430\u0439\u043b\u0410\u0441\u0438\u043d\u0445|MoveFileAsync|\u0421\u043e\u0437\u0434\u0430\u0442\u044c\u0414\u0432\u043e\u0438\u0447\u043d\u044b\u0435\u0414\u0430\u043d\u043d\u044b\u0435\u0418\u0437\u0424\u0430\u0439\u043b\u0430\u0410\u0441\u0438\u043d\u0445|CreateBinaryDataFromFileAsync|\u0421\u043e\u0437\u0434\u0430\u0442\u044c\u041a\u0430\u0442\u0430\u043b\u043e\u0433\u0410\u0441\u0438\u043d\u0445|CreateDirectoryAsync|\u0423\u0434\u0430\u043b\u0438\u0442\u044c\u0424\u0430\u0439\u043b\u044b\u0410\u0441\u0438\u043d\u0445|DeleteFilesAsync", + "type": "string", + "title": "Global methods pattern (regex)" + }, + "newExpression": { + "description": "Class names pattern (regex)", + "default": "File|\u0424\u0430\u0439\u043b|xBase|HTMLWriter|\u0417\u0430\u043f\u0438\u0441\u044cHTML|HTMLReader|\u0427\u0442\u0435\u043d\u0438\u0435HTML|FastInfosetReader|\u0427\u0442\u0435\u043d\u0438\u0435FastInfoset|FastInfosetWriter|\u0417\u0430\u043f\u0438\u0441\u044cFastInfoset|XSLTransform|\u041f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u0435XSL|ZipFileWriter|\u0417\u0430\u043f\u0438\u0441\u044cZip\u0424\u0430\u0439\u043b\u0430|ZipFileReader|\u0427\u0442\u0435\u043d\u0438\u0435Zip\u0424\u0430\u0439\u043b\u0430|TextReader|\u0427\u0442\u0435\u043d\u0438\u0435\u0422\u0435\u043a\u0441\u0442\u0430|TextWriter|\u0417\u0430\u043f\u0438\u0441\u044c\u0422\u0435\u043a\u0441\u0442\u0430|TextExtraction|\u0418\u0437\u0432\u043b\u0435\u0447\u0435\u043d\u0438\u0435\u0422\u0435\u043a\u0441\u0442\u0430|BinaryData|\u0414\u0432\u043e\u0438\u0447\u043d\u044b\u0435\u0414\u0430\u043d\u043d\u044b\u0435|FileStream|\u0424\u0430\u0439\u043b\u043e\u0432\u044b\u0439\u041f\u043e\u0442\u043e\u043a|FileStreamsManager|\u041c\u0435\u043d\u0435\u0434\u0436\u0435\u0440\u0424\u0430\u0439\u043b\u043e\u0432\u044b\u0445\u041f\u043e\u0442\u043e\u043a\u043e\u0432|DataWriter|\u0417\u0430\u043f\u0438\u0441\u044c\u0414\u0430\u043d\u043d\u044b\u0445|DataReader|\u0427\u0442\u0435\u043d\u0438\u0435\u0414\u0430\u043d\u043d\u044b\u0445", + "type": "string", + "title": "Class names pattern (regex)" + } + }, + "$id": "#/definitions/FileSystemAccess" + }, "ForbiddenMetadataName": { "description": "Metadata object has a forbidden name", "default": true, @@ -870,6 +972,16 @@ "title": "Incorrect use of \"StrTemplate\"", "$id": "#/definitions/IncorrectUseOfStrTemplate" }, + "InternetAccess": { + "description": "Referring to Internet resources", + "default": false, + "type": [ + "boolean", + "object" + ], + "title": "Referring to Internet resources", + "$id": "#/definitions/InternetAccess" + }, "InvalidCharacterInFile": { "description": "Invalid character", "default": true, @@ -1046,6 +1158,16 @@ }, "$id": "#/definitions/MethodSize" }, + "MissedRequiredParameter": { + "description": "Missed a required method parameter", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Missed a required method parameter", + "$id": "#/definitions/MissedRequiredParameter" + }, "MissingCodeTryCatchEx": { "description": "Missing code in Raise block in \"Try ... Raise ... EndTry\"", "default": true, @@ -1064,6 +1186,16 @@ }, "$id": "#/definitions/MissingCodeTryCatchEx" }, + "MissingCommonModuleMethod": { + "description": "Referencing a missing common module method", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Referencing a missing common module method", + "$id": "#/definitions/MissingCommonModuleMethod" + }, "MissingEventSubscriptionHandler": { "description": "Event subscription handler missing", "default": true, @@ -1432,6 +1564,24 @@ "title": "Source code parse error", "$id": "#/definitions/ParseError" }, + "PrivilegedModuleMethodCall": { + "description": "Accessing privileged module methods", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Accessing privileged module methods", + "properties": { + "validateNestedCalls": { + "description": "Validate nested method calls from privileged modules", + "default": true, + "type": "boolean", + "title": "Validate nested method calls from privileged modules" + } + }, + "$id": "#/definitions/PrivilegedModuleMethodCall" + }, "ProcedureReturnsValue": { "description": "Procedure should not return Value", "default": true, @@ -1442,6 +1592,16 @@ "title": "Procedure should not return Value", "$id": "#/definitions/ProcedureReturnsValue" }, + "ProtectedModule": { + "description": "Protected modules", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Protected modules", + "$id": "#/definitions/ProtectedModule" + }, "PublicMethodsDescription": { "description": "All public methods must have a description", "default": true, @@ -1520,6 +1680,24 @@ "title": "Overuse \"Reference\" in a query", "$id": "#/definitions/RefOveruse" }, + "ReservedParameterNames": { + "description": "Reserved parameter names", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Reserved parameter names", + "properties": { + "reservedWords": { + "description": "Regular expression for reserved parameter names.", + "default": "", + "type": "string", + "title": "Regular expression for reserved parameter names." + } + }, + "$id": "#/definitions/ReservedParameterNames" + }, "RewriteMethodParameter": { "description": "Rewrite method parameter", "default": true, @@ -1626,6 +1804,16 @@ }, "$id": "#/definitions/SetPermissionsForNewObjects" }, + "SetPrivilegedMode": { + "description": "Using privileged mode", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Using privileged mode", + "$id": "#/definitions/SetPrivilegedMode" + }, "SeveralCompilerDirectives": { "description": "Erroneous indication of several compilation directives", "default": true, @@ -1736,6 +1924,16 @@ }, "$id": "#/definitions/TooManyReturns" }, + "TransferringParametersBetweenClientAndServer": { + "description": "Transferring parameters between the client and the server", + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Transferring parameters between the client and the server", + "$id": "#/definitions/TransferringParametersBetweenClientAndServer" + }, "TryNumber": { "description": "Cast to number of try catch block", "default": true, @@ -1834,6 +2032,12 @@ "default": "\u043f\u043e\u0434\u043a\u043b\u044e\u0447\u0430\u0435\u043c\u044b\u0439_,attachable_", "type": "string", "title": "Method prefixes (comma separated)" + }, + "checkObjectModule": { + "description": "Check object modules", + "default": false, + "type": "boolean", + "title": "Check object modules" } }, "$id": "#/definitions/UnusedLocalMethod" @@ -1878,6 +2082,16 @@ "title": "Useless collection iteration", "$id": "#/definitions/UseLessForEach" }, + "UseSystemInformation": { + "description": "Use of system information", + "default": false, + "type": [ + "boolean", + "object" + ], + "title": "Use of system information", + "$id": "#/definitions/UseSystemInformation" + }, "UsingCancelParameter": { "description": "Using parameter \"Cancel\"", "default": true, @@ -1899,13 +2113,13 @@ "$id": "#/definitions/UsingExternalCodeTools" }, "UsingFindElementByString": { - "description": "Using FindByName and FindByCode", + "description": "Using FindByName, FindByCode and FindByNumber", "default": true, "type": [ "boolean", "object" ], - "title": "Using FindByName and FindByCode", + "title": "Using FindByName, FindByCode and FindByNumber", "$id": "#/definitions/UsingFindElementByString" }, "UsingGoto": { diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json index 662d4024cad..8bcf9df256f 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/configuration/schema.json @@ -29,6 +29,9 @@ "AssignAliasFieldsInQuery": { "$ref": "parameters-schema.json#/definitions/AssignAliasFieldsInQuery" }, + "BadWords": { + "$ref": "parameters-schema.json#/definitions/BadWords" + }, "BeginTransactionBeforeTryCatch": { "$ref": "parameters-schema.json#/definitions/BeginTransactionBeforeTryCatch" }, @@ -116,6 +119,9 @@ "DeletingCollectionItem": { "$ref": "parameters-schema.json#/definitions/DeletingCollectionItem" }, + "DenyIncompleteValues": { + "$ref": "parameters-schema.json#/definitions/DenyIncompleteValues" + }, "DeprecatedAttributes8312": { "$ref": "parameters-schema.json#/definitions/DeprecatedAttributes8312" }, @@ -140,9 +146,21 @@ "DeprecatedTypeManagedForm": { "$ref": "parameters-schema.json#/definitions/DeprecatedTypeManagedForm" }, + "DisableSafeMode": { + "$ref": "parameters-schema.json#/definitions/DisableSafeMode" + }, + "DoubleNegatives": { + "$ref": "parameters-schema.json#/definitions/DoubleNegatives" + }, "DuplicateRegion": { "$ref": "parameters-schema.json#/definitions/DuplicateRegion" }, + "DuplicateStringLiteral": { + "$ref": "parameters-schema.json#/definitions/DuplicateStringLiteral" + }, + "DuplicatedInsertionIntoCollection": { + "$ref": "parameters-schema.json#/definitions/DuplicatedInsertionIntoCollection" + }, "EmptyCodeBlock": { "$ref": "parameters-schema.json#/definitions/EmptyCodeBlock" }, @@ -164,12 +182,21 @@ "ExportVariables": { "$ref": "parameters-schema.json#/definitions/ExportVariables" }, + "ExternalAppStarting": { + "$ref": "parameters-schema.json#/definitions/ExternalAppStarting" + }, "ExtraCommas": { "$ref": "parameters-schema.json#/definitions/ExtraCommas" }, "FieldsFromJoinsWithoutIsNull": { "$ref": "parameters-schema.json#/definitions/FieldsFromJoinsWithoutIsNull" }, + "FileSystemAccess": { + "$ref": "parameters-schema.json#/definitions/FileSystemAccess" + }, + "ForbiddenMetadataName": { + "$ref": "parameters-schema.json#/definitions/ForbiddenMetadataName" + }, "FormDataToValue": { "$ref": "parameters-schema.json#/definitions/FormDataToValue" }, @@ -218,6 +245,9 @@ "IncorrectUseOfStrTemplate": { "$ref": "parameters-schema.json#/definitions/IncorrectUseOfStrTemplate" }, + "InternetAccess": { + "$ref": "parameters-schema.json#/definitions/InternetAccess" + }, "InvalidCharacterInFile": { "$ref": "parameters-schema.json#/definitions/InvalidCharacterInFile" }, @@ -251,9 +281,15 @@ "MethodSize": { "$ref": "parameters-schema.json#/definitions/MethodSize" }, + "MissedRequiredParameter": { + "$ref": "parameters-schema.json#/definitions/MissedRequiredParameter" + }, "MissingCodeTryCatchEx": { "$ref": "parameters-schema.json#/definitions/MissingCodeTryCatchEx" }, + "MissingCommonModuleMethod": { + "$ref": "parameters-schema.json#/definitions/MissingCommonModuleMethod" + }, "MissingEventSubscriptionHandler": { "$ref": "parameters-schema.json#/definitions/MissingEventSubscriptionHandler" }, @@ -329,18 +365,42 @@ "ParseError": { "$ref": "parameters-schema.json#/definitions/ParseError" }, + "PrivilegedModuleMethodCall": { + "$ref": "parameters-schema.json#/definitions/PrivilegedModuleMethodCall" + }, "ProcedureReturnsValue": { "$ref": "parameters-schema.json#/definitions/ProcedureReturnsValue" }, + "ProtectedModule": { + "$ref": "parameters-schema.json#/definitions/ProtectedModule" + }, "PublicMethodsDescription": { "$ref": "parameters-schema.json#/definitions/PublicMethodsDescription" }, + "QueryParseError": { + "$ref": "parameters-schema.json#/definitions/QueryParseError" + }, + "QueryToMissingMetadata": { + "$ref": "parameters-schema.json#/definitions/QueryToMissingMetadata" + }, "RedundantAccessToObject": { "$ref": "parameters-schema.json#/definitions/RedundantAccessToObject" }, "RefOveruse": { "$ref": "parameters-schema.json#/definitions/RefOveruse" }, + "ReservedParameterNames": { + "$ref": "parameters-schema.json#/definitions/ReservedParameterNames" + }, + "RewriteMethodParameter": { + "$ref": "parameters-schema.json#/definitions/RewriteMethodParameter" + }, + "SameMetadataObjectAndChildNames": { + "$ref": "parameters-schema.json#/definitions/SameMetadataObjectAndChildNames" + }, + "ScheduledJobHandler": { + "$ref": "parameters-schema.json#/definitions/ScheduledJobHandler" + }, "SelectTopWithoutOrderBy": { "$ref": "parameters-schema.json#/definitions/SelectTopWithoutOrderBy" }, @@ -353,9 +413,15 @@ "SemicolonPresence": { "$ref": "parameters-schema.json#/definitions/SemicolonPresence" }, + "ServerSideExportFormMethod": { + "$ref": "parameters-schema.json#/definitions/ServerSideExportFormMethod" + }, "SetPermissionsForNewObjects": { "$ref": "parameters-schema.json#/definitions/SetPermissionsForNewObjects" }, + "SetPrivilegedMode": { + "$ref": "parameters-schema.json#/definitions/SetPrivilegedMode" + }, "SeveralCompilerDirectives": { "$ref": "parameters-schema.json#/definitions/SeveralCompilerDirectives" }, @@ -380,6 +446,9 @@ "TooManyReturns": { "$ref": "parameters-schema.json#/definitions/TooManyReturns" }, + "TransferringParametersBetweenClientAndServer": { + "$ref": "parameters-schema.json#/definitions/TransferringParametersBetweenClientAndServer" + }, "TryNumber": { "$ref": "parameters-schema.json#/definitions/TryNumber" }, @@ -416,6 +485,9 @@ "UseLessForEach": { "$ref": "parameters-schema.json#/definitions/UseLessForEach" }, + "UseSystemInformation": { + "$ref": "parameters-schema.json#/definitions/UseSystemInformation" + }, "UsingCancelParameter": { "$ref": "parameters-schema.json#/definitions/UsingCancelParameter" }, @@ -461,12 +533,18 @@ "WrongDataPathForFormElements": { "$ref": "parameters-schema.json#/definitions/WrongDataPathForFormElements" }, + "WrongHttpServiceHandler": { + "$ref": "parameters-schema.json#/definitions/WrongHttpServiceHandler" + }, "WrongUseFunctionProceedWithCall": { "$ref": "parameters-schema.json#/definitions/WrongUseFunctionProceedWithCall" }, "WrongUseOfRollbackTransactionMethod": { "$ref": "parameters-schema.json#/definitions/WrongUseOfRollbackTransactionMethod" }, + "WrongWebServiceHandler": { + "$ref": "parameters-schema.json#/definitions/WrongWebServiceHandler" + }, "YoLetterUsage": { "$ref": "parameters-schema.json#/definitions/YoLetterUsage" } @@ -516,6 +594,58 @@ "$id": "#/definitions/codeLensParameters/cyclomaticComplexity" } } + }, + "inlayHintParameters": { + "$id": "#/definitions/inlayHintParameters", + "type": "object", + "title": "Inlay hints parameters configuration.\nKey-value object, where key is a inlay hint ID, and value is boolean or object with concrete inlay hint configuration.", + "default": null, + "additionalProperties": { + "$ref": "#/definitions/parameter" + }, + "properties": { + "cognitiveComplexity": { + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Show cognitive complexity score inlay hints.", + "$id": "#/definitions/inlayHintParameters/cognitiveComplexity" + }, + "cyclomaticComplexity": { + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Show cyclomatic complexity score inlay hints.", + "$id": "#/definitions/inlayHintParameters/cyclomaticComplexity" + }, + "sourceDefinedMethodCall": { + "default": true, + "type": [ + "boolean", + "object" + ], + "title": "Show parameters of called source defined methods.", + "properties": { + "showParametersWithTheSameName": { + "description": "Show hints for parameters with names that are contained in passed value.", + "default": false, + "type": "boolean", + "title": "Show hints for parameters with names that contains passed value." + }, + "showDefaultValues": { + "description": "Show hints with default values for non-passed parameters.", + "default": true, + "type": "boolean", + "title": "Show hints with default values for non-passed parameters." + } + }, + "$id": "#/definitions/inlayHintParameters/sourceDefinedMethodCall" + } + } } }, "properties": { @@ -542,6 +672,78 @@ "properties": { "parameters": { "$ref": "#/definitions/codeLensParameters" + }, + "testRunner": { + "$id": "#/properties/codeLens/testRunner", + "type": "object", + "title": "Test runner configuration to use for 'Run test' code lenses.", + "properties": { + "testSources": { + "$id": "#/properties/codeLens/testRunner/testSources", + "type": "array", + "title": "List of directories with test sources.", + "items": { + "type": "string" + }, + "default": [ + "tests" + ] + }, + "annotations": { + "$id": "#/properties/codeLens/testRunner/annotations", + "type": "array", + "title": "List of annotations to find test methods.", + "items": { + "type": "string" + }, + "default": [ + "\u0422\u0435\u0441\u0442", + "Test" + ] + }, + "executable": { + "$id": "#/properties/codeLens/testRunner/executable", + "type": "string", + "title": "Path to test runner executable.", + "default": "1testrunner" + }, + "executableWin": { + "$id": "#/properties/codeLens/testRunner/executableWin", + "type": "string", + "title": "Path to test runner executable on Windows systems.", + "default": "1testrunner.bat" + }, + "getTestsByTestRunner": { + "$id": "#/properties/codeLens/testRunner/getTestsByTestRunner", + "type": "boolean", + "title": "Use testrunner to get test method names. By default, use internal parser to find methods annotated with &\u0422\u0435\u0441\u0442.", + "default": true + }, + "getTestsArguments": { + "$id": "#/properties/codeLens/testRunner/getTestsArguments", + "type": "string", + "title": "Arguments to pass to test runner executable to get test method names. %s will be replaced with path to current file.", + "default": "-show %s" + }, + "getTestsResultPattern": { + "$id": "#/properties/codeLens/testRunner/resultPattern", + "type": "string", + "title": "Regular expression to parse test runner output for method names.", + "default": "^[^<]*<([^>]+)>.*" + }, + "runTestArguments": { + "$id": "#/properties/codeLens/testRunner/runTestArguments", + "type": "string", + "title": "Arguments to pass to test runner executable to run test method. %s will be replaced with path to current file, %m will be replaced with test method name.", + "default": "-run %s %s" + }, + "runAllTestsArguments": { + "$id": "#/properties/codeLens/testRunner/runAllTestsArguments", + "type": "string", + "title": "Arguments to pass to test runner executable to run all tests in current file. %s will be replaced with path to current file.", + "default": "-run %s" + } + } } } }, @@ -694,7 +896,7 @@ "type": "object", "title": "Formatting configuration.", "properties": { - "useUpperCaseForOrNotKeywords": { + "useUpperCaseForOrNotAndKeywords": { "$id": "#/properties/useUpperCaseForOrNotAndKeywords", "type": "boolean", "default": true, @@ -726,6 +928,16 @@ } } }, + "inlayHint": { + "$id": "#/properties/inlayHint", + "type": "object", + "title": "Inlay hint configuration.", + "properties": { + "parameters": { + "$ref": "#/definitions/inlayHintParameters" + } + } + }, "useDevSite": { "$id": "#/properties/useDevSite", "type": "boolean", diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadWordsDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadWordsDiagnostic_en.properties index d4f0db3b506..5d24e89b057 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadWordsDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadWordsDiagnostic_en.properties @@ -1,3 +1,4 @@ -diagnosticMessage=Prohibited word found. +diagnosticMessage=Prohibited word found <%s>. diagnosticName=Prohibited words badWords=Regular expression for prohibited words. +findInComments=Find in comments diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadWordsDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadWordsDiagnostic_ru.properties index de3556166c6..952f8aa5921 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadWordsDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadWordsDiagnostic_ru.properties @@ -1,3 +1,4 @@ -diagnosticMessage=В тексте модуля найдено запрещенное слово. +diagnosticMessage=В тексте модуля найдено запрещенное слово <%s>. diagnosticName=Запрещенные слова badWords=Регулярное выражение для слов-исключений. +findInComments=Искать в комментариях diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DenyIncompleteValuesDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DenyIncompleteValuesDiagnostic_en.properties new file mode 100644 index 00000000000..d46277fecff --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DenyIncompleteValuesDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=The "Deny incomplete values" flag is not specified for the "%s" dimension of the "%s" metadata +diagnosticName=Deny incomplete values for dimensions diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DenyIncompleteValuesDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DenyIncompleteValuesDiagnostic_ru.properties new file mode 100644 index 00000000000..41d143257cd --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DenyIncompleteValuesDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Не указан флаг "Запрет незаполненных значений" у измерения "%s" метаданного "%s" +diagnosticName=Запрет незаполненных значений у измерений регистров diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DisableSafeModeDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DisableSafeModeDiagnostic_en.properties new file mode 100644 index 00000000000..7270e9aafaa --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DisableSafeModeDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Check the safe mode setting +diagnosticName=Disable safe mode diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DisableSafeModeDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DisableSafeModeDiagnostic_ru.properties new file mode 100644 index 00000000000..186180f5a86 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DisableSafeModeDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Проверьте отключение безопасного режима +diagnosticName=Отключение безопасного режима diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic_en.properties new file mode 100644 index 00000000000..b40f038bd92 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Using double negatives complicates understanding of code +diagnosticName=Double negatives diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic_ru.properties new file mode 100644 index 00000000000..06fb1ed09ea --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Использование двойных отрицаний усложняет понимание кода +diagnosticName=Двойные отрицания diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicatedInsertionIntoCollectionDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicatedInsertionIntoCollectionDiagnostic_en.properties new file mode 100644 index 00000000000..99ed1f8a3a8 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicatedInsertionIntoCollectionDiagnostic_en.properties @@ -0,0 +1,4 @@ +diagnosticMessage=Check the re-addition of %s to the collection with name %s +diagnosticName=Duplicate adding or pasting a value to a collection + +isAllowedMethodADD=Analysis of methods named "Add" is allowed - both useful and false issues may appear diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicatedInsertionIntoCollectionDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicatedInsertionIntoCollectionDiagnostic_ru.properties new file mode 100644 index 00000000000..024796a4a95 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicatedInsertionIntoCollectionDiagnostic_ru.properties @@ -0,0 +1,4 @@ +diagnosticMessage=Проверьте повторную вставку %s в коллекцию %s +diagnosticName=Повторное добавление/вставка значений в коллекцию + +isAllowedMethodADD=Разрешен анализ методов "Добавить" - могут появиться и полезные и ложные замечания diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExternalAppStartingDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExternalAppStartingDiagnostic_en.properties new file mode 100644 index 00000000000..117f5638521 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExternalAppStartingDiagnostic_en.properties @@ -0,0 +1,4 @@ +diagnosticMessage=Check the launch of an external application +diagnosticName=External applications starting +checkGotoUrl=Check navigation links +userPatternString=User regex pattern diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExternalAppStartingDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExternalAppStartingDiagnostic_ru.properties new file mode 100644 index 00000000000..45d566bc4d6 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExternalAppStartingDiagnostic_ru.properties @@ -0,0 +1,4 @@ +diagnosticMessage=Проверьте запуск внешнего приложения +diagnosticName=Запуск внешних приложений +checkGotoUrl=Проверять переход по навигационным ссылкам +userPatternString=Пользовательский шаблон (регулярное выражение) diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FileSystemAccessDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FileSystemAccessDiagnostic_en.properties new file mode 100644 index 00000000000..aa06ad1bf5e --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FileSystemAccessDiagnostic_en.properties @@ -0,0 +1,4 @@ +diagnosticMessage=Check access to the file system +diagnosticName=File system access +globalMethods=Global methods pattern (regex) +newExpression=Class names pattern (regex) diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FileSystemAccessDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FileSystemAccessDiagnostic_ru.properties new file mode 100644 index 00000000000..73648370051 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/FileSystemAccessDiagnostic_ru.properties @@ -0,0 +1,4 @@ +diagnosticMessage=Проверьте обращение к файловой системе +diagnosticName=Доступ к файловой системе +globalMethods=Шаблон глобальных методов (регулярное выражение) +newExpression=Шаблон классов (регулярное выражение) diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/InternetAccessDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/InternetAccessDiagnostic_en.properties new file mode 100644 index 00000000000..1e4019e3eb8 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/InternetAccessDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Check the reference to Internet resources +diagnosticName=Referring to Internet resources diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/InternetAccessDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/InternetAccessDiagnostic_ru.properties new file mode 100644 index 00000000000..4cf26b98770 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/InternetAccessDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Проверьте обращение к Интернет-ресурсам +diagnosticName=Обращение к Интернет-ресурсам diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissedRequiredParameterDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissedRequiredParameterDiagnostic_en.properties new file mode 100644 index 00000000000..e8b392b8ab3 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissedRequiredParameterDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Specify a required parameter %s +diagnosticName=Missed a required method parameter diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissedRequiredParameterDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissedRequiredParameterDiagnostic_ru.properties new file mode 100644 index 00000000000..eb968defac0 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissedRequiredParameterDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Укажите обязательный параметр %s +diagnosticName=Пропущен обязательный параметр метода diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCommonModuleMethodDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCommonModuleMethodDiagnostic_en.properties new file mode 100644 index 00000000000..4710f919fa2 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCommonModuleMethodDiagnostic_en.properties @@ -0,0 +1,4 @@ +diagnosticMessage=The method %s of %s common module does not exist +diagnosticName=Referencing a missing common module method + +privateMethod=Correct the reference to the non export %s method of the common module %s \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCommonModuleMethodDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCommonModuleMethodDiagnostic_ru.properties new file mode 100644 index 00000000000..1ae0931663e --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCommonModuleMethodDiagnostic_ru.properties @@ -0,0 +1,4 @@ +diagnosticMessage=Метод %s общего модуля %s не существует +diagnosticName=Обращение к отсутствующему методу общего модуля + +privateMethod=Исправьте обращение к закрытому, неэкспортному методу %s общего модуля %s \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/PrivilegedModuleMethodCallDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/PrivilegedModuleMethodCallDiagnostic_en.properties new file mode 100644 index 00000000000..eb7fdf7c62c --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/PrivilegedModuleMethodCallDiagnostic_en.properties @@ -0,0 +1,3 @@ +diagnosticMessage=Check the %s method access of the privileged module +diagnosticName=Accessing privileged module methods +validateNestedCalls=Validate nested method calls from privileged modules diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/PrivilegedModuleMethodCallDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/PrivilegedModuleMethodCallDiagnostic_ru.properties new file mode 100644 index 00000000000..e350b71eecf --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/PrivilegedModuleMethodCallDiagnostic_ru.properties @@ -0,0 +1,3 @@ +diagnosticMessage=Проверьте обращение к методу %s привилегированного модуля +diagnosticName=Обращение к методам привилегированных модулей +validateNestedCalls=Проверять вложенные вызовы методов из привилегированных модулей diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProtectedModuleDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProtectedModuleDiagnostic_en.properties new file mode 100644 index 00000000000..ebf9da6834b --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProtectedModuleDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=The source code of the module is missing due to password protection. %s +diagnosticName=Protected modules diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProtectedModuleDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProtectedModuleDiagnostic_ru.properties new file mode 100644 index 00000000000..43210c1d1ae --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProtectedModuleDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Исходный код модуля отсутствует из-за защиты паролем. %s +diagnosticName=Защищенные модули diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ReservedParameterNamesDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ReservedParameterNamesDiagnostic_en.properties new file mode 100644 index 00000000000..52aea28826f --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ReservedParameterNamesDiagnostic_en.properties @@ -0,0 +1,3 @@ +diagnosticMessage=Rename parameter "%s" that matches one of reserved words. +diagnosticName=Reserved parameter names +reservedWords=Regular expression for reserved parameter names. diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ReservedParameterNamesDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ReservedParameterNamesDiagnostic_ru.properties new file mode 100644 index 00000000000..e494355e7fa --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/ReservedParameterNamesDiagnostic_ru.properties @@ -0,0 +1,3 @@ +diagnosticMessage=Переименуйте параметр "%s" так, чтобы он не совпадал с зарезервированным словом. +diagnosticName=Зарезервированные имена параметров +reservedWords=Регулярное выражение для зарезервированных имен параметров. diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPrivilegedModeDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPrivilegedModeDiagnostic_en.properties new file mode 100644 index 00000000000..c6232bd990a --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPrivilegedModeDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Check the privileged mode setting +diagnosticName=Using privileged mode diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPrivilegedModeDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPrivilegedModeDiagnostic_ru.properties new file mode 100644 index 00000000000..490d1e1c754 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPrivilegedModeDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Проверьте установку привилегированного режима +diagnosticName=Использование привилегированного режима diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TransferringParametersBetweenClientAndServerDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TransferringParametersBetweenClientAndServerDiagnostic_en.properties new file mode 100644 index 00000000000..5fb24da373e --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TransferringParametersBetweenClientAndServerDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Set the modifier "ByValue" for the "%s" parameter of the "%s" method +diagnosticName=Transferring parameters between the client and the server diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TransferringParametersBetweenClientAndServerDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TransferringParametersBetweenClientAndServerDiagnostic_ru.properties new file mode 100644 index 00000000000..636aa2c68a9 --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/TransferringParametersBetweenClientAndServerDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Установите модификатор "Знач" для параметра %s метода %s +diagnosticName=Передача параметров между клиентом и сервером diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalMethodDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalMethodDiagnostic_en.properties index ebadb58a518..14fb4339fec 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalMethodDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalMethodDiagnostic_en.properties @@ -1,3 +1,4 @@ diagnosticMessage=Method "%s" is not called in the module diagnosticName=Unused local method attachableMethodPrefixes=Method prefixes (comma separated) +checkObjectModule=Check object modules diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalMethodDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalMethodDiagnostic_ru.properties index bcebece21c0..07da1efa33f 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalMethodDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalMethodDiagnostic_ru.properties @@ -1,3 +1,4 @@ diagnosticMessage=Метод "%s" не вызывается в теле модуля diagnosticName=Неиспользуемый локальный метод attachableMethodPrefixes=Префиксы подключаемых методов (через запятую) +checkObjectModule=Проверять модули объектов diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseSystemInformationDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseSystemInformationDiagnostic_en.properties new file mode 100644 index 00000000000..d04ce9a561a --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseSystemInformationDiagnostic_en.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Get rid of using the `SystemInformation` object +diagnosticName=Use of system information diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseSystemInformationDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseSystemInformationDiagnostic_ru.properties new file mode 100644 index 00000000000..ff81ebc0d8f --- /dev/null +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseSystemInformationDiagnostic_ru.properties @@ -0,0 +1,2 @@ +diagnosticMessage=Избавьтесь от использования объекта `СистемнаяИнформация` +diagnosticName=Использование системной информации diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnostic_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnostic_en.properties index 7f80282befe..06f19a2a603 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnostic_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnostic_en.properties @@ -1,2 +1,2 @@ diagnosticMessage=Don't use method "%s" and finding by string. -diagnosticName=Using FindByName and FindByCode \ No newline at end of file +diagnosticName=Using FindByName, FindByCode and FindByNumber \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnostic_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnostic_ru.properties index 6ae96c597d6..476a7617437 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnostic_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnostic_ru.properties @@ -1,2 +1,2 @@ diagnosticMessage=Не следует использовать метод "%s" и поиск по строке -diagnosticName=Использование методов "НайтиПоНаименованию" и "НайтиПоКоду" \ No newline at end of file +diagnosticName=Использование методов "НайтиПоНаименованию", "НайтиПоКоду" и "НайтиПоНомеру" \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/MethodSymbolMarkupContentBuilder_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatter_en.properties similarity index 61% rename from src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/MethodSymbolMarkupContentBuilder_en.properties rename to src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatter_en.properties index dd87e8b007d..10ca8a49e46 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/MethodSymbolMarkupContentBuilder_en.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatter_en.properties @@ -1,8 +1,10 @@ -callOptions=Сall options +annotation=Annotation +callOptions=Call options examples=Example export=Export function=Function parameters=Parameters procedure=Procedure returnedValue=Returns -val=Val \ No newline at end of file +val=Val +var=Var \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/MethodSymbolMarkupContentBuilder_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatter_ru.properties similarity index 77% rename from src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/MethodSymbolMarkupContentBuilder_ru.properties rename to src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatter_ru.properties index da11d16cb00..648351fc42b 100644 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/MethodSymbolMarkupContentBuilder_ru.properties +++ b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatter_ru.properties @@ -1,3 +1,4 @@ +annotation=Аннотация callOptions=Варианты вызова examples=Пример export=Экспорт @@ -5,4 +6,5 @@ function=Функция parameters=Параметры procedure=Процедура returnedValue=Возвращаемое значение -val=Знач \ No newline at end of file +val=Знач +var=Перем \ No newline at end of file diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/VariableSymbolMarkupContentBuilder_en.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/VariableSymbolMarkupContentBuilder_en.properties deleted file mode 100644 index f352ad82aa2..00000000000 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/VariableSymbolMarkupContentBuilder_en.properties +++ /dev/null @@ -1,2 +0,0 @@ -var=Var -export=Export diff --git a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/VariableSymbolMarkupContentBuilder_ru.properties b/src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/VariableSymbolMarkupContentBuilder_ru.properties deleted file mode 100644 index 4ef82d6d56b..00000000000 --- a/src/main/resources/com/github/_1c_syntax/bsl/languageserver/hover/VariableSymbolMarkupContentBuilder_ru.properties +++ /dev/null @@ -1,2 +0,0 @@ -var=Перем -export=Экспорт diff --git a/src/main/resources/language-client-aware-appender.xml b/src/main/resources/language-client-aware-appender.xml new file mode 100644 index 00000000000..4f8d680ab46 --- /dev/null +++ b/src/main/resources/language-client-aware-appender.xml @@ -0,0 +1,12 @@ + + + + + ${CONSOLE_LOG_THRESHOLD} + + + ${CONSOLE_LOG_PATTERN} + ${CONSOLE_LOG_CHARSET} + + + \ No newline at end of file diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml new file mode 100644 index 00000000000..be77b622cab --- /dev/null +++ b/src/main/resources/logback-spring.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/AnalyzeProjectOnStartTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/AnalyzeProjectOnStartTest.java index 6fd3108b947..63e409bf0d7 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/AnalyzeProjectOnStartTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/AnalyzeProjectOnStartTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -30,8 +30,8 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; @@ -47,11 +47,13 @@ class AnalyzeProjectOnStartTest { @Autowired private LanguageServerConfiguration configuration; - @SpyBean + + @MockitoSpyBean private ServerContext serverContext; - @MockBean + @MockitoBean private LanguageClient languageClient; + @Autowired private LanguageClientHolder languageClientHolder; @@ -87,7 +89,7 @@ void runAnalysisIfEnabled() { configuration.getDiagnosticsOptions().setAnalyzeOnStart(true); languageClientHolder.connect(languageClient); - var documentContext = TestUtils.getDocumentContext("A = 0", serverContext); + TestUtils.getDocumentContext("A = 0", serverContext); // when analyzeProjectOnStart.handleEvent(new ServerContextPopulatedEvent(serverContext)); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/AutoServerInfoTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/AutoServerInfoTest.java index 48c19510f91..65d7c8f2cfe 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/AutoServerInfoTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/AutoServerInfoTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSBindingTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSBindingTest.java index 4eb6d31417d..326b23f6042 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSBindingTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSBindingTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java index e3974355711..bfa589c3374 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLSPLauncherTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,8 +21,9 @@ */ package com.github._1c_syntax.bsl.languageserver; -import com.ginsberg.junit.exit.ExpectSystemExitWithStatus; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; +import mockit.Mock; +import mockit.MockUp; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -34,6 +35,7 @@ import java.io.PrintStream; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; @SpringBootTest @CleanupContextBeforeClassAndAfterEachTestMethod @@ -44,6 +46,13 @@ class BSLLSPLauncherTest { @BeforeEach void setUpStreams() { + new MockUp() { + @Mock + public void exit(int value) { + throw new RuntimeException(String.valueOf(value)); + } + }; + outContent = new ByteArrayOutputStream(); errContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); @@ -57,34 +66,28 @@ void restoreStreams() { } @Test - @ExpectSystemExitWithStatus(2) - void testParseError() { + void testParseError() throws Exception { // given String[] args = new String[]{"--error"}; - // when - try { - BSLLSPLauncher.main(args); - } catch (RuntimeException ignored) { - // catch prevented system.exit call - } + // when-then + assertThatThrownBy(() -> BSLLSPLauncher.main(args)) + .isInstanceOf(RuntimeException.class) + .hasMessage("2"); // then assertThat(errContent.toString()).containsIgnoringCase("Unknown option: '--error'"); } @Test - @ExpectSystemExitWithStatus(0) void testAnalyze() { // given String[] args = "--analyze --srcDir ./src/test/resources/cli".split(" "); - // when - try { - BSLLSPLauncher.main(args); - } catch (RuntimeException ignored) { - // catch prevented system.exit call - } + // when-then + assertThatThrownBy(() -> BSLLSPLauncher.main(args)) + .isInstanceOf(RuntimeException.class) + .hasMessage("0"); // then // main-method should run without exceptions @@ -94,17 +97,14 @@ void testAnalyze() { } @Test - @ExpectSystemExitWithStatus(0) void testAnalyzeSilent() { // given String[] args = "--analyze --srcDir ./src/test/resources/cli --silent".split(" "); - // when - try { - BSLLSPLauncher.main(args); - } catch (RuntimeException ignored) { - // catch prevented system.exit call - } + // when-then + assertThatThrownBy(() -> BSLLSPLauncher.main(args)) + .isInstanceOf(RuntimeException.class) + .hasMessage("0"); // then // main-method should runs without exceptions @@ -113,17 +113,14 @@ void testAnalyzeSilent() { } @Test - @ExpectSystemExitWithStatus(1) void testAnalyzeError() { // given String[] args = "--analyze --srcDir fake-dir".split(" "); - // when - try { - BSLLSPLauncher.main(args); - } catch (RuntimeException ignored) { - // catch prevented system.exit call - } + // when-then + assertThatThrownBy(() -> BSLLSPLauncher.main(args)) + .isInstanceOf(RuntimeException.class) + .hasMessage("1"); // then // main-method should runs without exceptions @@ -132,17 +129,14 @@ void testAnalyzeError() { } @Test - @ExpectSystemExitWithStatus(0) void testFormat() { // given String[] args = "--format --src ./src/test/resources/cli".split(" "); - // when - try { - BSLLSPLauncher.main(args); - } catch (RuntimeException ignored) { - // catch prevented system.exit call - } + // when-then + assertThatThrownBy(() -> BSLLSPLauncher.main(args)) + .isInstanceOf(RuntimeException.class) + .hasMessage("0"); // then // main-method should runs without exceptions @@ -152,17 +146,14 @@ void testFormat() { } @Test - @ExpectSystemExitWithStatus(0) void testFormatOneFile() { // given String[] args = "--format --src ./src/test/resources/cli/test.bsl.txt".split(" "); - // when - try { - BSLLSPLauncher.main(args); - } catch (RuntimeException ignored) { - // catch prevented system.exit call - } + // when-then + assertThatThrownBy(() -> BSLLSPLauncher.main(args)) + .isInstanceOf(RuntimeException.class) + .hasMessage("0"); // then // main-method should runs without exceptions @@ -172,17 +163,14 @@ void testFormatOneFile() { } @Test - @ExpectSystemExitWithStatus(0) void testFormatTwoFiles() { // given String[] args = "--format --src ./src/test/resources/cli/test.bsl.txt,./src/test/resources/cli/test.bsl".split(" "); - // when - try { - BSLLSPLauncher.main(args); - } catch (RuntimeException ignored) { - // catch prevented system.exit call - } + // when-then + assertThatThrownBy(() -> BSLLSPLauncher.main(args)) + .isInstanceOf(RuntimeException.class) + .hasMessage("0"); // then // main-method should runs without exceptions @@ -192,17 +180,14 @@ void testFormatTwoFiles() { } @Test - @ExpectSystemExitWithStatus(0) void testFormatSilent() { // given String[] args = "--format --src ./src/test/resources/cli --silent".split(" "); - // when - try { - BSLLSPLauncher.main(args); - } catch (RuntimeException ignored) { - // catch prevented system.exit call - } + // when-then + assertThatThrownBy(() -> BSLLSPLauncher.main(args)) + .isInstanceOf(RuntimeException.class) + .hasMessage("0"); // then // main-method should runs without exceptions @@ -211,17 +196,14 @@ void testFormatSilent() { } @Test - @ExpectSystemExitWithStatus(1) void testFormatError() { // given String[] args = "--format --src fake-dir".split(" "); - // when - try { - BSLLSPLauncher.main(args); - } catch (RuntimeException ignored) { - // catch prevented system.exit call - } + // when-then + assertThatThrownBy(() -> BSLLSPLauncher.main(args)) + .isInstanceOf(RuntimeException.class) + .hasMessage("1"); // then // main-method should runs without exceptions @@ -230,17 +212,14 @@ void testFormatError() { } @Test - @ExpectSystemExitWithStatus(0) void testVersion() { // given String[] args = {"-v"}; - // when - try { - BSLLSPLauncher.main(args); - } catch (RuntimeException ignored) { - // catch prevented system.exit call - } + // when-then + assertThatThrownBy(() -> BSLLSPLauncher.main(args)) + .isInstanceOf(RuntimeException.class) + .hasMessage("0"); // then // main-method should runs without exceptions @@ -270,11 +249,7 @@ void testWithoutCommandWithConfig() { String[] args = "-c .".split(" "); // when - try { - BSLLSPLauncher.main(args); - } catch (RuntimeException ignored) { - // catch prevented system.exit call - } + BSLLSPLauncher.main(args); // then assertThat(outContent.toString()).contains("LanguageServerStartCommand"); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServerTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServerTest.java index 43bdf5e4705..30193c342de 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServerTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLLanguageServerTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,15 +21,17 @@ */ package com.github._1c_syntax.bsl.languageserver; -import com.ginsberg.junit.exit.ExpectSystemExitWithStatus; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; import com.github._1c_syntax.utils.Absolute; +import mockit.Mock; +import mockit.MockUp; import org.eclipse.lsp4j.ClientCapabilities; import org.eclipse.lsp4j.InitializeParams; import org.eclipse.lsp4j.InitializeResult; import org.eclipse.lsp4j.RenameCapabilities; import org.eclipse.lsp4j.TextDocumentClientCapabilities; import org.eclipse.lsp4j.WorkspaceFolder; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -40,6 +42,7 @@ import static com.github._1c_syntax.bsl.languageserver.util.TestUtils.PATH_TO_METADATA; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; @SpringBootTest @CleanupContextBeforeClassAndAfterEachTestMethod @@ -48,12 +51,22 @@ class BSLLanguageServerTest { @Autowired private BSLLanguageServer server; + @BeforeEach + void setUp() { + new MockUp() { + @Mock + public void exit(int value) { + throw new RuntimeException(String.valueOf(value)); + } + }; + } + @Test void initialize() throws ExecutionException, InterruptedException { // given InitializeParams params = new InitializeParams(); - WorkspaceFolder workspaceFolder = new WorkspaceFolder(Absolute.path(PATH_TO_METADATA).toUri().toString()); + WorkspaceFolder workspaceFolder = new WorkspaceFolder(Absolute.path(PATH_TO_METADATA).toUri().toString(), "test"); List workspaceFolders = List.of(workspaceFolder); params.setWorkspaceFolders(workspaceFolders); @@ -69,7 +82,7 @@ void initializeRename() throws ExecutionException, InterruptedException { // given InitializeParams params = new InitializeParams(); - WorkspaceFolder workspaceFolder = new WorkspaceFolder(Absolute.path(PATH_TO_METADATA).toUri().toString()); + WorkspaceFolder workspaceFolder = new WorkspaceFolder(Absolute.path(PATH_TO_METADATA).toUri().toString(), "test"); List workspaceFolders = List.of(workspaceFolder); params.setWorkspaceFolders(workspaceFolders); @@ -94,24 +107,22 @@ void shutdown() throws ExecutionException, InterruptedException { } @Test - @ExpectSystemExitWithStatus(1) void exitWithoutShutdown() { - // when - server.exit(); - - // then ExpectSystemExitWithStatus should not throw exception + // when-then + assertThatThrownBy(() -> server.exit()) + .isInstanceOf(RuntimeException.class) + .hasMessage("1"); } @Test - @ExpectSystemExitWithStatus(0) void exitWithShutdown() { // given server.shutdown(); - // when - server.exit(); - - // then ExpectSystemExitWithStatus should not throw exception + // when-then + assertThatThrownBy(() -> server.exit()) + .isInstanceOf(RuntimeException.class) + .hasMessage("0"); } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentServiceTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentServiceTest.java index 0949d81cc58..17d3381bca7 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentServiceTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentServiceTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -176,6 +176,7 @@ private TextDocumentItem getTextDocumentItem() throws IOException { } private TextDocumentIdentifier getTextDocumentIdentifier() { + // TODO: Переделать на TestUtils.getTextDocumentIdentifier(); File file = getTestFile(); String uri = file.toURI().toString(); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/ParentProcessWatcherTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/ParentProcessWatcherTest.java index 11d7c3a0235..fb640bf3a1a 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/ParentProcessWatcherTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/ParentProcessWatcherTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/WorkDoneProgressHelperTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/WorkDoneProgressHelperTest.java index 201212a40e3..b177700edbc 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/WorkDoneProgressHelperTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/WorkDoneProgressHelperTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/MeasureCollectorTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/MeasureCollectorTest.java index 40bb89fb9fb..45534f9ae19 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/MeasureCollectorTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/MeasureCollectorTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/MeasuresSubsystemTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/MeasuresSubsystemTest.java index 95183c6fec4..6ca7321ff70 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/MeasuresSubsystemTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/aop/measures/MeasuresSubsystemTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/aop/sentry/PermissionFilterBeforeSendCallbackTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/aop/sentry/PermissionFilterBeforeSendCallbackTest.java index 81ec4950cf1..a3acd8ed7f1 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/aop/sentry/PermissionFilterBeforeSendCallbackTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/aop/sentry/PermissionFilterBeforeSendCallbackTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cfg/ControlFlowGraphBuilderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/cfg/ControlFlowGraphBuilderTest.java index b3c5712ea57..47ff170457e 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cfg/ControlFlowGraphBuilderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/cfg/ControlFlowGraphBuilderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -62,10 +62,11 @@ void linearBlockCanBeBuilt() { @Test void branchingWithOneBranch() { - var code = "А = 1;\n" + - "Если Б = 2 Тогда\n" + - " В = 4;\n" + - "КонецЕсли;"; + var code = """ + А = 1; + Если Б = 2 Тогда + В = 4; + КонецЕсли;"""; var parseTree = parse(code); var builder = new CfgBuildingParseTreeVisitor(); @@ -97,12 +98,12 @@ void branchingWithOneBranch() { @Test void conditionWithElse() { - var code = "А = 1;\n" + - "Если Б = 2 Тогда\n" + - " В = 4;\n" + - "Иначе\n" + - " В = 5;" + - "КонецЕсли;"; + var code = """ + А = 1; + Если Б = 2 Тогда + В = 4; + Иначе + В = 5;КонецЕсли;"""; var parseTree = parse(code); var builder = new CfgBuildingParseTreeVisitor(); @@ -129,15 +130,14 @@ void conditionWithElse() { @Test void multipleConditionsTest() { - var code = "Если Б = 1 Тогда\n" + - " В = 1;\n" + - "ИначеЕсли Б = 2 Тогда\n" + - " В = 2;\n" + - "ИначеЕсли Б = 3 Тогда\n" + - " В = 3;" + - "Иначе\n" + - " В = 4;" + - "КонецЕсли;"; + var code = """ + Если Б = 1 Тогда + В = 1; + ИначеЕсли Б = 2 Тогда + В = 2; + ИначеЕсли Б = 3 Тогда + В = 3;Иначе + В = 4;КонецЕсли;"""; var parseTree = parse(code); var builder = new CfgBuildingParseTreeVisitor(); @@ -181,10 +181,11 @@ void multipleConditionsTest() { @Test void whileLoopTest() { - var code = "А = 1;\n" + - "Пока Б = 1 Цикл\n" + - " В = 1;\n" + - "КонецЦикла;"; + var code = """ + А = 1; + Пока Б = 1 Цикл + В = 1; + КонецЦикла;"""; var parseTree = parse(code); var builder = new CfgBuildingParseTreeVisitor(); @@ -218,19 +219,20 @@ void whileLoopTest() { @Test void testInnerLoops() { - var code = "А = 1;\n" + - "Пока Б = 1 Цикл\n" + - " В = 1;\n" + - " Если А = 1 Тогда\n" + - " Продолжить;\n" + - " КонецЕсли;\n" + - " Для Сч = 1 По 5 Цикл\n" + - " Б = 1;\n" + - " Прервать;\n" + - " В = 2;\n" + - " КонецЦикла;\n" + - " Прервано = Истина;\n" + - "КонецЦикла;"; + var code = """ + А = 1; + Пока Б = 1 Цикл + В = 1; + Если А = 1 Тогда + Продолжить; + КонецЕсли; + Для Сч = 1 По 5 Цикл + Б = 1; + Прервать; + В = 2; + КонецЦикла; + Прервано = Истина; + КонецЦикла;"""; var parseTree = parse(code); var builder = new CfgBuildingParseTreeVisitor(); @@ -288,11 +290,12 @@ void testInnerLoops() { @Test void tryHandlerFlowTest() { - var code = "Попытка\n" + - " А = 1;\n" + - "Исключение\n" + - " Б = 1;\n" + - "КонецПопытки"; + var code = """ + Попытка + А = 1; + Исключение + Б = 1; + КонецПопытки"""; var parseTree = parse(code); var builder = new CfgBuildingParseTreeVisitor(); @@ -315,10 +318,11 @@ void tryHandlerFlowTest() { @Test void linearBlockWithLabel() { - var code = "А = 1;\n" + - "Б = 2;\n" + - "~Прыг:\n" + - "В = 4;"; + var code = """ + А = 1; + Б = 2; + ~Прыг: + В = 4;"""; var parseTree = parse(code); var builder = new CfgBuildingParseTreeVisitor(); @@ -339,12 +343,13 @@ void linearBlockWithLabel() { @Test void linearBlockWithJumpToLabel() { - var code = "А = 1;\n" + - "Б = 2;\n" + - "~Прыг:\n" + - "В = 4;\n" + - "Перейти ~Прыг;\n" + - "МертвыйКод = Истина;"; + var code = """ + А = 1; + Б = 2; + ~Прыг: + В = 4; + Перейти ~Прыг; + МертвыйКод = Истина;"""; var parseTree = parse(code); var builder = new CfgBuildingParseTreeVisitor(); @@ -376,7 +381,7 @@ void hardcoreCrazyJumpingTest() { var list = graph.vertexSet().stream() .filter(x -> x instanceof BasicBlockVertex) - .filter(x -> ((BasicBlockVertex) x).statements().size() == 0) + .filter(x -> ((BasicBlockVertex) x).statements().isEmpty()) .collect(Collectors.toList()); assertThat(list).isEmpty(); @@ -385,11 +390,12 @@ void hardcoreCrazyJumpingTest() { @Test void preprocessorSingleIfBranching() { - var code = "А = 1;\n" + - "#Если Сервер Тогда\n" + - " Б = 2;\n" + - "#КонецЕсли\n" + - "В = 3;"; + var code = """ + А = 1; + #Если Сервер Тогда + Б = 2; + #КонецЕсли + В = 3;"""; var parseTree = parse(code); var builder = new CfgBuildingParseTreeVisitor(); @@ -414,13 +420,13 @@ void preprocessorSingleIfBranching() { @Test void preprocessorIfWithElseBranching() { - var code = "А = 1;\n" + - "#Если Сервер Тогда\n" + - " Б = 2;\n" + - "#Иначе\n" + - " Б = 3;" + - "#КонецЕсли\n" + - "В = 3;"; + var code = """ + А = 1; + #Если Сервер Тогда + Б = 2; + #Иначе + Б = 3;#КонецЕсли + В = 3;"""; var parseTree = parse(code); var builder = new CfgBuildingParseTreeVisitor(); @@ -447,17 +453,17 @@ void preprocessorIfWithElseBranching() { @Test void preprocessorIfWithElseIfBranching() { - var code = "А = 1;\n" + - "#Если Сервер Тогда\n" + - " Б = 2;\n" + - "#ИначеЕсли ВебКлиент Тогда\n" + - " Б = 3;\n" + - "#ИначеЕсли МобильныйКлиент Тогда\n" + - " Б = 4;\n" + - "#Иначе\n" + - " Б = 5;" + - "#КонецЕсли\n" + - "В = 3;"; + var code = """ + А = 1; + #Если Сервер Тогда + Б = 2; + #ИначеЕсли ВебКлиент Тогда + Б = 3; + #ИначеЕсли МобильныйКлиент Тогда + Б = 4; + #Иначе + Б = 5;#КонецЕсли + В = 3;"""; var parseTree = parse(code); var builder = new CfgBuildingParseTreeVisitor(); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommandTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommandTest.java index 0c41875a1f1..b64c3a8472c 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommandTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/VersionCommandTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -25,8 +25,8 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @@ -35,7 +35,7 @@ @DirtiesContext class VersionCommandTest { - @MockBean + @MockitoBean private ServerInfo serverInfo; @Autowired diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/WebsocketCommandTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/WebsocketCommandTest.java index 74eaa2a2d28..720eca222bd 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/WebsocketCommandTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/cli/WebsocketCommandTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -26,7 +26,7 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import picocli.CommandLine; import picocli.spring.PicocliSpringFactory; @@ -40,7 +40,7 @@ @CleanupContextBeforeClassAndAfterEachTestMethod class WebsocketCommandTest { - @SpyBean + @MockitoSpyBean private LanguageServerConfiguration configuration; @Autowired diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/codeactions/DisableDiagnosticTriggeringSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codeactions/DisableDiagnosticTriggeringSupplierTest.java index 68c74eeaa03..b64fdef0367 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/codeactions/DisableDiagnosticTriggeringSupplierTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codeactions/DisableDiagnosticTriggeringSupplierTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,9 +23,9 @@ import com.github._1c_syntax.bsl.languageserver.configuration.Language; 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.util.TestUtils; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import jakarta.annotation.PostConstruct; import org.eclipse.lsp4j.CodeAction; import org.eclipse.lsp4j.CodeActionContext; import org.eclipse.lsp4j.CodeActionParams; @@ -37,7 +37,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; -import javax.annotation.PostConstruct; import java.util.List; import java.util.stream.Collectors; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/codeactions/ExtractStructureConstructorSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codeactions/ExtractStructureConstructorSupplierTest.java new file mode 100644 index 00000000000..0cb85d36fcf --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codeactions/ExtractStructureConstructorSupplierTest.java @@ -0,0 +1,207 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.codeactions; + +import com.github._1c_syntax.bsl.languageserver.configuration.Language; +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.util.TestUtils; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import org.eclipse.lsp4j.CodeAction; +import org.eclipse.lsp4j.CodeActionContext; +import org.eclipse.lsp4j.CodeActionParams; +import org.eclipse.lsp4j.Diagnostic; +import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.eclipse.lsp4j.TextEdit; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +class ExtractStructureConstructorSupplierTest { + + @Autowired + private LanguageServerConfiguration configuration; + + @Autowired + private ExtractStructureConstructorSupplier codeActionSupplier; + private DocumentContext documentContext; + private CodeActionParams params; + + @Test + void testGetCodeActions() { + + // given + setRange(Ranges.create(1, 21, 23)); + + // when + List codeActions = codeActionSupplier.getCodeActions(params, documentContext); + + assertThat(codeActions) + .hasSize(1) + .anyMatch(codeAction -> codeAction.getTitle().equals("Unwrap constructor")); + + assertThat((((ArrayList) (codeActions.get(0).getEdit().getChanges().values()).toArray()[0]))) + .hasSize(4) + .anyMatch(textedit -> ((TextEdit) textedit).getNewText().equals("()")) + .anyMatch(textedit -> ((TextEdit) textedit).getNewText().equals("Структура.Insert(\"а\", а);\n")) + .anyMatch(textedit -> ((TextEdit) textedit).getNewText().equals("Структура.Insert(\"б\", б);\n")) + .anyMatch(textedit -> ((TextEdit) textedit).getNewText().equals("Структура.Insert(\"в\", в);\n")) + ; + } + + @Test + void testGetCodeActionsDouble() { + + // given + setRange(Ranges.create(6, 14, 17)); + + // when + List codeActions = codeActionSupplier.getCodeActions(params, documentContext); + + assertThat(codeActions) + .hasSize(0) + .noneMatch(codeAction -> codeAction.getTitle().equals("Unwrap constructor")); + } + + @Test + void testGetCodeActionsFind() { + + // given + setRange(Ranges.create(10, 76, 78)); + + // when + List codeActions = codeActionSupplier.getCodeActions(params, documentContext); + + assertThat(codeActions) + .hasSize(0) + .noneMatch(codeAction -> codeAction.getTitle().equals("Unwrap constructor")); + } + + @Test + void testGetCodeActionsArray() { + + // given + setRange(Ranges.create(12, 21, 23)); + + // when + List codeActions = codeActionSupplier.getCodeActions(params, documentContext); + + assertThat(codeActions) + .hasSize(0) + .noneMatch(codeAction -> codeAction.getTitle().equals("Unwrap constructor")); + + } + + @Test + void testGetCodeActionsNOParams() { + + // given + setRange(Ranges.create(14, 21, 23)); + + // when + List codeActions = codeActionSupplier.getCodeActions(params, documentContext); + + assertThat(codeActions) + .hasSize(0) + .noneMatch(codeAction -> codeAction.getTitle().equals("Unwrap constructor")); + + } + + @Test + void testGetCodeActionsEmptyParams() { + + // given + setRange(Ranges.create(14, 21, 23)); + + // when + List codeActions = codeActionSupplier.getCodeActions(params, documentContext); + + assertThat(codeActions) + .hasSize(0) + .noneMatch(codeAction -> codeAction.getTitle().equals("Unwrap constructor")); + + } + + @Test + void testGetCodeActionsIdentifier() { + + // given + setRange(Ranges.create(15, 21, 23)); + + // when + List codeActions = codeActionSupplier.getCodeActions(params, documentContext); + + assertThat(codeActions) + .hasSize(0) + .noneMatch(codeAction -> codeAction.getTitle().equals("Unwrap constructor")); + + } + + @Test + void testGetCodeActionsObject() { + + // given + setRange(Ranges.create(17, 21, 23)); + + // when + List codeActions = codeActionSupplier.getCodeActions(params, documentContext); + + assertThat(codeActions) + .hasSize(1) + .anyMatch(codeAction -> codeAction.getTitle().equals("Unwrap constructor")); + assertThat((((ArrayList) (codeActions.get(0).getEdit().getChanges().values()).toArray()[0]))) + .hasSize(4) + .anyMatch(textedit -> ((TextEdit) textedit).getNewText().equals("()")) + .anyMatch(textedit -> ((TextEdit) textedit).getNewText().equals("Чтото.Поле.Insert(\"а\", а);\n")) + .anyMatch(textedit -> ((TextEdit) textedit).getNewText().equals("Чтото.Поле.Insert(\"б\", б);\n")) + .anyMatch(textedit -> ((TextEdit) textedit).getNewText().equals("Чтото.Поле.Insert(\"в\", в);\n")) + ; + + } + + void setRange(Range range) { + configuration.setLanguage(Language.EN); + + String filePath = "./src/test/resources/suppliers/extractStructureConstructor.bsl"; + documentContext = TestUtils.getDocumentContextFromFile(filePath); + + List diagnostics = new ArrayList<>(); + + TextDocumentIdentifier textDocumentIdentifier = new TextDocumentIdentifier(documentContext.getUri().toString()); + + CodeActionContext codeActionContext = new CodeActionContext(); + codeActionContext.setDiagnostics(diagnostics); + + params = new CodeActionParams(); + params.setRange(range); + params.setTextDocument(textDocumentIdentifier); + params.setContext(codeActionContext); + } + +} \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/codeactions/GenerateStandardRegionsSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codeactions/GenerateStandardRegionsSupplierTest.java index b9ada46c989..0dc18a2e8c8 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/codeactions/GenerateStandardRegionsSupplierTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codeactions/GenerateStandardRegionsSupplierTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixSupplierTest.java index c4401f7b04c..5a6d302bb4f 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixSupplierTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codeactions/QuickFixSupplierTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/AbstractRunTestsCodeLensSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/AbstractRunTestsCodeLensSupplierTest.java new file mode 100644 index 00000000000..bef79329e0f --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/AbstractRunTestsCodeLensSupplierTest.java @@ -0,0 +1,116 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.codelenses; + +import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; +import com.github._1c_syntax.bsl.languageserver.context.AbstractServerContextAwareTest; +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.events.LanguageServerInitializeRequestReceivedEvent; +import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import org.eclipse.lsp4j.ClientInfo; +import org.eclipse.lsp4j.CodeLens; +import org.eclipse.lsp4j.InitializeParams; +import org.eclipse.lsp4j.services.LanguageServer; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.annotation.Bean; + +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +@SpringBootTest +@CleanupContextBeforeClassAndAfterEachTestMethod +class AbstractRunTestsCodeLensSupplierTest extends AbstractServerContextAwareTest { + + @Autowired + private AbstractRunTestsCodeLensSupplier supplier; + + @Autowired + private ApplicationEventPublisher eventPublisher; + + @ParameterizedTest + @CsvSource({ + "./src/test/resources/codelenses/AbstractRunTestCodeLensSupplier.os, unknown, false", + "./src/test/resources/codelenses/tests/AbstractRunTestCodeLensSupplier.os, unknown, false", + "./src/test/resources/codelenses/AbstractRunTestCodeLensSupplier.os, Visual Studio Code, false", + "./src/test/resources/codelenses/tests/AbstractRunTestCodeLensSupplier.os, Visual Studio Code, true" + }) + void testIsApplicable(String filePath, String clientName, boolean expected) { + // given + var documentContext = TestUtils.getDocumentContextFromFile(filePath); + initializeServer("./src/test/resources/codelenses", clientName); + + // when + var result = supplier.isApplicable(documentContext); + + // then + assertThat(result).isEqualTo(expected); + } + + private void initializeServer(String path, String clientName) { + initServerContext(path); + + var initializeParams = new InitializeParams(); + initializeParams.setClientInfo( + new ClientInfo(clientName, "1.0.0") + ); + + var event = new LanguageServerInitializeRequestReceivedEvent( + mock(LanguageServer.class), + initializeParams + ); + eventPublisher.publishEvent(event); + } + + @TestConfiguration + static class TestConfig { + @Bean + public AbstractRunTestsCodeLensSupplier supplier(LanguageServerConfiguration configuration) { + return new AbstractRunTestsCodeLensSupplier<>(configuration) { + + @Override + public List getCodeLenses(DocumentContext documentContext) { + return Collections.emptyList(); + } + + @Override + public Class getCodeLensDataClass() { + return DefaultCodeLensData.class; + } + + @Override + protected AbstractRunTestsCodeLensSupplier getSelf() { + return this; + } + }; + } + } + +} \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CognitiveComplexityCodeLensSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CognitiveComplexityCodeLensSupplierTest.java index d2c60ed1bb7..df3197240b4 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CognitiveComplexityCodeLensSupplierTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CognitiveComplexityCodeLensSupplierTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,6 +22,7 @@ package com.github._1c_syntax.bsl.languageserver.codelenses; import com.github._1c_syntax.bsl.languageserver.codelenses.AbstractMethodComplexityCodeLensSupplier.ComplexityCodeLensData; +import com.github._1c_syntax.bsl.languageserver.commands.complexity.ToggleComplexityInlayHintsCommandArguments; import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; @@ -75,11 +76,18 @@ void testGetCodeLens() { assertThat(codeLenses) .hasSize(2) - .anyMatch(codeLens -> codeLens.getRange().equals(firstMethod.getSubNameRange())) - .anyMatch(codeLens -> codeLens.getCommand().getTitle().contains(String.valueOf(complexityFirstMethod))) - .anyMatch(codeLens -> codeLens.getRange().equals(secondMethod.getSubNameRange())) - .anyMatch(codeLens -> codeLens.getCommand().getTitle().contains(String.valueOf(complexitySecondMethod))) - ; + .anySatisfy(codeLens -> { + assertThat(codeLens.getRange()).isEqualTo(firstMethod.getSubNameRange()); + assertThat(codeLens.getCommand().getTitle()).contains(String.valueOf(complexityFirstMethod)); + assertThat(codeLens.getCommand().getCommand()).isEqualTo("toggleCognitiveComplexityInlayHints"); + assertThat(((ToggleComplexityInlayHintsCommandArguments) codeLens.getCommand().getArguments().get(0)).getMethodName()).isEqualTo(firstMethod.getName()); + }) + .anySatisfy(codeLens -> { + assertThat(codeLens.getRange()).isEqualTo(secondMethod.getSubNameRange()); + assertThat(codeLens.getCommand().getTitle()).contains(String.valueOf(complexitySecondMethod)); + assertThat(codeLens.getCommand().getCommand()).isEqualTo("toggleCognitiveComplexityInlayHints"); + assertThat(((ToggleComplexityInlayHintsCommandArguments) codeLens.getCommand().getArguments().get(0)).getMethodName()).isEqualTo(secondMethod.getName()); + }); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CyclomaticComplexityCodeLensSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CyclomaticComplexityCodeLensSupplierTest.java index 5be68d0f425..17d9461254b 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CyclomaticComplexityCodeLensSupplierTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/CyclomaticComplexityCodeLensSupplierTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,6 +22,7 @@ package com.github._1c_syntax.bsl.languageserver.codelenses; import com.github._1c_syntax.bsl.languageserver.codelenses.AbstractMethodComplexityCodeLensSupplier.ComplexityCodeLensData; +import com.github._1c_syntax.bsl.languageserver.commands.complexity.ToggleComplexityInlayHintsCommandArguments; import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; @@ -75,11 +76,18 @@ void testGetCodeLens() { assertThat(codeLenses) .hasSize(2) - .anyMatch(codeLens -> codeLens.getRange().equals(firstMethod.getSubNameRange())) - .anyMatch(codeLens -> codeLens.getCommand().getTitle().contains(String.valueOf(complexityFirstMethod))) - .anyMatch(codeLens -> codeLens.getRange().equals(secondMethod.getSubNameRange())) - .anyMatch(codeLens -> codeLens.getCommand().getTitle().contains(String.valueOf(complexitySecondMethod))) - ; + .anySatisfy(codeLens -> { + assertThat(codeLens.getRange()).isEqualTo(firstMethod.getSubNameRange()); + assertThat(codeLens.getCommand().getTitle()).contains(String.valueOf(complexityFirstMethod)); + assertThat(codeLens.getCommand().getCommand()).isEqualTo("toggleCyclomaticComplexityInlayHints"); + assertThat(((ToggleComplexityInlayHintsCommandArguments) codeLens.getCommand().getArguments().get(0)).getMethodName()).isEqualTo(firstMethod.getName()); + }) + .anySatisfy(codeLens -> { + assertThat(codeLens.getRange()).isEqualTo(secondMethod.getSubNameRange()); + assertThat(codeLens.getCommand().getTitle()).contains(String.valueOf(complexitySecondMethod)); + assertThat(codeLens.getCommand().getCommand()).isEqualTo("toggleCyclomaticComplexityInlayHints"); + assertThat(((ToggleComplexityInlayHintsCommandArguments) codeLens.getCommand().getArguments().get(0)).getMethodName()).isEqualTo(secondMethod.getName()); + }); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/RunAllTestsCodeLensSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/RunAllTestsCodeLensSupplierTest.java new file mode 100644 index 00000000000..44afd6bd973 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/RunAllTestsCodeLensSupplierTest.java @@ -0,0 +1,122 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.codelenses; + +import com.github._1c_syntax.bsl.languageserver.codelenses.testrunner.TestRunnerAdapter; +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.events.LanguageServerInitializeRequestReceivedEvent; +import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import org.eclipse.lsp4j.ClientInfo; +import org.eclipse.lsp4j.CodeLens; +import org.eclipse.lsp4j.InitializeParams; +import org.eclipse.lsp4j.services.LanguageServer; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@SpringBootTest +@CleanupContextBeforeClassAndAfterEachTestMethod +class RunAllTestsCodeLensSupplierTest { + + @Autowired + private RunAllTestsCodeLensSupplier supplier; + + @Autowired + private ApplicationEventPublisher eventPublisher; + + @MockitoSpyBean + private TestRunnerAdapter testRunnerAdapter; + + private DocumentContext documentContext; + + @BeforeEach + void init() { + var filePath = "./src/test/resources/codelenses/RunAllTestsCodeLensSupplier.os"; + documentContext = TestUtils.getDocumentContextFromFile(filePath); + } + + @Test + void testDryRun() { + // given + initializeServer("Visual Studio Code"); + + // when + var codeLenses = supplier.getCodeLenses(documentContext); + + // then + assertThat(codeLenses).isNotNull(); + } + + @Test + void testRunWithMockedTestIds() { + // given + initializeServer("Visual Studio Code"); + + when(testRunnerAdapter.getTestIds(documentContext)) + .thenReturn(List.of("testName")); + + // when + var codeLenses = supplier.getCodeLenses(documentContext); + + // then + assertThat(codeLenses).isNotNull(); + } + + @Test + void testResolve() { + // given + CodeLens codeLens = new CodeLens(); + DefaultCodeLensData codeLensData = new DefaultCodeLensData( + documentContext.getUri(), + supplier.getId() + ); + + // when + var resolvedCodeLens = supplier.resolve(documentContext, codeLens, codeLensData); + + // then + assertThat(resolvedCodeLens.getCommand()).isNotNull(); + } + + private void initializeServer(String clientName) { + var initializeParams = new InitializeParams(); + initializeParams.setClientInfo( + new ClientInfo(clientName, "1.0.0") + ); + + var event = new LanguageServerInitializeRequestReceivedEvent( + mock(LanguageServer.class), + initializeParams + ); + eventPublisher.publishEvent(event); + } +} \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/RunTestCodeLensSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/RunTestCodeLensSupplierTest.java new file mode 100644 index 00000000000..160ddef03a5 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/RunTestCodeLensSupplierTest.java @@ -0,0 +1,123 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.codelenses; + +import com.github._1c_syntax.bsl.languageserver.codelenses.testrunner.TestRunnerAdapter; +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.events.LanguageServerInitializeRequestReceivedEvent; +import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import org.eclipse.lsp4j.ClientInfo; +import org.eclipse.lsp4j.CodeLens; +import org.eclipse.lsp4j.InitializeParams; +import org.eclipse.lsp4j.services.LanguageServer; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@SpringBootTest +@CleanupContextBeforeClassAndAfterEachTestMethod +class RunTestCodeLensSupplierTest { + + @Autowired + private RunTestCodeLensSupplier supplier; + + @Autowired + private ApplicationEventPublisher eventPublisher; + + @MockitoSpyBean + private TestRunnerAdapter testRunnerAdapter; + + private DocumentContext documentContext; + + @BeforeEach + void init() { + var filePath = "./src/test/resources/codelenses/RunTestCodeLensSupplier.os"; + documentContext = TestUtils.getDocumentContextFromFile(filePath); + } + + @Test + void testDryRun() { + // given + initializeServer("Visual Studio Code"); + + // when + var codeLenses = supplier.getCodeLenses(documentContext); + + // then + assertThat(codeLenses).isNotNull(); + } + + @Test + void testRunWithMockedTestIds() { + // given + initializeServer("Visual Studio Code"); + + when(testRunnerAdapter.getTestIds(documentContext)) + .thenReturn(List.of("testName")); + + // when + var codeLenses = supplier.getCodeLenses(documentContext); + + // then + assertThat(codeLenses).isNotNull(); + } + + @Test + void testResolve() { + // given + CodeLens codeLens = new CodeLens(); + RunTestCodeLensSupplier.RunTestCodeLensData codeLensData = new RunTestCodeLensSupplier.RunTestCodeLensData( + documentContext.getUri(), + supplier.getId(), + "testName" + ); + + // when + var resolvedCodeLens = supplier.resolve(documentContext, codeLens, codeLensData); + + // then + assertThat(resolvedCodeLens.getCommand()).isNotNull(); + } + + private void initializeServer(String clientName) { + var initializeParams = new InitializeParams(); + initializeParams.setClientInfo( + new ClientInfo(clientName, "1.0.0") + ); + + var event = new LanguageServerInitializeRequestReceivedEvent( + mock(LanguageServer.class), + initializeParams + ); + eventPublisher.publishEvent(event); + } +} \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/testrunner/TestRunnerAdapterTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/testrunner/TestRunnerAdapterTest.java new file mode 100644 index 00000000000..1d8a06003aa --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/codelenses/testrunner/TestRunnerAdapterTest.java @@ -0,0 +1,54 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.codelenses.testrunner; + +import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +class TestRunnerAdapterTest { + + @Autowired + private TestRunnerAdapter testRunnerAdapter; + + @Autowired + private LanguageServerConfiguration configuration; + + @Test + void whenComputeTestsByLanguageServer_thenContainsTests() { + // given + var documentContext = TestUtils.getDocumentContextFromFile("src/test/resources/codelenses/testrunner/TestRunnerAdapter.os"); + configuration.getCodeLensOptions().getTestRunnerAdapterOptions().setGetTestsByTestRunner(false); + + // when + var testIds = testRunnerAdapter.getTestIds(documentContext); + + // then + assertThat(testIds).hasSize(1); + assertThat(testIds.get(0)).isEqualTo("Тест1"); + } +} \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/color/ConstructorColorInformationSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/color/ConstructorColorInformationSupplierTest.java index 638d593be06..1af94f1b298 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/color/ConstructorColorInformationSupplierTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/color/ConstructorColorInformationSupplierTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/color/ConstructorColorPresentationSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/color/ConstructorColorPresentationSupplierTest.java index f4c0fbe36a9..55d9b270ebf 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/color/ConstructorColorPresentationSupplierTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/color/ConstructorColorPresentationSupplierTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/color/WebColorInformationSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/color/WebColorInformationSupplierTest.java index 07579901e57..7e9f815826a 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/color/WebColorInformationSupplierTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/color/WebColorInformationSupplierTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/color/WebColorPresentationSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/color/WebColorPresentationSupplierTest.java index 175edf60725..4a946fc4b79 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/color/WebColorPresentationSupplierTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/color/WebColorPresentationSupplierTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/commands/ToggleCognitiveComplexityInlayHintsCommandSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/commands/ToggleCognitiveComplexityInlayHintsCommandSupplierTest.java new file mode 100644 index 00000000000..0fde97d4af2 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/commands/ToggleCognitiveComplexityInlayHintsCommandSupplierTest.java @@ -0,0 +1,75 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.commands; + +import com.github._1c_syntax.bsl.languageserver.commands.complexity.ToggleComplexityInlayHintsCommandArguments; +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import com.github._1c_syntax.bsl.languageserver.inlayhints.CognitiveComplexityInlayHintSupplier; +import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.bean.override.mockito.MockitoBean; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +@SpringBootTest +@CleanupContextBeforeClassAndAfterEachTestMethod +class ToggleCognitiveComplexityInlayHintsCommandSupplierTest { + private final static String FILE_PATH = "./src/test/resources/commands/ToggleCognitiveComplexityInlayHintsCommandSupplier.bsl"; + + @MockitoBean + private CognitiveComplexityInlayHintSupplier complexityInlayHintSupplier; + + @Autowired + private ToggleCognitiveComplexityInlayHintsCommandSupplier supplier; + + @Test + void testExecute() { + + // given + var documentContext = TestUtils.getDocumentContextFromFile(FILE_PATH); + MethodSymbol firstMethod = documentContext.getSymbolTree().getMethods().get(0); + + var methodName = firstMethod.getName(); + + var arguments = new ToggleComplexityInlayHintsCommandArguments( + documentContext.getUri(), + supplier.getId(), + methodName + ); + + // when + Optional result = supplier.execute(arguments); + + // then + assertThat(result).isEmpty(); + verify(complexityInlayHintSupplier, times(1)).toggleHints(documentContext.getUri(), methodName); + + } + +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/commands/ToggleCyclomaticComplexityInlayHintsCommandSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/commands/ToggleCyclomaticComplexityInlayHintsCommandSupplierTest.java new file mode 100644 index 00000000000..ba30aeb062c --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/commands/ToggleCyclomaticComplexityInlayHintsCommandSupplierTest.java @@ -0,0 +1,75 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.commands; + +import com.github._1c_syntax.bsl.languageserver.commands.complexity.ToggleComplexityInlayHintsCommandArguments; +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import com.github._1c_syntax.bsl.languageserver.inlayhints.CyclomaticComplexityInlayHintSupplier; +import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.bean.override.mockito.MockitoBean; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +@SpringBootTest +@CleanupContextBeforeClassAndAfterEachTestMethod +class ToggleCyclomaticComplexityInlayHintsCommandSupplierTest { + private final static String FILE_PATH = "./src/test/resources/commands/ToggleCyclomaticComplexityInlayHintsCommandSupplier.bsl"; + + @MockitoBean + private CyclomaticComplexityInlayHintSupplier complexityInlayHintSupplier; + + @Autowired + private ToggleCyclomaticComplexityInlayHintsCommandSupplier supplier; + + @Test + void testExecute() { + + // given + var documentContext = TestUtils.getDocumentContextFromFile(FILE_PATH); + MethodSymbol firstMethod = documentContext.getSymbolTree().getMethods().get(0); + + var methodName = firstMethod.getName(); + + var arguments = new ToggleComplexityInlayHintsCommandArguments( + documentContext.getUri(), + supplier.getId(), + methodName + ); + + // when + Optional result = supplier.execute(arguments); + + // then + assertThat(result).isEmpty(); + verify(complexityInlayHintSupplier, times(1)).toggleHints(documentContext.getUri(), methodName); + + } + +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/ConfigurationTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/ConfigurationTest.java index 9f2614ec855..75d30a08b62 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/ConfigurationTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/ConfigurationTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/GlobalConfigurationTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/GlobalConfigurationTest.java index 776bb900ca4..62c9af6f15b 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/GlobalConfigurationTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/GlobalConfigurationTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java index 9d84157445b..5eda351131c 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/LanguageServerConfigurationTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -25,6 +25,7 @@ import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.DiagnosticsOptions; import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.Mode; import com.github._1c_syntax.bsl.languageserver.configuration.diagnostics.SkipSupport; +import com.github._1c_syntax.bsl.languageserver.configuration.inlayhints.InlayHintOptions; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; import com.github._1c_syntax.utils.Absolute; import org.eclipse.lsp4j.jsonrpc.messages.Either; @@ -108,6 +109,10 @@ void createFromFile() { assertThat(configuration.isUseDevSite()).isTrue(); assertThat(configuration.getDiagnosticsOptions().isOrdinaryAppSupport()).isFalse(); + var annotations = configuration.getCodeLensOptions().getTestRunnerAdapterOptions().getAnnotations(); + assertThat(annotations) + .hasSize(2) + .contains("Test", "Test2"); } @Test @@ -152,6 +157,7 @@ void testPartialInitialization() { // when CodeLensOptions codeLensOptions = configuration.getCodeLensOptions(); DiagnosticsOptions diagnosticsOptions = configuration.getDiagnosticsOptions(); + InlayHintOptions inlayHintOptions = configuration.getInlayHintOptions(); // then assertThat(codeLensOptions.getParameters().get("cognitiveComplexity")).isNull(); @@ -162,6 +168,10 @@ void testPartialInitialization() { assertThat(diagnosticsOptions.getMode()).isEqualTo(Mode.ON); assertThat(diagnosticsOptions.getSkipSupport()).isEqualTo(SkipSupport.NEVER); assertThat(diagnosticsOptions.getParameters()).isEmpty(); + + assertThat(inlayHintOptions.getParameters()) + .containsEntry("sourceDefinedMethodCall", Either.forRight(Map.of("showParametersWithTheSameName", true))); + } } \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/watcher/ConfigurationFileSystemWatcherTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/watcher/ConfigurationFileSystemWatcherTest.java index 63a42431e8c..eac63460987 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/watcher/ConfigurationFileSystemWatcherTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/configuration/watcher/ConfigurationFileSystemWatcherTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/AbstractServerContextAwareTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/AbstractServerContextAwareTest.java new file mode 100644 index 00000000000..2addffaa45b --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/AbstractServerContextAwareTest.java @@ -0,0 +1,50 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.context; + +import com.github._1c_syntax.utils.Absolute; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import javax.annotation.PostConstruct; +import java.nio.file.Path; + +@SpringBootTest +public abstract class AbstractServerContextAwareTest { + @Autowired + protected ServerContext context; + + @PostConstruct + public void abstractServerContextAwareTestInit() { + context.clear(); + } + + protected void initServerContext(String path) { + var configurationRoot = Absolute.path(path); + initServerContext(configurationRoot); + } + + protected void initServerContext(Path configurationRoot) { + context.setConfigurationRoot(configurationRoot); + context.populateContext(); + } +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java index a42485f2c68..651bc501b16 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/DocumentContextTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -137,7 +137,7 @@ void testRegionsAdjustingCompute() { List regions = documentContext.getSymbolTree().getModuleLevelRegions(); // then - assertThat(regions).anyMatch(regionSymbol -> regionSymbol.getMethods().size() > 0); + assertThat(regions).anyMatch(regionSymbol -> !regionSymbol.getMethods().isEmpty()); } @Test diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java index c79e2e5605a..d69a17d908e 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/ServerContextTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -25,16 +25,13 @@ import com.github._1c_syntax.bsl.mdo.support.ScriptVariant; import com.github._1c_syntax.bsl.types.ConfigurationSource; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.Configuration; import com.github._1c_syntax.utils.Absolute; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.io.File; -import java.io.IOException; import java.nio.file.Path; -import java.nio.file.Paths; import static org.assertj.core.api.Assertions.assertThat; @@ -52,10 +49,9 @@ class ServerContextTest { @Test void testConfigurationMetadata() { - Path path = Absolute.path(PATH_TO_METADATA); serverContext.setConfigurationRoot(path); - Configuration configurationMetadata = serverContext.getConfiguration(); + var configurationMetadata = serverContext.getConfiguration(); assertThat(configurationMetadata).isNotNull(); @@ -67,14 +63,12 @@ void testConfigurationMetadata() { assertThat(configurationMetadata.getCompatibilityMode().getVersion()).isEqualTo(10); File file = new File(PATH_TO_METADATA, PATH_TO_MODULE_FILE); - ModuleType type = configurationMetadata.getModuleType(Absolute.uri(file.toURI())); + ModuleType type = configurationMetadata.getModuleTypeByURI(Absolute.uri(file.toURI())); assertThat(type).isEqualTo(ModuleType.CommonModule); - } @Test - void testMdoRefs() throws IOException { - + void testMdoRefs() { var path = Absolute.path(PATH_TO_METADATA); serverContext.setConfigurationRoot(path); var mdoRefCommonModule = "CommonModule.ПервыйОбщийМодуль"; @@ -106,10 +100,10 @@ void testMdoRefs() throws IOException { @Test void testErrorConfigurationMetadata() { - Path path = Absolute.path(Paths.get(PATH_TO_METADATA, "test")); + Path path = Absolute.path(PATH_TO_METADATA + "test"); serverContext.setConfigurationRoot(path); - Configuration configurationMetadata = serverContext.getConfiguration(); + var configurationMetadata = serverContext.getConfiguration(); assertThat(configurationMetadata).isNotNull(); assertThat(configurationMetadata.getModulesByType()).isEmpty(); @@ -137,5 +131,4 @@ private DocumentContext addDocumentContext(ServerContext serverContext, String p serverContext.rebuildDocument(documentContext); return documentContext; } - } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CognitiveComplexityComputerTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CognitiveComplexityComputerTest.java index 44ee1eee516..cd419c415d2 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CognitiveComplexityComputerTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CognitiveComplexityComputerTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CyclomaticComplexityComputerTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CyclomaticComplexityComputerTest.java index 20721a5dcce..b8954cac578 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CyclomaticComplexityComputerTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/CyclomaticComplexityComputerTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/DiagnosticIgnoranceComputerTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/DiagnosticIgnoranceComputerTest.java index 24ffb492e31..14a438d908c 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/DiagnosticIgnoranceComputerTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/DiagnosticIgnoranceComputerTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,7 +21,6 @@ */ package com.github._1c_syntax.bsl.languageserver.context.computer; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java index aa33c46cee1..638cffc7d3d 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/MethodSymbolComputerTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -57,7 +57,7 @@ void testMethodSymbolComputer() { var documentContext = TestUtils.getDocumentContextFromFile("./src/test/resources/context/computer/MethodSymbolComputerTest.bsl"); List methods = documentContext.getSymbolTree().getMethods(); - assertThat(methods.size()).isEqualTo(24); + assertThat(methods.size()).isEqualTo(25); assertThat(methods.get(0).getName()).isEqualTo("Один"); assertThat(methods.get(0).getDescription()).isNotPresent(); @@ -215,13 +215,13 @@ void testParameters() { assertThat(parameters.get(2).getName()).isEqualTo("Парам3"); assertThat(parameters.get(2).isByValue()).isFalse(); assertThat(parameters.get(2).isOptional()).isTrue(); - assertThat(parameters.get(2).getDefaultValue().getValue()).isEqualTo("0"); + assertThat(parameters.get(2).getDefaultValue().value()).isEqualTo("0"); assertThat(parameters.get(2).getRange()).isEqualTo(Ranges.create(14, 32, 38)); assertThat(parameters.get(3).getName()).isEqualTo("Парам4"); assertThat(parameters.get(3).isByValue()).isTrue(); assertThat(parameters.get(3).isOptional()).isTrue(); - assertThat(parameters.get(3).getDefaultValue().getValue()).isEqualTo("0"); + assertThat(parameters.get(3).getDefaultValue().value()).isEqualTo("0"); assertThat(parameters.get(3).getRange()).isEqualTo(Ranges.create(14, 49, 55)); parameters = methods.get(23).getParameters(); @@ -232,6 +232,22 @@ void testParameters() { assertThat(parameters.get(2).getName()).isEqualTo("Парам3"); assertThat(parameters.get(2).getDescription()).isPresent(); + parameters = methods.get(24).getParameters(); + assertThat(parameters.get(0).getName()).isEqualTo("Парам1"); + assertThat(parameters.get(0).getAnnotations()).hasSize(1); + assertThat(parameters.get(0).getAnnotations().get(0).getName()).isEqualTo("Повторяемый"); + assertThat(parameters.get(0).getAnnotations().get(0).getKind()).isEqualTo(AnnotationKind.CUSTOM); + assertThat(parameters.get(0).getAnnotations().get(0).getParameters()).isEmpty(); + assertThat(parameters.get(1).getName()).isEqualTo("Парам2"); + assertThat(parameters.get(1).getAnnotations()).hasSize(1); + assertThat(parameters.get(1).getAnnotations().get(0).getName()).isEqualTo("ДругаяАннотация"); + assertThat(parameters.get(1).getAnnotations().get(0).getKind()).isEqualTo(AnnotationKind.CUSTOM); + assertThat(parameters.get(1).getAnnotations().get(0).getParameters()).hasSize(1); + assertThat(parameters.get(1).getAnnotations().get(0).getParameters().get(0).getName()).isEqualTo(""); + assertThat(parameters.get(1).getAnnotations().get(0).getParameters().get(0).getValue()).isEqualTo("СПараметром"); + assertThat(parameters.get(2).getName()).isEqualTo("Парам3"); + assertThat(parameters.get(2).getAnnotations()).isEmpty(); + } @Test diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ModuleSymbolComputerTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ModuleSymbolComputerTest.java index 1429ebae21d..295ab8d885b 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ModuleSymbolComputerTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/ModuleSymbolComputerTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,9 +23,9 @@ import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.mdo.MD; import com.github._1c_syntax.bsl.types.MdoReference; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; import org.eclipse.lsp4j.SymbolKind; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @@ -68,7 +68,7 @@ void testModuleName() { var mdoReference = mock(MdoReference.class); when(mdoReference.getMdoRef()).thenReturn("Document.Document1"); - AbstractMDObjectBase mdObject = mock(AbstractMDObjectBase.class); + var mdObject = mock(MD.class); when(mdObject.getMdoReference()).thenReturn(mdoReference); doReturn(Optional.of(mdObject)).when(documentContext).getMdObject(); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/QueryComputerTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/QueryComputerTest.java index d8609a69354..48261b256e9 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/QueryComputerTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/QueryComputerTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/SymbolTreeComputerTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/SymbolTreeComputerTest.java index 2eac5fd1e51..0676d445fc6 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/SymbolTreeComputerTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/SymbolTreeComputerTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolTest.java index 81cc4416441..b1d4b6acda1 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/computer/VariableSymbolTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -52,11 +52,11 @@ void setup() { @Test void testVariableSymbolDescription() { - assertThat(variableSymbols).hasSize(19); + assertThat(variableSymbols).hasSize(23); assertThat(variableSymbols) .filteredOn(variableSymbol -> variableSymbol.getDescription().isEmpty()) - .hasSize(9) + .hasSize(11) .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(12, 6, 34))) .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(14, 6, 27))) .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(16, 6, 17))) @@ -65,11 +65,12 @@ void testVariableSymbolDescription() { .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(32, 31, 59))) .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(33, 10, 19))) .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(55, 0, 35))) - .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(56, 0, 47))); + .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(56, 0, 47))) + ; assertThat(variableSymbols) .filteredOn(variableSymbol -> variableSymbol.getDescription().isPresent()) - .hasSize(10) + .hasSize(12) .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(2, 6, 32))) .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(6, 6, 33))) .anyMatch(variableSymbol -> variableSymbol.getRange().equals(Ranges.create(8, 6, 33))) @@ -92,7 +93,7 @@ void testVariableDescriptionRange() { .collect(Collectors.toList()); assertThat(variableDescriptions) - .hasSize(10) + .hasSize(12) .filteredOn(variableDescription -> !variableDescription.getDescription().equals("")) .hasSize(5) .anyMatch(variableDescription -> variableDescription.getRange().equals(Ranges.create(1, 0, 18))) @@ -105,13 +106,15 @@ void testVariableDescriptionRange() { assertThat(variableDescriptions) .extracting(VariableDescription::getTrailingDescription) .filteredOn(Optional::isPresent) - .hasSize(7) + .hasSize(9) .extracting(Optional::get) .anyMatch(trailingDescription -> trailingDescription.getRange().equals(Ranges.create(8, 35, 55))) .anyMatch(variableDescription -> variableDescription.getRange().equals(Ranges.create(19, 20, 42))) .anyMatch(variableDescription -> variableDescription.getRange().equals(Ranges.create(24, 20, 42))) .anyMatch(variableDescription -> variableDescription.getRange().equals(Ranges.create(35, 21, 43))) .anyMatch(variableDescription -> variableDescription.getRange().equals(Ranges.create(39, 21, 43))) + .anyMatch(variableDescription -> variableDescription.getRange().equals(Ranges.create(63, 45, 77))) + .anyMatch(variableDescription -> variableDescription.getRange().equals(Ranges.create(71, 38, 70))) ; } @@ -121,7 +124,7 @@ void testVariableNameRange() { assertThat(variableSymbols) .filteredOn(variableSymbol -> variableSymbol.getDescription().isEmpty()) - .hasSize(9) + .hasSize(11) .anyMatch(variableName -> variableName.getVariableNameRange().equals(Ranges.create(12, 6, 34))) .anyMatch(variableName -> variableName.getVariableNameRange().equals(Ranges.create(14, 6, 27))) .anyMatch(variableName -> variableName.getVariableNameRange().equals(Ranges.create(16, 6, 17))) @@ -131,6 +134,8 @@ void testVariableNameRange() { .anyMatch(variableName -> variableName.getVariableNameRange().equals(Ranges.create(33, 10, 19))) .anyMatch(variableName -> variableName.getVariableNameRange().equals(Ranges.create(55, 0, 35))) .anyMatch(variableName -> variableName.getVariableNameRange().equals(Ranges.create(56, 0, 47))) + .anyMatch(variableName -> variableName.getVariableNameRange().equals(Ranges.create(59, 12, 30))) + .anyMatch(variableName -> variableName.getVariableNameRange().equals(Ranges.create(67, 4, 22))) ; } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/MethodDescriptionTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/MethodDescriptionTest.java index 47c7f34cb6b..f208747e688 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/MethodDescriptionTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/context/symbol/description/MethodDescriptionTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,7 +29,6 @@ import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; @@ -44,24 +43,38 @@ void prepare() { var documentContext = TestUtils.getDocumentContextFromFile("./src/test/resources/context/symbol/MethodDescription.bsl"); var methods = documentContext.getSymbolTree().getMethods(); - assertThat(methods.size()).isEqualTo(14); + assertThat(methods).hasSize(16); methodsWithDescription = methods.stream() .map(MethodSymbol::getDescription) .filter(Optional::isPresent) .map(Optional::get) - .collect(Collectors.toList()); + .toList(); - assertThat(methodsWithDescription.size()).isEqualTo(13); + assertThat(methodsWithDescription.size()).isEqualTo(15); } } + @Test + void testMethodWithAnnotationBeforeDescription() { + var method = methodsWithDescription.get(14); + assertThat(method.getDescription()).isEqualTo("// Описание процедуры"); + } + + @Test + void testMethodWithAnnotation() { + var method = methodsWithDescription.get(13); + assertThat(method.getDescription()).isEqualTo("// Описание процедуры"); + } + @Test void testMethod13() { var method = methodsWithDescription.get(12); - assertThat(method.getPurposeDescription()).isEqualTo("Значения реквизитов, прочитанные из информационной базы для нескольких объектов.\n" + - "\nЕсли необходимо зачитать реквизит независимо от прав текущего пользователя,\n" + - "то следует использовать предварительный переход в привилегированный режим."); + assertThat(method.getPurposeDescription()).isEqualTo(""" + Значения реквизитов, прочитанные из информационной базы для нескольких объектов. + + Если необходимо зачитать реквизит независимо от прав текущего пользователя, + то следует использовать предварительный переход в привилегированный режим."""); assertThat(method.isDeprecated()).isFalse(); assertThat(method.getDeprecationInfo()).isEmpty(); assertThat(method.getExamples()).isEmpty(); @@ -74,9 +87,10 @@ void testMethod13() { assertThat(param.getName()).isEqualTo("Ссылки"); assertThat(param.getTypes()).hasSize(1); assertThat(param.getTypes().get(0).getName()).isEqualTo("Массив"); - assertThat(param.getTypes().get(0).getDescription()).isEqualTo("массив ссылок на объекты одного типа.\n" + - "Значения массива должны быть ссылками на объекты одного типа.\n" + - "если массив пуст, то результатом будет пустое соответствие."); + assertThat(param.getTypes().get(0).getDescription()).isEqualTo(""" + массив ссылок на объекты одного типа. + Значения массива должны быть ссылками на объекты одного типа. + если массив пуст, то результатом будет пустое соответствие."""); assertThat(param.isHyperlink()).isFalse(); param = method.getParameters().get(1); @@ -93,11 +107,12 @@ void testMethod13() { assertThat(param.getTypes()).hasSize(1); assertThat(param.getTypes().get(0).getName()).isEqualTo("Булево"); assertThat(param.getTypes().get(0).getDescription()).isEqualTo( - "если Истина, то запрос к объектам выполняется с учетом прав пользователя, и в случае,\n" + - "- если какой-либо объект будет исключен из выборки по правам, то этот объект\n" + - "будет исключен и из результата;\n" + - "- если Ложь, то возникнет исключение при отсутствии прав на таблицу\n" + - "или любой из реквизитов."); + """ + если Истина, то запрос к объектам выполняется с учетом прав пользователя, и в случае, + - если какой-либо объект будет исключен из выборки по правам, то этот объект + будет исключен и из результата; + - если Ложь, то возникнет исключение при отсутствии прав на таблицу + или любой из реквизитов."""); assertThat(param.isHyperlink()).isFalse(); var type = method.getReturnedValue().get(0); @@ -427,4 +442,4 @@ void testMethod1() { assertThat(method.getReturnedValue()).isEmpty(); assertThat(method.getLink()).isEmpty(); } -} \ No newline at end of file +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractDiagnosticTest.java index a17e31847c7..5b62c2de353 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,11 +22,11 @@ package com.github._1c_syntax.bsl.languageserver.diagnostics; import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; +import com.github._1c_syntax.bsl.languageserver.context.AbstractServerContextAwareTest; import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; -import com.github._1c_syntax.bsl.languageserver.context.ServerContext; import com.github._1c_syntax.bsl.languageserver.diagnostics.infrastructure.DiagnosticObjectProvider; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; -import com.github._1c_syntax.utils.Absolute; +import jakarta.annotation.PostConstruct; import lombok.SneakyThrows; import org.apache.commons.io.IOUtils; import org.eclipse.lsp4j.CodeAction; @@ -39,20 +39,16 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import javax.annotation.PostConstruct; import java.nio.charset.StandardCharsets; -import java.nio.file.Path; import java.util.Collections; import java.util.List; @SpringBootTest -abstract class AbstractDiagnosticTest { +abstract class AbstractDiagnosticTest extends AbstractServerContextAwareTest { @Autowired private DiagnosticObjectProvider diagnosticObjectProvider; @Autowired - protected ServerContext context; - @Autowired protected LanguageServerConfiguration configuration; private final Class diagnosticClass; @@ -65,20 +61,9 @@ abstract class AbstractDiagnosticTest { @PostConstruct public void init() { diagnosticInstance = diagnosticObjectProvider.get(diagnosticClass); - context.clear(); configuration.reset(); } - protected void initServerContext(String path) { - var configurationRoot = Absolute.path(path); - initServerContext(configurationRoot); - } - - protected void initServerContext(Path configurationRoot) { - context.setConfigurationRoot(configurationRoot); - context.populateContext(); - } - protected List getDiagnostics(DocumentContext documentContext) { return diagnosticInstance.getDiagnostics(documentContext); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractSymbolTreeDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractSymbolTreeDiagnosticTest.java index 62189923708..0f2e0244783 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractSymbolTreeDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AbstractSymbolTreeDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AllFunctionPathMustHaveReturnDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AllFunctionPathMustHaveReturnDiagnosticTest.java index dc646ee9489..9e69a8b0d39 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AllFunctionPathMustHaveReturnDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AllFunctionPathMustHaveReturnDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,7 +21,6 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; @@ -84,15 +83,16 @@ void testElsIfClausesWithoutElse() { @Test void testEmptyIfBodies() { - var sample = "Функция Тест()\n" + - " Список = Новый СписокЗначений;\n" + - " #Если Сервер Или ТолстыйКлиентОбычноеПриложение Или ВнешнееСоединение Тогда\n" + - " Если Условие Тогда\n" + - " Иначе\n" + - " КонецЕсли;\n" + - " #КонецЕсли\n" + - " Возврат Список;\n" + - "КонецФункции"; + var sample = """ + Функция Тест() + Список = Новый СписокЗначений; + #Если Сервер Или ТолстыйКлиентОбычноеПриложение Или ВнешнееСоединение Тогда + Если Условие Тогда + Иначе + КонецЕсли; + #КонецЕсли + Возврат Список; + КонецФункции"""; var documentContext = TestUtils.getDocumentContext(sample); var diagnostics = getDiagnostics(documentContext); @@ -104,17 +104,18 @@ void testEmptyIfBodies() { @Test void testExitByRaiseException() { var sample = - "Функция Тест()\n" + - "Если Не ВебКлиент Тогда\n" + - " Массив = Новый Массив;\n" + - " Если Условие Тогда\n" + - " Возврат Массив;\n" + - " КонецЕсли;\n" + - " Возврат ПустойМассив;\n" + - "#Иначе\n" + - " ВызватьИсключение \"Упс\";\n" + - "#КонецЕсли\n" + - "КонецФункции"; + """ + Функция Тест() + Если Не ВебКлиент Тогда + Массив = Новый Массив; + Если Условие Тогда + Возврат Массив; + КонецЕсли; + Возврат ПустойМассив; + #Иначе + ВызватьИсключение "Упс"; + #КонецЕсли + КонецФункции"""; var documentContext = TestUtils.getDocumentContext(sample); var diagnostics = getDiagnostics(documentContext); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AssignAliasFieldsInQueryDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AssignAliasFieldsInQueryDiagnosticTest.java index d74951f16bd..5f882d2a741 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AssignAliasFieldsInQueryDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/AssignAliasFieldsInQueryDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadWordsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadWordsDiagnosticTest.java index a19f6a6b842..3e666b61894 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadWordsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BadWordsDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -38,7 +38,7 @@ class BadWordsDiagnosticTest extends AbstractDiagnosticTest{ void test() { List diagnostics = getDiagnostics(); - assertThat(diagnostics).hasSize(0); // Проверка количества + assertThat(diagnostics).isEmpty(); // Проверка количества } @Test @@ -52,11 +52,29 @@ void testConfigure() { assertThat(diagnostics).hasSize(6); assertThat(diagnostics, true) - .hasRange(0, 42, 0, 47) - .hasRange(0, 48, 0, 54) - .hasRange(4, 4, 4, 9) - .hasRange(6, 24, 6, 29) - .hasRange(6, 34, 6, 39) - .hasRange(8, 4, 8, 10); + .hasMessageOnRange("В тексте модуля найдено запрещенное слово <лотус>.", 0, 42, 0, 47) + .hasMessageOnRange("В тексте модуля найдено запрещенное слово <шмотус>.", 0, 48, 0, 54) + .hasMessageOnRange("В тексте модуля найдено запрещенное слово <Лотус>.", 4, 4, 4, 9) + .hasMessageOnRange("В тексте модуля найдено запрещенное слово <Лотус>.", 6, 24, 6, 29) + .hasMessageOnRange("В тексте модуля найдено запрещенное слово <Лотус>.", 6, 34, 6, 39) + .hasMessageOnRange("В тексте модуля найдено запрещенное слово <Шмотус>.", 8, 4, 8, 10); + } + + @Test + void testFindWithoutComments() { + + Map configuration = diagnosticInstance.info.getDefaultConfiguration(); + configuration.put("badWords", "лотус|шмотус"); + configuration.put("findInComments", false); + diagnosticInstance.configure(configuration); + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(4); + assertThat(diagnostics, true) + .hasMessageOnRange("В тексте модуля найдено запрещенное слово <Лотус>.", 4, 4, 4, 9) + .hasMessageOnRange("В тексте модуля найдено запрещенное слово <Лотус>.", 6, 24, 6, 29) + .hasMessageOnRange("В тексте модуля найдено запрещенное слово <Лотус>.", 6, 34, 6, 39) + .hasMessageOnRange("В тексте модуля найдено запрещенное слово <Шмотус>.", 8, 4, 8, 10); } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BeginTransactionBeforeTryCatchDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BeginTransactionBeforeTryCatchDiagnosticTest.java index b2aca8779d6..1604f84f7c0 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BeginTransactionBeforeTryCatchDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/BeginTransactionBeforeTryCatchDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnosticTest.java index 35549294e05..8fea49b5a68 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CachedPublicDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,8 +23,8 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.bsl.mdo.support.ReturnValueReuse; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; import com.github._1c_syntax.utils.Absolute; import lombok.SneakyThrows; import org.apache.commons.io.FileUtils; @@ -48,7 +48,7 @@ class CachedPublicDiagnosticTest extends AbstractDiagnosticTest, Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,7 +21,6 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import org.eclipse.lsp4j.CodeAction; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeAfterAsyncCallDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeAfterAsyncCallDiagnosticTest.java index 2d5d3c22054..f1dbf51519b 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeAfterAsyncCallDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeAfterAsyncCallDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeBlockBeforeSubDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeBlockBeforeSubDiagnosticTest.java index da0198090d9..b98faf4c26c 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeBlockBeforeSubDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeBlockBeforeSubDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnosticTest.java index 62ab56ee0af..62f656fa49c 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CodeOutOfRegionDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CognitiveComplexityDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CognitiveComplexityDiagnosticTest.java index de2ee711759..f7d45ba0437 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CognitiveComplexityDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CognitiveComplexityDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommandModuleExportMethodsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommandModuleExportMethodsDiagnosticTest.java index 01988ca3645..de89418fb9e 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommandModuleExportMethodsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommandModuleExportMethodsDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommentedCodeDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommentedCodeDiagnosticTest.java index d31fbb3e4bd..74054a238c8 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommentedCodeDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommentedCodeDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -81,9 +81,9 @@ void testConfigure() { Map configuration = diagnosticInstance.info.getDefaultConfiguration(); List thresholdVariants = new ArrayList<>(); - thresholdVariants.add(Float.valueOf(1f)); - thresholdVariants.add(Double.valueOf(1)); - thresholdVariants.add(Integer.valueOf(1)); + thresholdVariants.add(1f); + thresholdVariants.add(1.0); + thresholdVariants.add(1); for (Object threshold : thresholdVariants){ configuration.put("threshold", threshold); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommitTransactionOutsideTryCatchDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommitTransactionOutsideTryCatchDiagnosticTest.java index f5fa9d9d021..0cad3f0a230 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommitTransactionOutsideTryCatchDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommitTransactionOutsideTryCatchDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnosticTest.java index 2c38e5311f3..4f57a860d23 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleAssignDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnosticTest.java index 47a49278d4c..e4b5305c7e6 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleInvalidTypeDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,7 +24,7 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.utils.Absolute; import lombok.SneakyThrows; import org.apache.commons.io.FileUtils; @@ -47,7 +47,7 @@ class CommonModuleInvalidTypeDiagnosticTest extends AbstractDiagnosticTest, Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java index ec67ef788e0..18479f2a6c6 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameCachedDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,8 +24,8 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.bsl.mdo.support.ReturnValueReuse; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; import com.github._1c_syntax.utils.Absolute; import lombok.SneakyThrows; import org.apache.commons.io.FileUtils; @@ -44,7 +44,7 @@ @CleanupContextBeforeClassAndAfterEachTestMethod class CommonModuleNameCachedDiagnosticTest extends AbstractDiagnosticTest { - private MDCommonModule module; + private CommonModule module; private DocumentContext documentContext; CommonModuleNameCachedDiagnosticTest() { @@ -165,7 +165,6 @@ void testEmptyFile() { @SneakyThrows void getDocumentContextFromFile() { - Path path = Absolute.path(PATH_TO_METADATA); Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); @@ -176,10 +175,6 @@ void getDocumentContextFromFile() { FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), context )); - - - module = spy((MDCommonModule) configuration.getModulesByObject().get(documentContext.getUri())); - + module = spy((CommonModule) configuration.findChild(documentContext.getUri()).get()); } - } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java index 900ce3865b2..eb19a3063e9 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,7 +24,7 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.utils.Absolute; import lombok.SneakyThrows; import org.apache.commons.io.FileUtils; @@ -44,7 +44,7 @@ @CleanupContextBeforeClassAndAfterEachTestMethod class CommonModuleNameClientDiagnosticTest extends AbstractDiagnosticTest { private DocumentContext documentContext; - private MDCommonModule module; + private CommonModule module; CommonModuleNameClientDiagnosticTest() { super(CommonModuleNameClientDiagnostic.class); @@ -163,10 +163,8 @@ void testGlobal() { } - @SneakyThrows void getDocumentContextFromFile() { - Path path = Absolute.path(PATH_TO_METADATA); Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); @@ -177,10 +175,6 @@ void getDocumentContextFromFile() { FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), context )); - - - module = spy((MDCommonModule) configuration.getModulesByObject().get(documentContext.getUri())); - + module = spy((CommonModule) configuration.findChild(documentContext.getUri()).get()); } - } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java index 3d3e8c43a8f..1e624902ce4 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameClientServerDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,7 +24,7 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.utils.Absolute; import lombok.SneakyThrows; import org.apache.commons.io.FileUtils; @@ -43,7 +43,7 @@ @CleanupContextBeforeClassAndAfterEachTestMethod class CommonModuleNameClientServerDiagnosticTest extends AbstractDiagnosticTest { - private MDCommonModule module; + private CommonModule module; private DocumentContext documentContext; CommonModuleNameClientServerDiagnosticTest() { @@ -165,7 +165,6 @@ void testFalse2() { @SneakyThrows void getDocumentContextFromFile() { - Path path = Absolute.path(PATH_TO_METADATA); Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); @@ -176,9 +175,6 @@ void getDocumentContextFromFile() { FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), context )); - - - module = spy((MDCommonModule) configuration.getModulesByObject().get(documentContext.getUri())); - + module = spy((CommonModule) configuration.findChild(documentContext.getUri()).get()); } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnosticTest.java index de058e33412..a34bd2e49ec 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameFullAccessDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,7 +24,7 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.utils.Absolute; import lombok.SneakyThrows; import org.apache.commons.io.FileUtils; @@ -44,7 +44,7 @@ @CleanupContextBeforeClassAndAfterEachTestMethod class CommonModuleNameFullAccessDiagnosticTest extends AbstractDiagnosticTest { private DocumentContext documentContext; - private MDCommonModule module; + private CommonModule module; CommonModuleNameFullAccessDiagnosticTest() { super(CommonModuleNameFullAccessDiagnostic.class); @@ -116,7 +116,6 @@ void testFalse() { @SneakyThrows void getDocumentContextFromFile() { - Path path = Absolute.path(PATH_TO_METADATA); Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); @@ -128,8 +127,6 @@ void getDocumentContextFromFile() { context )); - - module = spy((MDCommonModule) configuration.getModulesByObject().get(documentContext.getUri())); - + module = spy((CommonModule) configuration.findChild(documentContext.getUri()).get()); } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java index d46860d69fe..15380f1dee4 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalClientDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,7 +24,7 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.utils.Absolute; import lombok.SneakyThrows; import org.apache.commons.io.FileUtils; @@ -43,7 +43,7 @@ @CleanupContextBeforeClassAndAfterEachTestMethod class CommonModuleNameGlobalClientDiagnosticTest extends AbstractDiagnosticTest { - private MDCommonModule module; + private CommonModule module; private DocumentContext documentContext; CommonModuleNameGlobalClientDiagnosticTest() { @@ -206,7 +206,6 @@ void testClient() { @SneakyThrows void getDocumentContextFromFile() { - Path path = Absolute.path(PATH_TO_METADATA); Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); @@ -217,9 +216,6 @@ void getDocumentContextFromFile() { FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), context )); - - - module = spy((MDCommonModule) configuration.getModulesByObject().get(documentContext.getUri())); - + module = spy((CommonModule) configuration.findChild(documentContext.getUri()).get()); } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnosticTest.java index 3ed54b58ec2..3ba2fce3513 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameGlobalDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,7 +24,7 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.utils.Absolute; import lombok.SneakyThrows; import org.apache.commons.io.FileUtils; @@ -44,7 +44,7 @@ @CleanupContextBeforeClassAndAfterEachTestMethod class CommonModuleNameGlobalDiagnosticTest extends AbstractDiagnosticTest { private DocumentContext documentContext; - private MDCommonModule module; + private CommonModule module; CommonModuleNameGlobalDiagnosticTest() { super(CommonModuleNameGlobalDiagnostic.class); @@ -53,7 +53,6 @@ class CommonModuleNameGlobalDiagnosticTest extends AbstractDiagnosticTest, Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,7 +24,7 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.utils.Absolute; import lombok.SneakyThrows; import org.apache.commons.io.FileUtils; @@ -44,7 +44,7 @@ @CleanupContextBeforeClassAndAfterEachTestMethod class CommonModuleNameServerCallDiagnosticTest extends AbstractDiagnosticTest { - private MDCommonModule module; + private CommonModule module; private DocumentContext documentContext; CommonModuleNameServerCallDiagnosticTest() { @@ -146,7 +146,6 @@ void TestNegative() { @SneakyThrows void getDocumentContextFromFile() { - Path path = Absolute.path(PATH_TO_METADATA); Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); @@ -157,9 +156,6 @@ void getDocumentContextFromFile() { FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), context )); - - - module = spy((MDCommonModule) configuration.getModulesByObject().get(documentContext.getUri())); - + module = spy((CommonModule) configuration.findChild(documentContext.getUri()).get()); } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnosticTest.java index 17a38447e33..baeee1eb45a 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CommonModuleNameWordsDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,7 +24,7 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.utils.Absolute; import lombok.SneakyThrows; import org.apache.commons.io.FileUtils; @@ -45,7 +45,7 @@ @CleanupContextBeforeClassAndAfterEachTestMethod class CommonModuleNameWordsDiagnosticTest extends AbstractDiagnosticTest { - private MDCommonModule module; + private CommonModule module; private DocumentContext documentContext; CommonModuleNameWordsDiagnosticTest() { @@ -118,7 +118,6 @@ void testConfigure() { @SneakyThrows void getDocumentContextFromFile() { - Path path = Absolute.path(PATH_TO_METADATA); Path testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); @@ -129,10 +128,7 @@ void getDocumentContextFromFile() { FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), context )); - - - module = spy((MDCommonModule) configuration.getModulesByObject().get(documentContext.getUri())); - + module = spy((CommonModule) configuration.findChild(documentContext.getUri()).get()); } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CompilationDirectiveLostDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CompilationDirectiveLostDiagnosticTest.java index 9a90ffcedb1..5aa067ef10d 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CompilationDirectiveLostDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CompilationDirectiveLostDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,9 +21,9 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.mdo.Form; import com.github._1c_syntax.bsl.mdo.support.FormType; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDOForm; import com.github._1c_syntax.utils.Absolute; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; @@ -56,12 +56,11 @@ void test() { void testOriginalFormModule() { final var PATH_TO_METADATA = "src/test/resources/metadata/designer"; initServerContext(Absolute.path(PATH_TO_METADATA)); - var form = spy((AbstractMDOForm) context.getConfiguration().getChildren().stream() + var form = spy((Form) context.getConfiguration().getPlainChildren().stream() .filter(mdo -> mdo.getName().equalsIgnoreCase("ФормаЭлемента")) .findFirst() .get()); - var documentContext = spy(getDocumentContext()); when(documentContext.getModuleType()).thenReturn(ModuleType.FormModule); when(form.getFormType()).thenReturn(FormType.ORDINARY); @@ -71,5 +70,4 @@ void testOriginalFormModule() { assertThat(diagnostics).isEmpty(); } - } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CompilationDirectiveNeedLessDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CompilationDirectiveNeedLessDiagnosticTest.java index 589f2b6f93c..8c5538f0b61 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CompilationDirectiveNeedLessDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CompilationDirectiveNeedLessDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnosticTest.java index 0b3e1d8d186..74187aea9ad 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ConsecutiveEmptyLinesDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -39,9 +39,10 @@ class ConsecutiveEmptyLinesDiagnosticTest extends AbstractDiagnosticTest diagnostics = getDiagnosticsForText(module); @@ -53,10 +54,11 @@ void test_EmptyTwoFirstLines() { @Test void test_EmptyThreeFirstLines() { - String module = " \n" + - "\n" + - "\n" + - "КонецПроцедуры"; + String module = """ + \s + + + КонецПроцедуры"""; List diagnostics = getDiagnosticsForText(module); @@ -68,10 +70,11 @@ void test_EmptyThreeFirstLines() { @Test void test_EmptyTwoInnerLines() { - String module = "Процедура Первая()\n" + - "\n" + - "\n" + - "КонецПроцедуры"; + String module = """ + Процедура Первая() + + + КонецПроцедуры"""; List diagnostics = getDiagnosticsForText(module); @@ -83,10 +86,11 @@ void test_EmptyTwoInnerLines() { @Test void test_EmptyTwoInnerLinesWithSpaces() { - String module = "Процедура Первая() \n" + - " \n" + - " \n" + - "КонецПроцедуры"; + String module = """ + Процедура Первая() \s + \s + \s + КонецПроцедуры"""; List diagnostics = getDiagnosticsForText(module); @@ -98,12 +102,13 @@ void test_EmptyTwoInnerLinesWithSpaces() { @Test void test_WorseEmptyTwoInnerLines() { - String module = "Процедура Первая() \n" + - " \n" + - " Метод1(); //комментарии \n" + - "\n" + - " \n" + - "КонецПроцедуры"; + String module = """ + Процедура Первая() \s + \s + Метод1(); //комментарии \s + + \s + КонецПроцедуры"""; List diagnostics = getDiagnosticsForText(module); @@ -115,11 +120,12 @@ void test_WorseEmptyTwoInnerLines() { @Test void test_EmptyThreeInnerLines() { - String module = "Процедура Первая()\n" + - "\n" + - "\n" + - "\n" + - "КонецПроцедуры"; + String module = """ + Процедура Первая() + + + + КонецПроцедуры"""; List diagnostics = getDiagnosticsForText(module); @@ -131,8 +137,10 @@ void test_EmptyThreeInnerLines() { @Test void test_EmptyLastLines() { - String module = "Перем А;\n" + - "\n"; + String module = """ + Перем А; + + """; List diagnostics = getDiagnosticsForText(module); @@ -182,11 +190,12 @@ void test_EmptyLinePlusOneFilledLine() { void test_ConfigureEmptyLineParam() { setTwoForAllowedEmptyLinesCount(); - String module = "Процедура Первая()\n" + - "\n" + - "\n" + - "\n" + - "КонецПроцедуры"; + String module = """ + Процедура Первая() + + + + КонецПроцедуры"""; List diagnostics = getDiagnosticsForText(module); @@ -200,10 +209,11 @@ void test_ConfigureEmptyLineParam() { void test_ConfigureEmptyLineParamNoIssue() { setTwoForAllowedEmptyLinesCount(); - String module = "Процедура Первая()\n" + - "\n" + - "\n" + - "КонецПроцедуры"; + String module = """ + Процедура Первая() + + + КонецПроцедуры"""; List diagnostics = getDiagnosticsForText(module); @@ -267,8 +277,10 @@ private void checkQuickFixes(String module, boolean haveFix) { @Test void testQuickFixLastLines() { - String module = "Перем А;\n" + - "\n"; + String module = """ + Перем А; + + """; checkQuickFixes(module, true); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CrazyMultilineStringDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CrazyMultilineStringDiagnosticTest.java index d38477eeffc..3570d7e4ec0 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CrazyMultilineStringDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CrazyMultilineStringDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnosticTest.java index 333b79e1f7d..ea0990d86d8 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CreateQueryInCycleDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CyclomaticComplexityDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CyclomaticComplexityDiagnosticTest.java index 960a1a3f4fe..6ff9727c9c1 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CyclomaticComplexityDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/CyclomaticComplexityDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -37,6 +37,8 @@ class CyclomaticComplexityDiagnosticTest extends AbstractDiagnosticTest diagnostics = getDiagnostics(); @@ -45,7 +47,6 @@ void test() { assertThat(diagnostics, true) .hasRange(0, 8, 0, 32); assertThat(diagnostics.get(0).getRelatedInformation()).hasSize(21); - } @Test diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java index e2a8107bdce..7bb17900d67 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DataExchangeLoadingDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeletingCollectionItemDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeletingCollectionItemDiagnosticTest.java index 4eb28cace36..075c8fcb643 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeletingCollectionItemDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeletingCollectionItemDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DenyIncompleteValuesDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DenyIncompleteValuesDiagnosticTest.java new file mode 100644 index 00000000000..182d35bc964 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DenyIncompleteValuesDiagnosticTest.java @@ -0,0 +1,122 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.context.ServerContext; +import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; +import com.github._1c_syntax.bsl.mdo.InformationRegister; +import com.github._1c_syntax.bsl.mdo.MD; +import com.github._1c_syntax.bsl.types.MDOType; +import com.github._1c_syntax.bsl.types.MdoReference; +import com.github._1c_syntax.bsl.types.ModuleType; +import com.github._1c_syntax.utils.Absolute; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +@CleanupContextBeforeClassAndAfterEachTestMethod +class DenyIncompleteValuesDiagnosticTest extends AbstractDiagnosticTest { + DenyIncompleteValuesDiagnosticTest() { + super(DenyIncompleteValuesDiagnostic.class); + } + + private static final String PATH_TO_METADATA = "src/test/resources/metadata/designer"; + private static final String PATH_TO_MANAGER_MODULE_FILE = "InformationRegisters/РегистрСведений1/Ext/ManagerModule.bsl"; + private static final String PATH_TO_OBJECT_MODULE_FILE = "InformationRegisters/РегистрСведений1/Ext/RecordSetModule.bsl"; + + @Test + void testMdoWithoutModule() { + checkMockHandler(ModuleType.SessionModule, true); + } + + @Test + void testMdoWithOneModule() { + checkMockHandler(ModuleType.ManagerModule, false); + } + + @Test + void testMdoWithModules() { + var path = Absolute.path(PATH_TO_METADATA); + context.setConfigurationRoot(path); + + var managerDocumentContext = addDocumentContext(context, PATH_TO_MANAGER_MODULE_FILE); + var recordSetDocumentContext = addDocumentContext(context, PATH_TO_OBJECT_MODULE_FILE); + + final var diagnostics = getDiagnostics(managerDocumentContext); + + assertThat(diagnostics, true) + .hasMessageOnRange("Не указан флаг \"Запрет незаполненных значений\" у измерения \"Справочник1\" метаданного \"РегистрСведений.РегистрСведений1\"", + 0, 0, 9) + .hasSize(1); + + final var diagnostics2 = getDiagnostics(recordSetDocumentContext); + assertThat(diagnostics2, true).isEmpty(); + } + + private void checkMockHandler(ModuleType type, boolean noneModules) { + initServerContext(Absolute.path(PATH_TO_METADATA)); + + var documentContext = spy(getDocumentContext()); + when(documentContext.getModuleType()).thenReturn(type); + + final var infoReg = spy((InformationRegister) context.getConfiguration().findChild(MdoReference.create(MDOType.INFORMATION_REGISTER, + "РегистрСведений1")).orElseThrow() + ); + + when(documentContext.getMdObject()).thenReturn(Optional.of(infoReg)); + + if (noneModules) { + when(infoReg.getModules()).thenReturn(Collections.emptyList()); + + List children = List.of(infoReg); + + var configuration = spy(context.getConfiguration()); + when(configuration.getChildren()).thenReturn(children); + var serverContext = spy(documentContext.getServerContext()); + when(serverContext.getConfiguration()).thenReturn(configuration); + when(documentContext.getServerContext()).thenReturn(serverContext); + } + + final var diagnostics = getDiagnostics(documentContext); + + assertThat(diagnostics, true) + .hasMessageOnRange("Не указан флаг \"Запрет незаполненных значений\" у измерения \"Справочник1\" метаданного \"РегистрСведений.РегистрСведений1\"", + 0, 0, 9) + .hasSize(1); + } + + private DocumentContext addDocumentContext(ServerContext serverContext, String path) { + var file = new File(PATH_TO_METADATA, path); + var uri = Absolute.uri(file); + var documentContext = serverContext.addDocument(uri); + serverContext.rebuildDocument(documentContext); + return documentContext; + } +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312DiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312DiagnosticTest.java index ad9965eba66..a515adbc763 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312DiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedAttributes8312DiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnosticTest.java index 28c05663628..8f6ace0d136 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedCurrentDateDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedFindDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedFindDiagnosticTest.java index 30c67bea8b0..5bc8c895343 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedFindDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedFindDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMessageDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMessageDiagnosticTest.java index 846ebbe6727..496c92b9b50 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMessageDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMessageDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnosticTest.java index f33e71aca04..8969585297a 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethodCallDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310DiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310DiagnosticTest.java index 26400cf56f8..3019813d1de 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310DiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8310DiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317DiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317DiagnosticTest.java index 93caa850286..2a72ecc19a7 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317DiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedMethods8317DiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedTypeManagedFormDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedTypeManagedFormDiagnosticTest.java index be35eb825bc..07211dc1e55 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedTypeManagedFormDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DeprecatedTypeManagedFormDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,7 +21,6 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import org.eclipse.lsp4j.CodeAction; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticInfosTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticInfosTest.java index 956c709240c..e61c96eca85 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticInfosTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticInfosTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -75,16 +75,16 @@ void testAllDiagnosticsHaveDiagnosticMessage() { @Test void testAllDiagnosticsHaveDescriptionResource() { - assertThatCode(() -> diagnosticInfos.values().forEach(diagnosticInfo - -> assertThat(diagnosticInfo.getDescription()).isNotEmpty())) - .doesNotThrowAnyException(); + assertThat(diagnosticInfos).allSatisfy((key, diagnosticInfo) -> { + assertThat(diagnosticInfo.getDescription()).isNotEmpty(); + }); } @Test void testAllDiagnosticsHaveTags() { assertThatCode(() -> diagnosticInfos.values().forEach(diagnosticInfo -> assertThat( - diagnosticInfo.getTags().size() > 0 + !diagnosticInfo.getTags().isEmpty() && diagnosticInfo.getTags().size() <= 3) .isTrue())) .doesNotThrowAnyException(); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticsTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticsTest.java index 01edd4f729b..c76cc17aa20 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticsTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DiagnosticsTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -30,7 +30,6 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.infrastructure.DiagnosticsConfiguration; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterClass; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; -import com.github._1c_syntax.bsl.supconf.SupportConfiguration; import com.github._1c_syntax.bsl.support.CompatibilityMode; import com.github._1c_syntax.bsl.support.SupportVariant; import com.github._1c_syntax.bsl.types.ModuleType; @@ -41,7 +40,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -49,7 +47,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @SpringBootTest @@ -146,78 +143,77 @@ void testSkipSupport() { // given documentContext = spy(TestUtils.getDocumentContext("А = 0")); - var supportConfiguration = mock(SupportConfiguration.class); // when-then pairs ComputeDiagnosticsSkipSupport.NEVER configuration.getDiagnosticsOptions().setSkipSupport(SkipSupport.NEVER); - doReturn(Collections.emptyMap()).when(documentContext).getSupportVariants(); + doReturn(SupportVariant.NONE).when(documentContext).getSupportVariant(); assertThat(diagnosticsConfiguration.diagnostics(documentContext)) .isNotEmpty(); - doReturn(Map.of(supportConfiguration, SupportVariant.NONE)).when(documentContext).getSupportVariants(); + doReturn(SupportVariant.NONE).when(documentContext).getSupportVariant(); assertThat(diagnosticsConfiguration.diagnostics(documentContext)) .isNotEmpty(); - doReturn(Map.of(supportConfiguration, SupportVariant.NOT_SUPPORTED)).when(documentContext).getSupportVariants(); + doReturn(SupportVariant.NOT_SUPPORTED).when(documentContext).getSupportVariant(); assertThat(diagnosticsConfiguration.diagnostics(documentContext)) .isNotEmpty(); - doReturn(Map.of(supportConfiguration, SupportVariant.EDITABLE_SUPPORT_ENABLED)).when(documentContext).getSupportVariants(); + doReturn(SupportVariant.EDITABLE_SUPPORT_ENABLED).when(documentContext).getSupportVariant(); assertThat(diagnosticsConfiguration.diagnostics(documentContext)) .isNotEmpty(); - doReturn(Map.of(supportConfiguration, SupportVariant.NOT_EDITABLE)).when(documentContext).getSupportVariants(); + doReturn(SupportVariant.NOT_EDITABLE).when(documentContext).getSupportVariant(); assertThat(diagnosticsConfiguration.diagnostics(documentContext)) .isNotEmpty(); // when-then pairs ComputeDiagnosticsSkipSupport.WITHSUPPORTLOCKED configuration.getDiagnosticsOptions().setSkipSupport(SkipSupport.WITH_SUPPORT_LOCKED); - doReturn(Collections.emptyMap()).when(documentContext).getSupportVariants(); + doReturn(SupportVariant.NONE).when(documentContext).getSupportVariant(); assertThat(diagnosticsConfiguration.diagnostics(documentContext)) .isNotEmpty(); - doReturn(Map.of(supportConfiguration, SupportVariant.NONE)).when(documentContext).getSupportVariants(); + doReturn(SupportVariant.NONE).when(documentContext).getSupportVariant(); assertThat(diagnosticsConfiguration.diagnostics(documentContext)) .isNotEmpty(); - doReturn(Map.of(supportConfiguration, SupportVariant.NOT_SUPPORTED)).when(documentContext).getSupportVariants(); + doReturn(SupportVariant.NOT_SUPPORTED).when(documentContext).getSupportVariant(); assertThat(diagnosticsConfiguration.diagnostics(documentContext)) .isNotEmpty(); - doReturn(Map.of(supportConfiguration, SupportVariant.EDITABLE_SUPPORT_ENABLED)).when(documentContext).getSupportVariants(); + doReturn(SupportVariant.EDITABLE_SUPPORT_ENABLED).when(documentContext).getSupportVariant(); assertThat(diagnosticsConfiguration.diagnostics(documentContext)) .isNotEmpty(); - doReturn(Map.of(supportConfiguration, SupportVariant.NOT_EDITABLE)).when(documentContext).getSupportVariants(); + doReturn(SupportVariant.NOT_EDITABLE).when(documentContext).getSupportVariant(); assertThat(diagnosticsConfiguration.diagnostics(documentContext)) .isEmpty(); // when-then pairs ComputeDiagnosticsSkipSupport.WITHSUPPORT configuration.getDiagnosticsOptions().setSkipSupport(SkipSupport.WITH_SUPPORT); - doReturn(Collections.emptyMap()).when(documentContext).getSupportVariants(); + doReturn(SupportVariant.NONE).when(documentContext).getSupportVariant(); assertThat(diagnosticsConfiguration.diagnostics(documentContext)) .isNotEmpty(); - doReturn(Map.of(supportConfiguration, SupportVariant.NONE)).when(documentContext).getSupportVariants(); + doReturn(SupportVariant.NONE).when(documentContext).getSupportVariant(); assertThat(diagnosticsConfiguration.diagnostics(documentContext)) .isNotEmpty(); - doReturn(Map.of(supportConfiguration, SupportVariant.NOT_SUPPORTED)).when(documentContext).getSupportVariants(); + doReturn(SupportVariant.NOT_SUPPORTED).when(documentContext).getSupportVariant(); assertThat(diagnosticsConfiguration.diagnostics(documentContext)) .isEmpty(); - doReturn(Map.of(supportConfiguration, SupportVariant.EDITABLE_SUPPORT_ENABLED)).when(documentContext).getSupportVariants(); + doReturn(SupportVariant.EDITABLE_SUPPORT_ENABLED).when(documentContext) + .getSupportVariant(); assertThat(diagnosticsConfiguration.diagnostics(documentContext)) .isEmpty(); - doReturn(Map.of(supportConfiguration, SupportVariant.NOT_EDITABLE)).when(documentContext).getSupportVariants(); + doReturn(SupportVariant.NOT_EDITABLE).when(documentContext).getSupportVariant(); assertThat(diagnosticsConfiguration.diagnostics(documentContext)) .isEmpty(); } @Test void testDiagnosticModeOff() { - // when configuration.getDiagnosticsOptions().setMode(Mode.OFF); @@ -226,7 +222,6 @@ void testDiagnosticModeOff() { @Test void testDiagnosticModeOn() { - // when configuration.getDiagnosticsOptions().setMode(Mode.ON); @@ -238,7 +233,6 @@ void testDiagnosticModeOn() { @Test void testDiagnosticModeAll() { - // when configuration.getDiagnosticsOptions().setMode(Mode.ALL); @@ -250,7 +244,6 @@ void testDiagnosticModeAll() { @Test void testDiagnosticModeOnly() { - // when configuration.getDiagnosticsOptions().setMode(Mode.ONLY); Map>> rules = new HashMap<>(); @@ -269,7 +262,6 @@ void testDiagnosticModeOnly() { @Test void testDiagnosticModeExcept() { - // when configuration.getDiagnosticsOptions().setMode(Mode.EXCEPT); Map>> rules = new HashMap<>(); @@ -289,7 +281,6 @@ void testDiagnosticModeExcept() { @Test void testDiagnosticSubsystemsIncludeCheck() { - var PATH_TO_METADATA = "src/test/resources/metadata/subSystemFilter"; context.clear(); context.setConfigurationRoot(Absolute.path(PATH_TO_METADATA)); @@ -297,7 +288,7 @@ void testDiagnosticSubsystemsIncludeCheck() { documentContext = spy(TestUtils.getDocumentContext("А = 0")); - var form = context.getConfiguration().getChildren().stream() + var form = context.getConfiguration().getPlainChildren().stream() .filter(mdo -> mdo.getName().equalsIgnoreCase("ФормаЭлемента")) .findFirst(); @@ -340,13 +331,11 @@ void testDiagnosticSubsystemsIncludeCheck() { .setInclude(new TreeSet<>(List.of("Подсистема3"))); assertThat(diagnosticsConfiguration.diagnostics(documentContext)) .isEmpty(); - } // @Test void testDiagnosticSubsystemsExcludeCheck() { - var PATH_TO_METADATA = "src/test/resources/metadata/subSystemFilter"; context.clear(); context.setConfigurationRoot(Absolute.path(PATH_TO_METADATA)); @@ -375,7 +364,6 @@ void testDiagnosticSubsystemsExcludeCheck() { @Test void testDiagnosticSubsystemsIncludeExcludeCheck() { - var PATH_TO_METADATA = "src/test/resources/metadata/subSystemFilter"; context.clear(); context.setConfigurationRoot(Absolute.path(PATH_TO_METADATA)); @@ -404,5 +392,4 @@ void testDiagnosticSubsystemsIncludeExcludeCheck() { assertThat(diagnosticsConfiguration.diagnostics(documentContext)) .isEmpty(); } - } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DisableSafeModeDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DisableSafeModeDiagnosticTest.java new file mode 100644 index 00000000000..9a928a8f61d --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DisableSafeModeDiagnosticTest.java @@ -0,0 +1,49 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class DisableSafeModeDiagnosticTest extends AbstractDiagnosticTest { + DisableSafeModeDiagnosticTest() { + super(DisableSafeModeDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics, true) + .hasRange(2, 4, 29) + .hasRange(5, 4, 29) + .hasRange(9, 4, 41) + .hasRange(12, 4, 41) + .hasSize(4); + + } +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnosticTest.java new file mode 100644 index 00000000000..0f2b04731d1 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DoubleNegativesDiagnosticTest.java @@ -0,0 +1,57 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class DoubleNegativesDiagnosticTest extends AbstractDiagnosticTest { + DoubleNegativesDiagnosticTest() { + super(DoubleNegativesDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics, true) + .hasRange(1, 5, 1, 73) + .hasRange(5, 4, 5, 20) + .hasRange(6, 4, 6, 21) + .hasRange(7, 4, 7, 42) + .hasRange(8, 4, 8, 42) + .hasRange(9, 4, 9, 25) + .hasRange(10, 4, 10, 24) + .hasRange(15, 5, 15, 38) + .hasRange(19, 19, 19, 39) + .hasRange(28, 4, 28, 26) + .hasRange(29, 4, 29, 36) + .hasRange(35, 4, 35, 19) + ; + + } +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicateRegionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicateRegionDiagnosticTest.java index 012eaa23af6..5c2f4600478 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicateRegionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicateRegionDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicateStringLiteralDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicateStringLiteralDiagnosticTest.java index fd0ea0488fa..61bdcccc437 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicateStringLiteralDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicateStringLiteralDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicatedInsertionIntoCollectionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicatedInsertionIntoCollectionDiagnosticTest.java new file mode 100644 index 00000000000..6fbf27c93dc --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/DuplicatedInsertionIntoCollectionDiagnosticTest.java @@ -0,0 +1,231 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class DuplicatedInsertionIntoCollectionDiagnosticTest extends AbstractDiagnosticTest { + DuplicatedInsertionIntoCollectionDiagnosticTest() { + super(DuplicatedInsertionIntoCollectionDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics, true) + .hasIssueOnRange(8, 4, 8, 34, + getMessage("\"Ключ1\"", "Коллекция"), + Arrays.asList( + Ranges.create(7, 4, 34), + Ranges.create(8, 4, 34))) + + .hasIssueOnRange(12, 4, 35, + getMessage("\"Ключ1\"", "Коллекция2"), + Arrays.asList( + Ranges.create(11, 4, 35), + Ranges.create(12, 4, 35))) + + .hasIssueOnRange(4, 4, 34, + getMessage("СтрокаТаблицы", "Массив"), + Arrays.asList( + Ranges.create(3, 4, 34), + Ranges.create(4, 4, 34))) + + .hasIssueOnRange(22, 8, 38, + getMessage("\"Ключ1\"", "Коллекция"), + Arrays.asList( + Ranges.create(21, 8, 38), + Ranges.create(22, 8, 38))) + + .hasIssueOnRange(27, 8, 55, + getMessage("\"Пользователь\"", "Итог.Коллекция.Индексы"), + Arrays.asList( + Ranges.create(26, 8, 55), + Ranges.create(27, 8, 55))) + + .hasIssueOnRange(58, 12, 76, + getMessage("ЭлементСтиля.Ключ", "ЭлементыСтиля"), + Arrays.asList( + Ranges.create(56, 12, 87), + Ranges.create(58, 12, 76))) + + .hasIssueOnRange(99, 8, 77, + getMessage("\"Пользователь\"", "Данные.Метод().ПовторнаяСоздаваемаяКоллекция"), + Arrays.asList( + Ranges.create(98, 8, 77), + Ranges.create(99, 8, 77))) + + .hasIssueOnRange(102, 8, 92, + getMessage("Данные.Метод().ПовторнаяСоздаваемаяКоллекция", "Данные.Метод().ОбщаяКоллекция"), + Arrays.asList( + Ranges.create(101, 8, 92), + Ranges.create(102, 8, 92))) + + .hasIssueOnRange(119, 4, 65, + getMessage("\"ДополнительныеРеквизиты\"", "ВидыСвойствНабора"), + Arrays.asList( + Ranges.create(112, 4, 63), + Ranges.create(119, 4, 65))) + + .hasIssueOnRange(133, 4, 58, + getMessage("\"Пользователь\"", "ПовторнаяСоздаваемаяКоллекция"), + Arrays.asList( + Ranges.create(132, 4, 58), + Ranges.create(133, 4, 58))) + + .hasIssueOnRange(136, 4, 58, + getMessage("ПовторнаяСоздаваемаяКоллекция", "ОбщаяКоллекция"), + Arrays.asList( + Ranges.create(135, 4, 58), + Ranges.create(136, 4, 58))) + + .hasIssueOnRange(147, 8, 90, + getMessage("Данные2.Реквизит2.ПовторнаяСоздаваемаяКоллекция2", "Данные2.ОбщаяКоллекция2"), + Arrays.asList( + Ranges.create(145, 8, 90), + Ranges.create(147, 8, 90))) + + .hasIssueOnRange(151, 8, 90, + getMessage("Данные3.Реквизит3.ПовторнаяСоздаваемаяКоллекция3", "Данные3.ОбщаяКоллекция3"), + Arrays.asList( + Ranges.create(149, 8, 90), + Ranges.create(151, 8, 90))) + + .hasIssueOnRange(157, 4, 27, + getMessage("Ключ", "Описания"), + Arrays.asList( + Ranges.create(155, 4, 27), + Ranges.create(157, 4, 27))) + + .hasIssueOnRange(161, 4, 37, + getMessage("Часть1.Часть2", "Описания2"), + Arrays.asList( + Ranges.create(159, 4, 37), + Ranges.create(161, 4, 37), + Ranges.create(162, 4, 37) + )) + + .hasIssueOnRange(171, 4, 65, + getMessage("ИмяКоманды", "Сведения2.ДобавленныеЭлементы"), + Arrays.asList( + Ranges.create(170, 4, 57), + Ranges.create(171, 4, 65) + )) + + .hasIssueOnRange(265, 4, 39, + getMessage("СтрокаТаблицы", "Коллекция()"), + Arrays.asList( + Ranges.create(264, 4, 39), + Ranges.create(265, 4, 39) + )) + + .hasIssueOnRange(268, 4, 50, + getMessage("СтрокаТаблицы2", "Коллекция2().Реквизит"), + Arrays.asList( + Ranges.create(267, 4, 50), + Ranges.create(268, 4, 50) + )) + ; + + assertThat(diagnostics).hasSize(18); + } + + @Test + void testWithAdd() { + + Map configuration = diagnosticInstance.getInfo().getDefaultConfiguration(); + configuration.put("isAllowedMethodADD", true); + diagnosticInstance.configure(configuration); + + test(); + } + + @Test + void testWithoutAdd() { + + Map configuration = diagnosticInstance.getInfo().getDefaultConfiguration(); + configuration.put("isAllowedMethodADD", false); + diagnosticInstance.configure(configuration); + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics, true) + .hasIssueOnRange(8, 4, 8, 34, + getMessage("\"Ключ1\"", "Коллекция"), + Arrays.asList( + Ranges.create(7, 4, 34), + Ranges.create(8, 4, 34))) + + .hasIssueOnRange(12, 4, 35, + getMessage("\"Ключ1\"", "Коллекция2"), + Arrays.asList( + Ranges.create(11, 4, 35), + Ranges.create(12, 4, 35))) + + .hasIssueOnRange(22, 8, 38, + getMessage("\"Ключ1\"", "Коллекция"), + Arrays.asList( + Ranges.create(21, 8, 38), + Ranges.create(22, 8, 38))) + + .hasIssueOnRange(58, 12, 76, + getMessage("ЭлементСтиля.Ключ", "ЭлементыСтиля"), + Arrays.asList( + Ranges.create(56, 12, 87), + Ranges.create(58, 12, 76))) + + .hasIssueOnRange(119, 4, 65, + getMessage("\"ДополнительныеРеквизиты\"", "ВидыСвойствНабора"), + Arrays.asList( + Ranges.create(112, 4, 63), + Ranges.create(119, 4, 65))) + + .hasIssueOnRange(147, 8, 90, + getMessage("Данные2.Реквизит2.ПовторнаяСоздаваемаяКоллекция2", "Данные2.ОбщаяКоллекция2"), + Arrays.asList( + Ranges.create(145, 8, 90), + Ranges.create(147, 8, 90))) + + .hasIssueOnRange(151, 8, 90, + getMessage("Данные3.Реквизит3.ПовторнаяСоздаваемаяКоллекция3", "Данные3.ОбщаяКоллекция3"), + Arrays.asList( + Ranges.create(149, 8, 90), + Ranges.create(151, 8, 90)) + ); + + assertThat(diagnostics).hasSize(7); + } + + private String getMessage(String keyName, String collectionName) { + return String.format("Проверьте повторную вставку %s в коллекцию %s", keyName, collectionName); + } +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyCodeBlockDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyCodeBlockDiagnosticTest.java index 2347836356d..1f1d70ff369 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyCodeBlockDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyCodeBlockDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnosticTest.java index 824830a2c6a..f30946cd34c 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyRegionDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,7 +21,6 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import org.eclipse.lsp4j.CodeAction; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyStatementDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyStatementDiagnosticTest.java index 1b17385a6fe..825ad4eb115 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyStatementDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/EmptyStatementDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnosticTest.java index 0af689b3658..f9fe8903b0e 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExcessiveAutoTestCheckDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnosticTest.java index 8add53ef789..ff0bfc7e686 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnosticTest.java index 6d187e07e6f..ae2cb71aa80 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExecuteExternalCodeInCommonModuleDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,7 +23,7 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.utils.Absolute; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; @@ -46,7 +46,7 @@ class ExecuteExternalCodeInCommonModuleDiagnosticTest extends AbstractDiagnostic private static final String PATH_TO_METADATA = "src/test/resources/metadata/designer"; private static final String PATH_TO_MODULE_FILE = "src/test/resources/metadata/designer/CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; - private MDCommonModule module; + private CommonModule module; private DocumentContext documentContext; @Test @@ -128,8 +128,6 @@ private void getDocumentContextFromFile() { getText(), context )); - - module = spy((MDCommonModule) configuration.getModulesByObject().get(documentContext.getUri())); - + module = spy((CommonModule) configuration.findChild(documentContext.getUri()).get()); } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExportVariablesDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExportVariablesDiagnosticTest.java index d70df4aa532..2c0c20162e1 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExportVariablesDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExportVariablesDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExternalAppStartingDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExternalAppStartingDiagnosticTest.java new file mode 100644 index 00000000000..01491127f24 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExternalAppStartingDiagnosticTest.java @@ -0,0 +1,132 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class ExternalAppStartingDiagnosticTest extends AbstractDiagnosticTest { + ExternalAppStartingDiagnosticTest() { + super(ExternalAppStartingDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics, true) + .hasRange(8, 4, 18) + .hasRange(9, 4, 23) + .hasRange(10, 4, 23) + .hasRange(12, 4, 26) + + .hasRange(18, 26, 44) + .hasRange(19, 26, 44) + .hasRange(20, 20, 38) + .hasRange(21, 20, 38) + .hasRange(23, 26, 42) + .hasRange(24, 26, 37) + .hasRange(25, 26, 37) + .hasRange(35, 10, 34) + + .hasRange(53, 4, 20) + .hasRange(54, 4, 20) + .hasRange(55, 4, 20) + .hasRange(56, 4, 20) + .hasSize(16); + } + + @Test + void testConfigure_checkGotoUrl() { + + Map configuration = diagnosticInstance.info.getDefaultConfiguration(); + configuration.put("checkGotoUrl", true); + diagnosticInstance.configure(configuration); + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics, true) + .hasRange(8, 4, 18) + .hasRange(9, 4, 23) + .hasRange(10, 4, 23) + .hasRange(12, 4, 26) + + .hasRange(14, 4, 32) + .hasRange(15, 26, 52) + .hasRange(16, 26, 52) + + .hasRange(18, 26, 44) + .hasRange(19, 26, 44) + .hasRange(20, 20, 38) + .hasRange(21, 20, 38) + .hasRange(23, 26, 42) + .hasRange(24, 26, 37) + .hasRange(25, 26, 37) + .hasRange(35, 10, 34) + + .hasRange(53, 4, 20) + .hasRange(54, 4, 20) + .hasRange(55, 4, 20) + .hasRange(56, 4, 20) + .hasSize(19); + } + + @Test + void testConfigure_userPatternString() { + + Map configuration = diagnosticInstance.info.getDefaultConfiguration(); + configuration.put("userPatternString", "КомандаСистемы"); + diagnosticInstance.configure(configuration); + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics, true) + .hasRange(8, 4, 18) + .hasSize(1); + } + + @Test + void testConfigure_userPatternString_checkGotoUrl() { + + Map configuration = diagnosticInstance.info.getDefaultConfiguration(); + configuration.put("checkGotoUrl", true); + configuration.put("userPatternString", "КомандаСистемы"); + diagnosticInstance.configure(configuration); + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics, true) + .hasRange(8, 4, 18) + + .hasRange(14, 4, 32) + .hasRange(15, 26, 52) + .hasRange(16, 26, 52) + + .hasSize(4); + } +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExtraCommasDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExtraCommasDiagnosticTest.java index bdd5cf4c338..31aba5633f4 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExtraCommasDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ExtraCommasDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FieldsFromJoinsWithoutIsNullDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FieldsFromJoinsWithoutIsNullDiagnosticTest.java index c5c7afbc926..30b6fb2a1e3 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FieldsFromJoinsWithoutIsNullDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FieldsFromJoinsWithoutIsNullDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FileSystemAccessDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FileSystemAccessDiagnosticTest.java new file mode 100644 index 00000000000..65b3a377310 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FileSystemAccessDiagnosticTest.java @@ -0,0 +1,87 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class FileSystemAccessDiagnosticTest extends AbstractDiagnosticTest { + FileSystemAccessDiagnosticTest() { + super(FileSystemAccessDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics, true) + .hasRange(1, 15, 35) + .hasRange(2, 15, 41) + .hasRange(3, 15, 31) + .hasRange(4, 15, 31) + .hasRange(5, 15, 38) + .hasRange(6, 15, 38) + .hasRange(7, 15, 33) + .hasRange(8, 15, 44) + .hasRange(9, 15, 44) + .hasRange(10, 15, 41) + .hasRange(11, 15, 41) + .hasRange(12, 15, 45) + .hasRange(13, 15, 41) + .hasRange(14, 15, 56) + .hasRange(19, 15, 41) + .hasRange(24, 15, 26) + + .hasRange(29, 4, 17) + .hasRange(30, 4, 18) + .hasRange(34, 4, 19) + .hasRange(36, 4, 19) + .hasRange(37, 4, 17) + .hasRange(38, 4, 18) + .hasRange(39, 4, 16) + .hasSize(23) + ; + } + + @Test + void testConfigure() { + + Map configuration = diagnosticInstance.info.getDefaultConfiguration(); + configuration.put("globalMethods", "ЗначениеВФайл"); + configuration.put("newExpression", "File"); + diagnosticInstance.configure(configuration); + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics, true) + .hasRange(1, 15, 35) + .hasRange(29, 4, 17) + .hasSize(2); + } + +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ForbiddenMetadataNameDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ForbiddenMetadataNameDiagnosticTest.java index a3899d63362..e3bfab3a21f 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ForbiddenMetadataNameDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ForbiddenMetadataNameDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,11 +21,9 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.mdo.MD; +import com.github._1c_syntax.bsl.mdo.ModuleOwner; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBSL; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectComplex; -import com.github._1c_syntax.mdclasses.mdo.attributes.AbstractMDOAttribute; import com.github._1c_syntax.utils.Absolute; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.BeforeEach; @@ -33,10 +31,8 @@ import java.util.ArrayList; import java.util.Collections; -import java.util.HashSet; import java.util.List; import java.util.Optional; -import java.util.Set; import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; import static org.mockito.Mockito.spy; @@ -58,33 +54,32 @@ void beforeTest() { void testCatalog() { var documentContext = spy(getDocumentContext()); - var mdObjectBase = spy(context.getConfiguration().getChildren().stream() - .filter(mdo -> mdo.getMdoReference().getMdoRefRu().equalsIgnoreCase("Справочник.Справочник1")) - .findFirst() + var spyCatalog = spy(context.getConfiguration() + .findCatalog(catalog -> catalog.getName().equalsIgnoreCase("Справочник1")) .get()); when(documentContext.getModuleType()).thenReturn(ModuleType.ManagerModule); - when(mdObjectBase.getName()).thenReturn("Справочник"); - - List attributes = new ArrayList<>(); - - ((AbstractMDObjectComplex) mdObjectBase).getAttributes().forEach(mdo -> { - var spyMDO = spy(mdo); - when(spyMDO.getName()).thenReturn("РегистрСведений"); - var mdoRef = spy(mdo.getMdoReference()); - when(mdoRef.getMdoRefRu()) - .thenReturn(mdo.getMdoReference().getMdoRefRu().replace("." + mdo.getName(), ".РегистрСведений")); - when(spyMDO.getMdoReference()).thenReturn(mdoRef); - when(spyMDO.getName()).thenReturn("РегистрСведений"); - attributes.add(spyMDO); - }); - - when(((AbstractMDObjectComplex) mdObjectBase).getAttributes()).thenReturn(attributes); - when(documentContext.getMdObject()).thenReturn(Optional.of(mdObjectBase)); + when(spyCatalog.getName()).thenReturn("Справочник"); + + List children = new ArrayList<>(); + spyCatalog.getPlainStorageFields() + .forEach(mdo -> { + var spyMDO = spy(mdo); + when(spyMDO.getName()).thenReturn("РегистрСведений"); + var mdoRef = spy(mdo.getMdoReference()); + when(mdoRef.getMdoRefRu()) + .thenReturn(mdo.getMdoReference().getMdoRefRu().replace("." + mdo.getName(), ".РегистрСведений")); + when(spyMDO.getMdoReference()).thenReturn(mdoRef); + when(spyMDO.getName()).thenReturn("РегистрСведений"); + children.add(spyMDO); + }); + + when(spyCatalog.getPlainStorageFields()).thenReturn(children); + when(documentContext.getMdObject()).thenReturn(Optional.of(spyCatalog)); List diagnostics = diagnosticInstance.getDiagnostics(documentContext); - assertThat(diagnostics).hasSize(5); + assertThat(diagnostics).hasSize(7); assertThat(diagnostics, true) .hasMessageOnRange("Запрещено использовать имя `Справочник` для `Справочник.Справочник1`", 0, 0, 9) .hasMessageOnRange( @@ -100,7 +95,7 @@ void testCatalog() { void testOtherMDO() { var documentContext = spy(getDocumentContext()); - Set children = new HashSet<>(); + List children = new ArrayList<>(); context.getConfiguration().getChildren().forEach(mdo -> { var spyMDO = spy(mdo); @@ -132,7 +127,7 @@ void testOtherMDO() { void testAllMDO() { var documentContext = spy(getDocumentContext()); - Set children = new HashSet<>(); + List children = new ArrayList<>(); context.getConfiguration().getChildren().forEach(mdo -> { var spyMDO = spy(mdo); @@ -142,8 +137,8 @@ void testAllMDO() { .thenReturn(mdo.getMdoReference().getMdoRefRu().replace("." + mdo.getName(), ".РегистрСведений")); when(spyMDO.getMdoReference()).thenReturn(mdoRef); when(spyMDO.getName()).thenReturn("РегистрСведений"); - if (mdo instanceof AbstractMDObjectBSL) { - when(((AbstractMDObjectBSL) spyMDO).getModules()).thenReturn(Collections.emptyList()); + if (mdo instanceof ModuleOwner) { + when(((ModuleOwner) spyMDO).getModules()).thenReturn(Collections.emptyList()); } children.add(spyMDO); }); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FormDataToValueDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FormDataToValueDiagnosticTest.java index f4d32699d80..dfa84fe9d39 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FormDataToValueDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FormDataToValueDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FullOuterJoinQueryDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FullOuterJoinQueryDiagnosticTest.java index 08347f2a3bd..89ad394e70e 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FullOuterJoinQueryDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FullOuterJoinQueryDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionNameStartsWithGetDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionNameStartsWithGetDiagnosticTest.java index 1b03f26986d..bfe1c3a9cea 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionNameStartsWithGetDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionNameStartsWithGetDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionOutParameterDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionOutParameterDiagnosticTest.java index 3138a7aee7b..2a10cd7cd83 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionOutParameterDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionOutParameterDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java index 47fedab354a..f59625daab6 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionReturnsSamePrimitiveDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionShouldHaveReturnDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionShouldHaveReturnDiagnosticTest.java index 8e13158e4da..7bb99733155 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionShouldHaveReturnDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/FunctionShouldHaveReturnDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/GetFormMethodDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/GetFormMethodDiagnosticTest.java index b355bdf3980..f3d2ccb1e8d 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/GetFormMethodDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/GetFormMethodDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/GlobalContextMethodCollision8312DiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/GlobalContextMethodCollision8312DiagnosticTest.java index 6184ee3fe96..442d64fdf31 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/GlobalContextMethodCollision8312DiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/GlobalContextMethodCollision8312DiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IdenticalExpressionsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IdenticalExpressionsDiagnosticTest.java index 2942d8962cb..4a4e9a7ff82 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IdenticalExpressionsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IdenticalExpressionsDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -67,11 +67,12 @@ void runTest() { @Test void checkMessage() { - var code = "А = ТипДокумента = Тип(\"ДокументСсылка.ПриходнаяНакладная\")\n" + - "Или ТипДокумента = Тип(\"ДокументСсылка.СчетНаОплатуПоставщика\")\n" + - "Или ТипДокумента = Тип(\"ДокументСсылка.КорректировкаПоступления\")\n" + - "Или ТипДокумента = Тип(\"ДокументСсылка.ЗаказПоставщику\")\n" + - "Или ТипДокумента = Тип(\"ДокументСсылка.СчетНаОплатуПоставщика\")"; + var code = """ + А = ТипДокумента = Тип("ДокументСсылка.ПриходнаяНакладная") + Или ТипДокумента = Тип("ДокументСсылка.СчетНаОплатуПоставщика") + Или ТипДокумента = Тип("ДокументСсылка.КорректировкаПоступления") + Или ТипДокумента = Тип("ДокументСсылка.ЗаказПоставщику") + Или ТипДокумента = Тип("ДокументСсылка.СчетНаОплатуПоставщика")"""; var context = TestUtils.getDocumentContext(code); var diagnostics = getDiagnostics(context); @@ -81,9 +82,10 @@ void checkMessage() { @Test void testThatPopularQuantificationSkipped() { - var code = "А = Байты / 1024 / 1024;\n" + - "В = Время / 24 / 60 / 60;\n" + - "Б = Байты = 1024 / \"1024\""; + var code = """ + А = Байты / 1024 / 1024; + В = Время / 24 / 60 / 60; + Б = Байты = 1024 / "1024\""""; var context = TestUtils.getDocumentContext(code); var diagnostics = getDiagnostics(context); @@ -93,9 +95,10 @@ void testThatPopularQuantificationSkipped() { @Test void testThatConfiguredPopularQuantificationSkipped() { - var code = "А = Байты / 1024 / 1024;\n" + - "В = Время / 24 / 60 / 60;\n" + - "Б = Байты = 1024 / \"1024\""; + var code = """ + А = Байты / 1024 / 1024; + В = Время / 24 / 60 / 60; + Б = Байты = 1024 / "1024\""""; // получение текущей конфигурации диагностики var configuration = diagnosticInstance.getInfo().getDefaultConfiguration(); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfConditionComplexityDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfConditionComplexityDiagnosticTest.java index b50faf3190b..11b1e3ec8c2 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfConditionComplexityDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfConditionComplexityDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedCodeBlockDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedCodeBlockDiagnosticTest.java index d77a4a5acfe..e938b0fbd33 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedCodeBlockDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedCodeBlockDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedConditionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedConditionDiagnosticTest.java index bb835a29708..2f54ffb9e06 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedConditionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseDuplicatedConditionDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseIfEndsWithElseDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseIfEndsWithElseDiagnosticTest.java index f052c7aba01..3caa8affe69 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseIfEndsWithElseDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IfElseIfEndsWithElseDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectLineBreakDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectLineBreakDiagnosticTest.java index fb8d6a72c26..27667d749ec 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectLineBreakDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectLineBreakDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectUseLikeInQueryDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectUseLikeInQueryDiagnosticTest.java index 59db1159a1c..efd8b66056b 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectUseLikeInQueryDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectUseLikeInQueryDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectUseOfStrTemplateDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectUseOfStrTemplateDiagnosticTest.java index b9543f8f374..91211b4a8fd 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectUseOfStrTemplateDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IncorrectUseOfStrTemplateDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InternetAccessDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InternetAccessDiagnosticTest.java new file mode 100644 index 00000000000..ff6f9e81907 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InternetAccessDiagnosticTest.java @@ -0,0 +1,57 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class InternetAccessDiagnosticTest extends AbstractDiagnosticTest { + InternetAccessDiagnosticTest() { + super(InternetAccessDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics, true) + .hasRange(1, 20, 75) + .hasRange(3, 18, 72) + .hasRange(5, 16, 80) + .hasRange(8, 8, 111) + .hasRange(13, 21, 65) + .hasRange(14, 17, 35) + .hasRange(15, 17, 47) + .hasRange(16, 17, 43) + .hasRange(17, 21, 51) + .hasRange(21, 14, 43) + .hasRange(27, 14, 32) + .hasRange(31, 14, 35) + .hasRange(34, 10, 21) + .hasSize(13); + } +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnosticTest.java index 9fa32365ef2..65fe0abb838 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/InvalidCharacterInFileDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -64,19 +64,21 @@ void test() { @Test void testMultiString() { - String module = "//в строке ниже неразрывный пробел\n" + - "А = \" \n" + - "|// минусы с ошибками\n" + - "|//СреднееТире = \n" + - "|–;\n" + - "|//ЦифровоеТире = \n" + - "|‒;\n" + - "|//ДлинноеТире = \n" + - "|—;\n" + - "|//ГоризонтальнаяЛиния = \n" + - "|―;\n" + - "|//НеправильныйМинус = \n" + - "|−;\";\n"; + String module = """ + //в строке ниже неразрывный пробел + А = "  + |// минусы с ошибками + |//СреднееТире =\s + |–; + |//ЦифровоеТире =\s + |‒; + |//ДлинноеТире =\s + |—; + |//ГоризонтальнаяЛиния =\s + |―; + |//НеправильныйМинус =\s + |−;"; + """; var documentContext = TestUtils.getDocumentContext(module); var diagnostics = getDiagnostics(documentContext); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticTest.java index 4fc7b0009ae..d56a251a54b 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/IsInRoleMethodDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/JoinWithSubQueryDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/JoinWithSubQueryDiagnosticTest.java index 24aa5dffdf6..a14f1e6f253 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/JoinWithSubQueryDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/JoinWithSubQueryDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/JoinWithVirtualTableDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/JoinWithVirtualTableDiagnosticTest.java index cf12684d91d..d0ae57b6136 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/JoinWithVirtualTableDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/JoinWithVirtualTableDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LatinAndCyrillicSymbolInWordDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LatinAndCyrillicSymbolInWordDiagnosticTest.java index f2132e224f3..73246ff99ea 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LatinAndCyrillicSymbolInWordDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LatinAndCyrillicSymbolInWordDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LineLengthDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LineLengthDiagnosticTest.java index f2170d68ae0..45e8d561953 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LineLengthDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LineLengthDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LogicalOrInTheWhereSectionOfQueryDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LogicalOrInTheWhereSectionOfQueryDiagnosticTest.java index 536adf74101..f439adc37a0 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LogicalOrInTheWhereSectionOfQueryDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/LogicalOrInTheWhereSectionOfQueryDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java index 59affb0d359..2f7ba2af51e 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicDateDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -39,30 +39,48 @@ void test() { List diagnostics = getDiagnostics(); - assertThat(diagnostics).hasSize(5); + assertThat(diagnostics).hasSize(18); assertThat(diagnostics, true) - .hasRange(1, 12, 1, 22) - .hasRange(2, 12, 2, 28) - .hasRange(3, 7, 3, 17) - .hasRange(4, 14, 4, 24) - .hasRange(13, 7, 13, 26); - + .hasRange(11, 12, 22) + .hasRange(12, 12, 28) + .hasRange(13, 7, 17) + .hasRange(14, 14, 24) + .hasRange(23, 7, 26) + .hasRange(25, 87, 97) + .hasRange(26, 80, 90) + .hasRange(26, 92, 102) + .hasRange(27, 22, 32) + .hasRange(28, 19, 35) + .hasRange(29, 10, 26) + .hasRange(29, 29, 39) + .hasRange(31, 64, 80) + .hasRange(58, 17, 27) + .hasRange(58, 29, 45) + .hasRange(58, 47, 63) + .hasRange(60, 19, 29) + .hasRange(65, 22, 32); } @Test void testConfigure() { Map configuration = diagnosticInstance.getInfo().getDefaultConfiguration(); - configuration.put("authorizedDates", "00010101,00010101000000,000101010000,12340101, 00020101 ,,"); + configuration.put("authorizedDates", "00010101,00010101000000,000101010000,00050101,00020501121314,12340101, 00020101 ,,"); diagnosticInstance.configure(configuration); List diagnostics = getDiagnostics(); - assertThat(diagnostics).hasSize(3); + assertThat(diagnostics).hasSize(10); assertThat(diagnostics, true) - .hasRange(2, 12, 2, 28) - .hasRange(3, 7, 3, 17) - .hasRange(13, 7, 13, 26); - + .hasRange(12, 12, 28) + .hasRange(13, 7, 17) + .hasRange(23, 7, 26) + .hasRange(27, 22, 32) + .hasRange(29, 29, 39) + .hasRange(31, 64, 80) + .hasRange(58, 17, 27) + .hasRange(58, 29, 45) + .hasRange(58, 47, 63) + .hasRange(65, 22, 32); } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnosticTest.java index d58e9d2f0a1..268e785f0f9 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MagicNumberDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -42,15 +42,20 @@ void runTest() { List diagnostics = getDiagnostics(); // then - assertThat(diagnostics).hasSize(7); + assertThat(diagnostics).hasSize(12); assertThat(diagnostics, true) - .hasRange(3, 18, 3, 20) - .hasRange(3, 23, 3, 25) - .hasRange(7, 31, 7, 33) - .hasRange(11, 20, 11, 21) - .hasRange(20, 21, 20, 23) - .hasRange(23, 24, 23, 26) - .hasRange(27, 34, 27, 35); + .hasRange(3, 18, 20) + .hasRange(3, 23, 25) + .hasRange(7, 31, 33) + .hasRange(11, 20, 21) + .hasRange(20, 21, 23) + .hasRange(23, 24, 26) + .hasRange(27, 34, 35) + .hasRange(33, 37, 38) + .hasRange(34, 37, 38) + .hasRange(36, 87, 88) + .hasRange(37, 55, 56) + .hasRange(41, 16, 19); } @Test @@ -64,12 +69,17 @@ void testConfigure() { List diagnostics = getDiagnostics(); // then - assertThat(diagnostics).hasSize(4); + assertThat(diagnostics).hasSize(9); assertThat(diagnostics, true) - .hasRange(7, 31, 7, 33) - .hasRange(11, 20, 11, 21) - .hasRange(20, 21, 20, 23) - .hasRange(23, 24, 23, 26); + .hasRange(7, 31, 33) + .hasRange(11, 20, 21) + .hasRange(20, 21, 23) + .hasRange(23, 24, 26) + .hasRange(33, 37, 38) + .hasRange(34, 37, 38) + .hasRange(36, 87, 88) + .hasRange(37, 55, 56) + .hasRange(41, 16, 19); } @Test @@ -83,17 +93,22 @@ void testIndexes() { List diagnostics = getDiagnostics(); // then - assertThat(diagnostics).hasSize(9); + assertThat(diagnostics).hasSize(14); assertThat(diagnostics, true) - .hasRange(3, 18, 3, 20) - .hasRange(3, 23, 3, 25) - .hasRange(7, 31, 7, 33) - .hasRange(11, 20, 11, 21) - .hasRange(20, 21, 20, 23) - .hasRange(23, 24, 23, 26) - .hasRange(27, 34, 27, 35) - .hasRange(53, 32, 53, 34) - .hasRange(54, 18, 54, 20); + .hasRange(3, 18, 20) + .hasRange(3, 23, 25) + .hasRange(7, 31, 33) + .hasRange(11, 20, 21) + .hasRange(20, 21, 23) + .hasRange(23, 24, 26) + .hasRange(27, 34, 35) + .hasRange(33, 37, 38) + .hasRange(34, 37, 38) + .hasRange(36, 87, 88) + .hasRange(37, 55, 56) + .hasRange(41, 16, 19) + .hasRange(52, 32, 34) + .hasRange(53, 18, 20); } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MetadataObjectNameLengthDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MetadataObjectNameLengthDiagnosticTest.java index d394e9932cc..af58f3a55bd 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MetadataObjectNameLengthDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MetadataObjectNameLengthDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,8 +23,10 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import com.github._1c_syntax.bsl.mdo.CommonModule; +import com.github._1c_syntax.bsl.mdo.MD; +import com.github._1c_syntax.bsl.mdo.children.ObjectModule; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; import lombok.SneakyThrows; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; @@ -35,12 +37,11 @@ import org.springframework.test.annotation.DirtiesContext; import java.io.File; -import java.util.HashSet; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; -import java.util.Set; import java.util.stream.Stream; import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; @@ -53,7 +54,7 @@ class MetadataObjectNameLengthDiagnosticTest extends AbstractDiagnosticTest children = new HashSet<>(); + List children = new ArrayList<>(); List.of("CommandGroup.ГруппаКоманд1", "EventSubscription.ВерсионированиеПриЗаписи", "Role.ПолныеПрава").forEach((String mdoName) -> { - var mdObjectBase = spy(context.getConfiguration().getChildren().stream() + var spyMdo = spy(context.getConfiguration().getChildren().stream() .filter(mdo -> mdo.getMdoReference().getMdoRef().equalsIgnoreCase(mdoName)) .findFirst() .get()); // given - when(mdObjectBase.getName()).thenReturn(LONG_NAME); - children.add(mdObjectBase); + when(spyMdo.getName()).thenReturn(LONG_NAME); + children.add(spyMdo); }); var configuration = spy(context.getConfiguration()); @@ -190,7 +191,14 @@ void getDocumentContextFromFile(String modulePath, String content) { initServerContext(PATH_TO_METADATA); var testFile = new File(PATH_TO_METADATA, modulePath).getAbsoluteFile(); documentContext = spy(TestUtils.getDocumentContext(testFile.toURI(), content, context)); - module = spy((AbstractMDObjectBase) Objects.requireNonNull(context).getConfiguration().getModulesByObject().get(documentContext.getUri())); + var moduleByUri = Objects.requireNonNull(context).getConfiguration() + .getModuleByUri(documentContext.getUri()).get(); + if (moduleByUri instanceof CommonModule) { + module = spy((CommonModule) moduleByUri); + } else { + module = spy(Objects.requireNonNull(context).getConfiguration().findChild(((ObjectModule) moduleByUri).getOwner()) + .get()); + } } static Stream contentProvider() { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MethodSizeDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MethodSizeDiagnosticTest.java index 7732a23009f..fec8c3f0ea8 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MethodSizeDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MethodSizeDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissedRequiredParameterDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissedRequiredParameterDiagnosticTest.java new file mode 100644 index 00000000000..dff67a11f7e --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissedRequiredParameterDiagnosticTest.java @@ -0,0 +1,76 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; +import com.github._1c_syntax.utils.Absolute; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +@CleanupContextBeforeClassAndAfterEachTestMethod +class MissedRequiredParameterDiagnosticTest extends AbstractDiagnosticTest { + private static final String PATH_TO_METADATA = "src/test/resources/metadata/designer"; + + MissedRequiredParameterDiagnosticTest() { + super(MissedRequiredParameterDiagnostic.class); + } + + @Test + void testLocalMethod() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(5); + assertThat(diagnostics, true) + .hasRange(2, 16, 2, 29) + .hasRange(8, 16, 8, 27) + .hasRange(14, 16, 14, 26) + .hasRange(17, 13, 17, 24) + .hasRange(18, 13, 18, 35) + ; + } + + @Test + void testSideMethod() { + + initServerContext(Absolute.path(PATH_TO_METADATA)); + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(9); + assertThat(diagnostics, true) + .hasRange(2, 16, 2, 29) + .hasRange(8, 16, 8, 27) + .hasRange(14, 16, 14, 26) + .hasRange(17, 13, 17, 24) + .hasRange(18, 13, 18, 35) + .hasRange(24, 22, 24, 49) + .hasRange(25, 22, 25, 50) + .hasRange(26, 22, 26, 48) + .hasRange(27, 31, 27, 57) + ; + } +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCodeTryCatchExDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCodeTryCatchExDiagnosticTest.java index 2bfc926cd52..5f3302efd3d 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCodeTryCatchExDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCodeTryCatchExDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCommonModuleMethodDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCommonModuleMethodDiagnosticTest.java new file mode 100644 index 00000000000..cae6969ffa1 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingCommonModuleMethodDiagnosticTest.java @@ -0,0 +1,70 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; +import com.github._1c_syntax.utils.Absolute; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +@CleanupContextBeforeClassAndAfterEachTestMethod +class MissingCommonModuleMethodDiagnosticTest extends AbstractDiagnosticTest { + + private static final String PATH_TO_METADATA = "src/test/resources/metadata/designer"; + + MissingCommonModuleMethodDiagnosticTest() { + super(MissingCommonModuleMethodDiagnostic.class); + } + + @Test + void test() { + initServerContext(Absolute.path(PATH_TO_METADATA)); + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics, true) + .hasMessageOnRange("Метод МетодНесуществующий общего модуля ПервыйОбщийМодуль не существует", 1, 22, 41) + .hasMessageOnRange("Метод ДругойМетодНесуществующий общего модуля ПервыйОбщийМодуль не существует", 2, 26, 51) + .hasMessageOnRange("Метод ЕщеМетодНесуществующий общего модуля ПервыйОбщийМодуль не существует", 3, 22, 44) + .hasMessageOnRange("Метод ЕщеОдинМетодНесуществующий общего модуля ПервыйОбщийМодуль не существует", 4, 22, 48) + .hasMessageOnRange("Метод ЕщеДругойМетодНесуществующий общего модуля ПервыйОбщийМодуль не существует", 5, 26, 54) + + .hasMessageOnRange("Исправьте обращение к закрытому, неэкспортному методу РегистрацияИзмененийПередУдалением общего модуля ПервыйОбщийМодуль", 11, 22, 56) + .hasMessageOnRange("Исправьте обращение к закрытому, неэкспортному методу Тест общего модуля ПервыйОбщийМодуль", 12, 26, 30) + .hasMessageOnRange("Исправьте обращение к закрытому, неэкспортному методу Тест общего модуля ПервыйОбщийМодуль", 13, 22, 26) + .hasMessageOnRange("Исправьте обращение к закрытому, неэкспортному методу Тест общего модуля ПервыйОбщийМодуль", 14, 22, 26) + .hasMessageOnRange("Исправьте обращение к закрытому, неэкспортному методу Тест общего модуля ПервыйОбщийМодуль", 15, 26, 30) + .hasSize(10); + } + + @Test + void testWithoutMetadata() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).isEmpty(); + } +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingEventSubscriptionHandlerDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingEventSubscriptionHandlerDiagnosticTest.java index 87ffebde551..c939908148e 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingEventSubscriptionHandlerDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingEventSubscriptionHandlerDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingParameterDescriptionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingParameterDescriptionDiagnosticTest.java index a5e7607fb4e..5ccdd89ddc3 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingParameterDescriptionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingParameterDescriptionDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingReturnedValueDescriptionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingReturnedValueDescriptionDiagnosticTest.java index 5929e80a69c..ac2b0f32221 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingReturnedValueDescriptionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingReturnedValueDescriptionDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnosticTest.java index 6b0e0338cd2..34b7584f6d5 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingSpaceDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTempStorageDeletionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTempStorageDeletionDiagnosticTest.java index 72fd271cf98..9c78875e43a 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTempStorageDeletionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTempStorageDeletionDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -66,9 +66,10 @@ void testFileCodeBlock() { void testFileCodeBlockWithoutError() { var diagnostics = getDiagnosticList( - "ПодобранныеТоварыТело2 = ПолучитьИзВременногоХранилища(АдресТоваровВХранилищеТело2); // не ошибка\n" + - "Объект.Товары.Загрузить(ПодобранныеТоварыТело2);\n" + - "УдалитьИзВременногоХранилища(АдресТоваровВХранилищеТело2)"); + """ + ПодобранныеТоварыТело2 = ПолучитьИзВременногоХранилища(АдресТоваровВХранилищеТело2); // не ошибка + Объект.Товары.Загрузить(ПодобранныеТоварыТело2); + УдалитьИзВременногоХранилища(АдресТоваровВХранилищеТело2)"""); assertThat(diagnostics).isEmpty(); @@ -78,21 +79,22 @@ void testFileCodeBlockWithoutError() { void testTryBlockWithoutError() { var diagnostics = getDiagnosticList( - "&НаСервере\n" + - "Процедура ПолучитьТоварыИзХранилища_Успешно1()\n" + - "\n" + - " Адрес = \"\";\n" + - " Попытка\n" + - " ОбщийМодуль.ПолучитьАдрес(Адрес);\n" + - "\n" + - " ПодобранныеТовары = ПолучитьИзВременногоХранилища(Адрес); // не ошибка\n" + - " Результат = ПодобранныеТовары.ВыгрузитьКолонку(\"Наименование\");\n" + - "\n" + - " УдалитьИзВременногоХранилища(Адрес);\n" + - " Исключение\n" + - " КонецПопытки;\n" + - "\n" + - "КонецПроцедуры"); + """ + &НаСервере + Процедура ПолучитьТоварыИзХранилища_Успешно1() + + Адрес = ""; + Попытка + ОбщийМодуль.ПолучитьАдрес(Адрес); + + ПодобранныеТовары = ПолучитьИзВременногоХранилища(Адрес); // не ошибка + Результат = ПодобранныеТовары.ВыгрузитьКолонку("Наименование"); + + УдалитьИзВременногоХранилища(Адрес); + Исключение + КонецПопытки; + + КонецПроцедуры"""); assertThat(diagnostics).isEmpty(); @@ -102,11 +104,12 @@ void testTryBlockWithoutError() { void testFileBlockBeforeSubForTester() { var diagnostics = getDiagnosticList( - "Данные = ПолучитьИзВременногоХранилища( тут.Адрес );\n" + - "Данные.Записать ( \"c:\\mydata.txt\" );\n" + - "&НаСервере\n" + - "Процедура Обработать ()\n" + - "КонецПроцедуры"); + """ + Данные = ПолучитьИзВременногоХранилища( тут.Адрес ); + Данные.Записать ( "c:\\mydata.txt" ); + &НаСервере + Процедура Обработать () + КонецПроцедуры"""); assertThat(diagnostics, true) .hasRange(0, 9, 51) @@ -119,12 +122,13 @@ void testFileBlockBeforeSubForTester() { void testTryFileBlockBeforeSubForTesterWithoutError() { var diagnostics = getDiagnosticList( - "Данные = ПолучитьИзВременногоХранилища( тут.Адрес );\n" + - "Данные.Записать ( \"c:\\mydata.txt\" );\n" + - "УдалитьИзВременногоХранилища( тут.Адрес );\n" + - "&НаСервере\n" + - "Процедура Обработать ()\n" + - "КонецПроцедуры"); + """ + Данные = ПолучитьИзВременногоХранилища( тут.Адрес ); + Данные.Записать ( "c:\\mydata.txt" ); + УдалитьИзВременногоХранилища( тут.Адрес ); + &НаСервере + Процедура Обработать () + КонецПроцедуры"""); assertThat(diagnostics).isEmpty(); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTemporaryFileDeletionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTemporaryFileDeletionDiagnosticTest.java index 9a310296c29..9e56093bdbe 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTemporaryFileDeletionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingTemporaryFileDeletionDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticTest.java index a366b892be9..a78ee1536d7 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MissingVariablesDescriptionDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilineStringInQueryDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilineStringInQueryDiagnosticTest.java index 38ce53f86b4..79b0cedf300 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilineStringInQueryDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilineStringInQueryDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilingualStringHasAllDeclaredLanguagesDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilingualStringHasAllDeclaredLanguagesDiagnosticTest.java index d6abc240734..24203e0b1cf 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilingualStringHasAllDeclaredLanguagesDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilingualStringHasAllDeclaredLanguagesDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilingualStringUsingWithTemplateDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilingualStringUsingWithTemplateDiagnosticTest.java index 9bb1facecf5..ab343c152e5 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilingualStringUsingWithTemplateDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/MultilingualStringUsingWithTemplateDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedConstructorsInStructureDeclarationDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedConstructorsInStructureDeclarationDiagnosticTest.java index b01d5846813..339b7d542d1 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedConstructorsInStructureDeclarationDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedConstructorsInStructureDeclarationDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,12 +22,12 @@ package com.github._1c_syntax.bsl.languageserver.diagnostics; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import jakarta.annotation.PostConstruct; import org.eclipse.lsp4j.Diagnostic; import org.eclipse.lsp4j.DiagnosticRelatedInformation; import org.eclipse.lsp4j.Range; import org.junit.jupiter.api.Test; -import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.List; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedFunctionInParametersDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedFunctionInParametersDiagnosticTest.java index 76e193486cd..129b1a234f9 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedFunctionInParametersDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedFunctionInParametersDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedStatementsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedStatementsDiagnosticTest.java index 0a2c1471c5b..39ea71c4602 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedStatementsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedStatementsDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedTernaryOperatorDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedTernaryOperatorDiagnosticTest.java index ae683c3b5f6..25a98b24d32 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedTernaryOperatorDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NestedTernaryOperatorDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonExportMethodsInApiRegionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonExportMethodsInApiRegionDiagnosticTest.java index ee97b519583..0931a811b6f 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonExportMethodsInApiRegionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonExportMethodsInApiRegionDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnosticTest.java index 9cc03aea53b..5486c6638b0 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NonStandardRegionDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfOptionalParamsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfOptionalParamsDiagnosticTest.java index f801cd6bb9c..55791de5c3a 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfOptionalParamsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfOptionalParamsDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfParamsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfParamsDiagnosticTest.java index 8b18a808eff..b87e904cc21 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfParamsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfParamsDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfValuesInStructureConstructorDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfValuesInStructureConstructorDiagnosticTest.java index a472cf5eaa1..b716e7c16ba 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfValuesInStructureConstructorDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/NumberOfValuesInStructureConstructorDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OSUsersMethodDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OSUsersMethodDiagnosticTest.java index fb669054aba..c267d4a4276 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OSUsersMethodDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OSUsersMethodDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OneStatementPerLineDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OneStatementPerLineDiagnosticTest.java index 32db291314a..311525d10e0 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OneStatementPerLineDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OneStatementPerLineDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OrderOfParamsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OrderOfParamsDiagnosticTest.java index 23813647ad9..4cbe7b41103 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OrderOfParamsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OrderOfParamsDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OrdinaryAppSupportDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OrdinaryAppSupportDiagnosticTest.java index 04f637bd62e..0ef172fea4f 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OrdinaryAppSupportDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/OrdinaryAppSupportDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PairingBrokenTransactionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PairingBrokenTransactionDiagnosticTest.java index cc43ab7ab18..938a9ff36cc 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PairingBrokenTransactionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PairingBrokenTransactionDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnosticTest.java index a9537cd5a27..bce7cb3c6e9 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ParseErrorDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PrivilegedModuleMethodCallDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PrivilegedModuleMethodCallDiagnosticTest.java new file mode 100644 index 00000000000..66eb20cd6a6 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PrivilegedModuleMethodCallDiagnosticTest.java @@ -0,0 +1,91 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +class PrivilegedModuleMethodCallDiagnosticTest extends AbstractDiagnosticTest { + private static final String PATH_TO_METADATA = "src/test/resources/metadata/privilegedModules"; + private static final String PATH_TO_MODULE_FILE = PATH_TO_METADATA + "/CommonModules/ПривилегированныйМодуль1/Ext/Module.bsl"; + + PrivilegedModuleMethodCallDiagnosticTest() { + super(PrivilegedModuleMethodCallDiagnostic.class); + } + + @Test + void testWithoutMetadata() { + var diagnostics = getDiagnostics(); + assertThat(diagnostics).isEmpty(); + } + + @Test + void test() { + initServerContext(PATH_TO_METADATA); + + var diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(2); + assertThat(diagnostics, true) + .hasMessageOnRange("Проверьте обращение к методу ПубличнаяФункция привилегированного модуля", 3, 40, 56) + .hasMessageOnRange("Проверьте обращение к методу ПубличнаяПроцедура привилегированного модуля", 4, 29, 47); + } + + @Test + void getNestedCalls() { + var diagnostics = getDiagnosticsAsCommonModule(); + assertThat(diagnostics).hasSize(2); + assertThat(diagnostics, true) + .hasMessageOnRange("Проверьте обращение к методу ПубличнаяФункция привилегированного модуля", 15, 15, 31) + .hasMessageOnRange("Проверьте обращение к методу ПубличнаяПроцедура привилегированного модуля", 19, 4, 22); + } + + @Test + void testParameterValidateNestedCalls() { + Map configuration = diagnosticInstance.getInfo().getDefaultConfiguration(); + configuration.put("validateNestedCalls", false); + diagnosticInstance.configure(configuration); + + var diagnostics = getDiagnosticsAsCommonModule(); + assertThat(diagnostics).isEmpty(); + } + + private List getDiagnosticsAsCommonModule() { + Path moduleFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + + initServerContext(PATH_TO_METADATA); + + var documentContext = spy(getDocumentContext(diagnosticInstance.getClass().getSimpleName())); + when(documentContext.getUri()).thenReturn(moduleFile.toUri()); + + return getDiagnostics(documentContext); + } +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProcedureReturnsValueDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProcedureReturnsValueDiagnosticTest.java index 51a0a71102b..62e2ad26c40 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProcedureReturnsValueDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProcedureReturnsValueDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProtectedModuleDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProtectedModuleDiagnosticTest.java new file mode 100644 index 00000000000..8c52dfa580a --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ProtectedModuleDiagnosticTest.java @@ -0,0 +1,63 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.types.ModuleType; +import com.github._1c_syntax.utils.Absolute; +import org.eclipse.lsp4j.Diagnostic; +import org.eclipse.lsp4j.Range; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +class ProtectedModuleDiagnosticTest extends AbstractDiagnosticTest { + ProtectedModuleDiagnosticTest() { + super(ProtectedModuleDiagnostic.class); + } + + private static final String PATH_TO_METADATA = "src/test/resources/metadata/subSystemFilter"; + + @Test + void test() { + initServerContext(Absolute.path(PATH_TO_METADATA)); + var documentContext = spy(getDocumentContext()); + when(documentContext.getModuleType()).thenReturn(ModuleType.SessionModule); + + List diagnostics = getDiagnostics(documentContext); + assertThat(diagnostics, true) + .hasSize(1) + .allMatch( + diagnostic -> diagnostic.getRange().equals(getRange())) + .anyMatch(diagnostic -> diagnostic.getMessage() + .equals("Исходный код модуля отсутствует из-за защиты паролем. ОбщийМодуль.ОбщийМодуль1")) + ; + } + + private static Range getRange() { + return Ranges.create(0, 0, 9); + } +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PublicMethodsDescriptionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PublicMethodsDescriptionDiagnosticTest.java index 371912b36c6..40d14475d16 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PublicMethodsDescriptionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/PublicMethodsDescriptionDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryParseErrorDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryParseErrorDiagnosticTest.java index 5a5caf1801c..ff1254e962b 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryParseErrorDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryParseErrorDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryToMissingMetadataDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryToMissingMetadataDiagnosticTest.java index 72352cd4404..ce42684a0d8 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryToMissingMetadataDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/QueryToMissingMetadataDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RedundantAccessToObjectDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RedundantAccessToObjectDiagnosticTest.java index 9748f7975a7..8e1239e28d8 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RedundantAccessToObjectDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RedundantAccessToObjectDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,8 +24,8 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import com.github._1c_syntax.bsl.mdo.CommonModule; import com.github._1c_syntax.bsl.mdo.support.ReturnValueReuse; -import com.github._1c_syntax.mdclasses.mdo.MDCommonModule; import com.github._1c_syntax.utils.Absolute; import lombok.SneakyThrows; import org.apache.commons.io.FileUtils; @@ -86,7 +86,7 @@ void testCommonModuleCached() { ); var configuration = context.getConfiguration(); - var module = spy((MDCommonModule) configuration.getModulesByObject().get(documentContext.getUri())); + var module = spy((CommonModule) configuration.findChild(documentContext.getUri()).get()); when(module.getReturnValuesReuse()).thenReturn(ReturnValueReuse.DURING_SESSION); when(documentContext.getMdObject()).thenReturn(Optional.of(module)); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RefOveruseDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RefOveruseDiagnosticTest.java index 86dc114c122..9b222e1038e 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RefOveruseDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RefOveruseDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,6 +21,8 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; +import com.github._1c_syntax.utils.Absolute; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; @@ -28,13 +30,48 @@ import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +@CleanupContextBeforeClassAndAfterEachTestMethod class RefOveruseDiagnosticTest extends AbstractDiagnosticTest { + private static final String PATH_TO_METADATA = "src/test/resources/metadata/designer"; + RefOveruseDiagnosticTest() { super(RefOveruseDiagnostic.class); } @Test void test() { + initServerContext(Absolute.path(PATH_TO_METADATA)); + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics, true) + .hasRange(3, 28, 3, 45) + .hasRange(13, 8, 13, 34) + .hasRange(14, 8, 14, 38) + .hasRange(25, 8, 25, 21) + .hasRange(37, 8, 37, 29) + .hasRange(38, 8, 38, 35) + .hasRange(56, 13, 43) + .hasRange(57, 14, 48) + .hasRange(92, 8, 29) + .hasRange(153, 13, 153, 41) + .hasRange(164, 13, 164, 53) + .hasRange(178, 13, 178, 35) + .hasRange(216, 13, 37) + .hasRange(226, 13, 37) + .hasRange(238, 13, 38) + .hasRange(296, 33, 80) + .hasRange(300, 33, 70) + .hasRange(309, 12, 28) + .hasRange(342, 12, 56) + .hasRange(343, 12, 56) + .hasRange(354, 26, 96) + .hasRange(364, 9, 44) // TODO не должно быть ошибкой + .hasRange(378, 20, 55) // TODO не должно быть ошибкой + .hasSize(23); + } + @Test + void testSingleFile() { List diagnostics = getDiagnostics(); @@ -45,8 +82,8 @@ void test() { .hasRange(25, 8, 25, 21) .hasRange(37, 8, 37, 29) .hasRange(38, 8, 38, 35) - .hasRange(56, 37, 56, 43) - .hasRange(57, 42, 57, 48) + .hasRange(56, 13, 43) + .hasRange(57, 14, 48) .hasRange(92, 8, 29) .hasRange(153, 13, 153, 41) .hasRange(164, 13, 164, 53) @@ -54,6 +91,14 @@ void test() { .hasRange(216, 13, 37) .hasRange(226, 13, 37) .hasRange(238, 13, 38) - .hasSize(15); + .hasRange(296, 33, 80) + .hasRange(300, 33, 70) + .hasRange(309, 12, 28) + .hasRange(342, 12, 56) + .hasRange(343, 12, 56) + .hasRange(354, 26, 96) + .hasRange(364, 9, 44) + .hasRange(378, 20, 55) + .hasSize(23); } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ReservedParameterNamesDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ReservedParameterNamesDiagnosticTest.java new file mode 100644 index 00000000000..b3513e17ad7 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ReservedParameterNamesDiagnosticTest.java @@ -0,0 +1,75 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class ReservedParameterNamesDiagnosticTest extends AbstractDiagnosticTest { + ReservedParameterNamesDiagnosticTest() { + super(ReservedParameterNamesDiagnostic.class); + } + + @Test + void testEmpty() { + List diagnostics = getDiagnostics(); + assertThat(diagnostics).isEmpty(); + } + + @Test + void testPositive() { + + Map configuration = diagnosticInstance.info.getDefaultConfiguration(); + configuration.put("reservedWords", "ВидГруппыФормы"); + diagnosticInstance.configure(configuration); + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(1); + assertThat(diagnostics, true) + .hasMessageOnRange("Переименуйте параметр \"ВидГруппыФормы\" так, чтобы он не совпадал с зарезервированным словом.", + 2, 16, 30); + + } + + @ParameterizedTest + @ValueSource(strings = {" ", "ВидГруппы", "ВидГруппыФормыРасширенный"}) + void testNegative(String testWord) { + + Map configuration = diagnosticInstance.info.getDefaultConfiguration(); + configuration.put("reservedWords", testWord); + diagnosticInstance.configure(configuration); + + List diagnostics = getDiagnostics(); + assertThat(diagnostics).isEmpty(); + + } + +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RewriteMethodParameterDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RewriteMethodParameterDiagnosticTest.java index d498c9871f1..26491db8b1d 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RewriteMethodParameterDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/RewriteMethodParameterDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SameMetadataObjectAndChildNamesDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SameMetadataObjectAndChildNamesDiagnosticTest.java index 85f9882968b..a8cafd9767e 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SameMetadataObjectAndChildNamesDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SameMetadataObjectAndChildNamesDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,12 +21,14 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.mdo.Attribute; +import com.github._1c_syntax.bsl.mdo.AttributeOwner; +import com.github._1c_syntax.bsl.mdo.Catalog; +import com.github._1c_syntax.bsl.mdo.MD; +import com.github._1c_syntax.bsl.mdo.ModuleOwner; +import com.github._1c_syntax.bsl.mdo.TabularSection; +import com.github._1c_syntax.bsl.mdo.TabularSectionOwner; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectComplex; -import com.github._1c_syntax.mdclasses.mdo.attributes.AbstractMDOAttribute; -import com.github._1c_syntax.mdclasses.mdo.attributes.TabularSection; -import com.github._1c_syntax.mdclasses.mdo.metadata.AttributeType; import com.github._1c_syntax.utils.Absolute; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.BeforeEach; @@ -34,10 +36,8 @@ import java.util.ArrayList; import java.util.Collections; -import java.util.HashSet; import java.util.List; import java.util.Optional; -import java.util.Set; import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; import static org.mockito.Mockito.spy; @@ -59,38 +59,37 @@ void beforeTest() { void testCatalog() { var documentContext = spy(getDocumentContext()); - var mdObjectBase = spy(context.getConfiguration().getChildren().stream() + var spyMDO = (Catalog) spy(context.getConfiguration().getChildren().stream() .filter(mdo -> mdo.getMdoReference().getMdoRefRu().equalsIgnoreCase("Справочник.Справочник1")) .findFirst() .get()); when(documentContext.getModuleType()).thenReturn(ModuleType.ManagerModule); - List attributes = new ArrayList<>(); + List attributes = new ArrayList<>(); + List tabularSections = new ArrayList<>(); - var attribute = spy(((AbstractMDObjectComplex) mdObjectBase).getAttributes().stream() - .filter(mdo -> mdo.getAttributeType() == AttributeType.ATTRIBUTE) + var attribute = spy(spyMDO.getAllAttributes().stream() .findFirst() .get()); when(attribute.getName()).thenReturn("Справочник1"); attributes.add(attribute); - var tabularSection = spy(((AbstractMDObjectComplex) mdObjectBase).getAttributes().stream() - .filter(mdo -> mdo.getAttributeType() == AttributeType.TABULAR_SECTION) - .map(TabularSection.class::cast) + var tabularSection = spy(spyMDO.getTabularSections().stream() .findFirst() .get()); when(tabularSection.getName()).thenReturn("Тара"); - attributes.add(tabularSection); + tabularSections.add(tabularSection); var tabAttribute = spy(tabularSection.getAttributes().get(0)); when(tabAttribute.getName()).thenReturn("Тара"); when(tabularSection.getAttributes()).thenReturn(List.of(tabAttribute)); - when(((AbstractMDObjectComplex) mdObjectBase).getAttributes()).thenReturn(attributes); - when(documentContext.getMdObject()).thenReturn(Optional.of(mdObjectBase)); + when(spyMDO.getAllAttributes()).thenReturn(attributes); + when(spyMDO.getTabularSections()).thenReturn(tabularSections); + when(documentContext.getMdObject()).thenReturn(Optional.of(spyMDO)); List diagnostics = diagnosticInstance.getDiagnostics(documentContext); @@ -105,25 +104,35 @@ void testCatalog() { void testOtherMDO() { var documentContext = spy(getDocumentContext()); - Set children = new HashSet<>(); + List children = new ArrayList<>(); context.getConfiguration().getChildren().forEach(mdo -> { - if (mdo instanceof AbstractMDObjectComplex) { - var spyMDO = spy(mdo); - List attributes = new ArrayList<>(); - ((AbstractMDObjectComplex) mdo).getAttributes().forEach(mdoAttribute -> { - var attribute = spy(mdoAttribute); - when(attribute.getName()).thenReturn(mdo.getName()); - attributes.add(attribute); - }); - when(((AbstractMDObjectComplex) spyMDO).getAttributes()).thenReturn(attributes); + var spyMDO = spy(mdo); - if (!mdo.getName().equalsIgnoreCase("Справочник1")) { - when(((AbstractMDObjectComplex) spyMDO).getModules()).thenReturn(Collections.emptyList()); - } + if (!(mdo instanceof ModuleOwner || mdo instanceof AttributeOwner || mdo instanceof TabularSectionOwner) + || mdo.getName().equalsIgnoreCase("Справочник1") + ) { + return; + } - children.add(spyMDO); + if (mdo instanceof ModuleOwner) { + when(((ModuleOwner) spyMDO).getModules()).thenReturn(Collections.emptyList()); } + + mockAttributes(mdo, spyMDO, mdo.getName()); + + if (mdo instanceof TabularSectionOwner tabularSectionOwner) { + List tabularSections = new ArrayList<>(); + tabularSectionOwner.getTabularSections().forEach(tabularSection -> { + var spyTabularSection = spy(tabularSection); + when(spyTabularSection.getName()).thenReturn(mdo.getName()); + mockAttributes(tabularSection, spyTabularSection, mdo.getName()); + tabularSections.add(spyTabularSection); + }); + when(((TabularSectionOwner) spyMDO).getTabularSections()).thenReturn(tabularSections); + } + + children.add(spyMDO); }); var configuration = spy(context.getConfiguration()); @@ -136,11 +145,23 @@ void testOtherMDO() { List diagnostics = diagnosticInstance.getDiagnostics(documentContext); assertThat(diagnostics) - .hasSize(5) + .hasSize(6) .noneMatch(diagnostic -> diagnostic.getMessage().contains("имя `Справочник.Справочник1")) .anyMatch(diagnostic -> diagnostic.getMessage().contains("имя `Документ.Документ1.Реквизит")) .anyMatch(diagnostic -> diagnostic.getMessage().contains("имя `Документ.Документ1.ТабличнаяЧасть")) .anyMatch(diagnostic -> diagnostic.getMessage().contains("имя `РегистрСведений.РегистрСведений1.Измерение")) ; } + + private static void mockAttributes(MD mdo, MD spyMDO, String parentName) { + if (mdo instanceof AttributeOwner attributeOwner) { + List attributes = new ArrayList<>(); + attributeOwner.getAllAttributes().forEach(attribute -> { + var spyAttribute = spy(attribute); + when(spyAttribute.getName()).thenReturn(parentName); + attributes.add(spyAttribute); + }); + when(((AttributeOwner) spyMDO).getAllAttributes()).thenReturn(attributes); + } + } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ScheduledJobHandlerDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ScheduledJobHandlerDiagnosticTest.java index 7cf015cb631..757ab256464 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ScheduledJobHandlerDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ScheduledJobHandlerDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,23 +23,22 @@ import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.mdo.MD; +import com.github._1c_syntax.bsl.mdo.Module; +import com.github._1c_syntax.bsl.mdo.ModuleOwner; +import com.github._1c_syntax.bsl.mdo.ScheduledJob; import com.github._1c_syntax.bsl.mdo.support.Handler; import com.github._1c_syntax.bsl.types.MDOType; import com.github._1c_syntax.bsl.types.MdoReference; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectBase; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDObjectComplex; -import com.github._1c_syntax.mdclasses.mdo.MDScheduledJob; -import com.github._1c_syntax.mdclasses.mdo.support.MDOModule; import com.github._1c_syntax.utils.Absolute; import org.eclipse.lsp4j.Diagnostic; import org.eclipse.lsp4j.Range; import org.junit.jupiter.api.Test; -import java.util.HashSet; +import java.util.ArrayList; import java.util.List; import java.util.Optional; -import java.util.Set; import java.util.stream.Collectors; import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; @@ -168,21 +167,21 @@ private List checkMockHandler(String methodPath) { var documentContext = spy(getDocumentContext()); when(documentContext.getModuleType()).thenReturn(ModuleType.SessionModule); - Set children = new HashSet<>(); + List children = new ArrayList<>(); context.getConfiguration().getChildren().forEach(mdo -> { var spyMDO = spy(mdo); - if (mdo instanceof MDScheduledJob) { - when(((MDScheduledJob) spyMDO).getHandler()).thenReturn(new Handler(methodPath)); + if (mdo instanceof ScheduledJob) { + when(((ScheduledJob) spyMDO).getMethodName()).thenReturn(new Handler(methodPath)); if (mdo.getName().equalsIgnoreCase("РегламентноеЗадание1")) { children.add(spyMDO); } - } else if (mdo instanceof AbstractMDObjectComplex) { - List modules = ((AbstractMDObjectComplex) mdo).getModules().stream() + } else if (mdo instanceof ModuleOwner moduleOwner) { + List modules = moduleOwner.getModules().stream() .filter(mdoModule -> mdoModule.getModuleType() == ModuleType.ManagerModule) .collect(Collectors.toList()); - when(((AbstractMDObjectComplex) spyMDO).getModules()).thenReturn(modules); + when(((ModuleOwner) spyMDO).getModules()).thenReturn(modules); } }); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelectTopWithoutOrderByDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelectTopWithoutOrderByDiagnosticTest.java index e31c50e37eb..10720dc1714 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelectTopWithoutOrderByDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelectTopWithoutOrderByDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelfAssignDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelfAssignDiagnosticTest.java index cdc4467d400..29a92637a8b 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelfAssignDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelfAssignDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelfInsertionDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelfInsertionDiagnosticTest.java index f5ddcd211e5..484ff08b86b 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelfInsertionDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SelfInsertionDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SemicolonPresenceDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SemicolonPresenceDiagnosticTest.java index 67ea24ec636..73aff88e9df 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SemicolonPresenceDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SemicolonPresenceDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ServerSideExportFormMethodDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ServerSideExportFormMethodDiagnosticTest.java index 4d991af6ec8..e471ca94eca 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ServerSideExportFormMethodDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ServerSideExportFormMethodDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,9 +21,9 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.mdo.Form; import com.github._1c_syntax.bsl.mdo.support.FormType; import com.github._1c_syntax.bsl.types.ModuleType; -import com.github._1c_syntax.mdclasses.mdo.AbstractMDOForm; import com.github._1c_syntax.utils.Absolute; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.BeforeEach; @@ -42,12 +42,12 @@ class ServerSideExportFormMethodDiagnosticTest extends AbstractDiagnosticTest mdo.getName().equalsIgnoreCase("ФормаЭлемента")) .findFirst() .get()); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPermissionsForNewObjectsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPermissionsForNewObjectsDiagnosticTest.java index 14cebd0b11d..626533d7c47 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPermissionsForNewObjectsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPermissionsForNewObjectsDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPrivilegedModeDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPrivilegedModeDiagnosticTest.java new file mode 100644 index 00000000000..bd3c7de8f70 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SetPrivilegedModeDiagnosticTest.java @@ -0,0 +1,46 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class SetPrivilegedModeDiagnosticTest extends AbstractDiagnosticTest { + SetPrivilegedModeDiagnosticTest() { + super(SetPrivilegedModeDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics, true) + .hasRange(2, 4, 36) + .hasRange(4, 4, 36) + .hasSize(2); + } +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SeveralCompilerDirectivesDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SeveralCompilerDirectivesDiagnosticTest.java index 2f0b3ac6221..debf42c0c75 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SeveralCompilerDirectivesDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SeveralCompilerDirectivesDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SmokyTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SmokyTest.java index 83ee8e262d5..25438cb3423 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SmokyTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SmokyTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,7 +21,6 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; -import com.ginsberg.junit.exit.ExpectSystemExitWithStatus; import com.github._1c_syntax.bsl.languageserver.BSLLSPLauncher; import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; @@ -29,9 +28,12 @@ import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; +import mockit.Mock; +import mockit.MockUp; import org.apache.commons.io.FileUtils; import org.eclipse.lsp4j.Diagnostic; import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -46,6 +48,7 @@ import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; @SpringBootTest @Slf4j @@ -58,18 +61,27 @@ class SmokyTest { @Autowired private Collection diagnosticInfos; + @BeforeEach + void setUpStreams() { + new MockUp() { + @Mock + public void exit(int value) { + throw new RuntimeException(String.valueOf(value)); + } + }; + } + @Test - @ExpectSystemExitWithStatus(0) - void test() { + void test() throws Exception { // given String[] args = new String[]{"--analyze", "--srcDir", "./src/test/resources/diagnostics"}; - // when - BSLLSPLauncher.main(args); + // when-then + assertThatThrownBy(() -> BSLLSPLauncher.main(args)) + .isInstanceOf(RuntimeException.class) + .hasMessage("0"); - // then - assertThat(true).isTrue(); } @Test @@ -131,4 +143,13 @@ void testIAllDiagnostics() { assertThat(diagnosticErrors).isEmpty(); } + @Test + void testExtraMinForComplexity() { + // нельзя ставить отрицательное значение + diagnosticInfos.forEach(diagnosticInfo -> + assertThat(diagnosticInfo.getExtraMinForComplexity()) + .as(diagnosticInfo.getCode().getStringValue()) + .isNotNegative() + ); + } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SpaceAtStartCommentDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SpaceAtStartCommentDiagnosticTest.java index ea776a86179..bec14c6ab98 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SpaceAtStartCommentDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/SpaceAtStartCommentDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/StyleElementConstructorsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/StyleElementConstructorsDiagnosticTest.java index b7deb243111..489808c129f 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/StyleElementConstructorsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/StyleElementConstructorsDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TempFilesDirDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TempFilesDirDiagnosticTest.java index 21124d02df2..92e0615782f 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TempFilesDirDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TempFilesDirDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TernaryOperatorUsageDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TernaryOperatorUsageDiagnosticTest.java index 40e6e7161f3..53d6bd2f9f5 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TernaryOperatorUsageDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TernaryOperatorUsageDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnosticTest.java index 20281c27a31..c1c2cb1c525 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/ThisObjectAssignDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TimeoutsInExternalResourcesDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TimeoutsInExternalResourcesDiagnosticTest.java index add6cdfde5e..20900b906d5 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TimeoutsInExternalResourcesDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TimeoutsInExternalResourcesDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TooManyReturnsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TooManyReturnsDiagnosticTest.java index 5c89e17c46a..90185c30fa3 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TooManyReturnsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TooManyReturnsDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TransferringParametersBetweenClientAndServerDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TransferringParametersBetweenClientAndServerDiagnosticTest.java new file mode 100644 index 00000000000..48240a16f4a --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TransferringParametersBetweenClientAndServerDiagnosticTest.java @@ -0,0 +1,54 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterClass; +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +@CleanupContextBeforeClassAndAfterClass +class TransferringParametersBetweenClientAndServerDiagnosticTest extends AbstractDiagnosticTest { + TransferringParametersBetweenClientAndServerDiagnosticTest() { + super(TransferringParametersBetweenClientAndServerDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics, true) + .hasMessageOnRange(getMessage("Парам1", "Сервер1"), 6, 18, 24) + .hasSize(1); + } + + private String getMessage(String paramName, String methodName) { + return String.format("Установите модификатор \"Знач\" для параметра %s метода %s", + paramName, methodName); + } + + +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TryNumberDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TryNumberDiagnosticTest.java index c40ecf1335b..e781a2b77fd 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TryNumberDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TryNumberDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnosticTest.java index 103b99712d7..61a73432b89 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/TypoDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnaryPlusInConcatenationDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnaryPlusInConcatenationDiagnosticTest.java index eb7cc7cd476..336055eae5a 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnaryPlusInConcatenationDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnaryPlusInConcatenationDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnionAllDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnionAllDiagnosticTest.java index 3897578c143..f5dacb17324 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnionAllDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnionAllDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnknownPreprocessorSymbolDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnknownPreprocessorSymbolDiagnosticTest.java index 1461d25ea2a..98009f4a534 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnknownPreprocessorSymbolDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnknownPreprocessorSymbolDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnosticTest.java index ffd79b6d468..1e287a73a35 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnreachableCodeDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java index bba505c39e6..ceddc056207 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnsafeSafeModeMethodCallDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalMethodDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalMethodDiagnosticTest.java index 4a4b56e468d..b9bea7be445 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalMethodDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalMethodDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,30 +21,59 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import com.github._1c_syntax.bsl.mdo.CommonModule; +import com.github._1c_syntax.bsl.types.ModuleType; +import com.github._1c_syntax.utils.Absolute; +import lombok.SneakyThrows; +import org.apache.commons.io.FileUtils; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.List; import java.util.Map; +import java.util.Optional; import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; class UnusedLocalMethodDiagnosticTest extends AbstractDiagnosticTest { + private static final String PATH_TO_METADATA = "src/test/resources/metadata/designer"; + private static final String PATH_TO_MODULE_FILE = PATH_TO_METADATA + "/CommonModules/ПервыйОбщийМодуль/Ext/Module.bsl"; + private static final String PATH_TO_MODULE_CONTENT = "src/test/resources/diagnostics/UnusedLocalMethodDiagnostic.bsl"; + + private CommonModule module; + private DocumentContext documentContext; + UnusedLocalMethodDiagnosticTest() { super(UnusedLocalMethodDiagnostic.class); } @Test void test() { - List diagnostics = getDiagnostics(); + checkByDefault(diagnostics); + } + private static void checkByDefault(List diagnostics) { assertThat(diagnostics).hasSize(2); assertThat(diagnostics, true) .hasRange(1, 10, 24) .hasRange(70, 10, 41) ; + } + + @Test + void testObjectModuleByDefault() { + getObjectModuleDocumentContext(); + List diagnostics = getDiagnostics(documentContext); + assertThat(diagnostics).isEmpty(); } @Test @@ -65,4 +94,44 @@ void testConfigure() { .hasRange(63, 10, 39) ; } + + @Test + void testObjectModuleWithEnabledConfiguration() { + // given + getObjectModuleDocumentContext(); + + Map configuration = diagnosticInstance.getInfo().getDefaultConfiguration(); + configuration.put("checkObjectModule", true); + diagnosticInstance.configure(configuration); + + // when + List diagnostics = getDiagnostics(documentContext); + + // then + checkByDefault(diagnostics); + } + + private void getObjectModuleDocumentContext() { + Path testFile = Paths.get(PATH_TO_MODULE_CONTENT).toAbsolutePath(); + getDocumentContextFromFile(testFile); + when(documentContext.getModuleType()).thenReturn(ModuleType.ObjectModule); + when(documentContext.getMdObject()).thenReturn(Optional.of(module)); + } + + @SneakyThrows + void getDocumentContextFromFile(Path testFile) { + + Path path = Absolute.path(PATH_TO_METADATA); + Path moduleFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + + initServerContext(path); + var configuration = context.getConfiguration(); + documentContext = spy(TestUtils.getDocumentContext( + testFile.toUri(), + FileUtils.readFileToString(testFile.toFile(), StandardCharsets.UTF_8), + context + )); + + module = spy((CommonModule) configuration.findChild(moduleFile.toUri()).get()); + } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalVariableDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalVariableDiagnosticTest.java index 178b4e1dfad..ade3b750d0d 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalVariableDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedLocalVariableDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedParametersDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedParametersDiagnosticTest.java index c37de8b12a6..74f30430dd0 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedParametersDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UnusedParametersDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsageWriteLogEventDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsageWriteLogEventDiagnosticTest.java index 0756b85a23e..3a0e89edaa5 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsageWriteLogEventDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsageWriteLogEventDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -54,7 +54,12 @@ void test() { .hasRange(204, 6, 206,22) .hasRange(219, 6, 221,22) .hasRange(286, 12, 291,39) - .hasSize(14) + + .hasRange(354, 6, 356,73) + .hasRange(368, 6, 370,22) + .hasRange(383, 6, 385,22) + .hasRange(439, 12, 444,39) + .hasSize(18) ; } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnosticTest.java index 8716cd6558d..5df059a4ff8 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseLessForEachDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseSystemInformationDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseSystemInformationDiagnosticTest.java new file mode 100644 index 00000000000..f1a8fe17e56 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UseSystemInformationDiagnosticTest.java @@ -0,0 +1,51 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin and contributors + * + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * BSL Language Server is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3.0 of the License, or (at your option) any later version. + * + * BSL Language Server is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with BSL Language Server. + */ +package com.github._1c_syntax.bsl.languageserver.diagnostics; + +import org.eclipse.lsp4j.Diagnostic; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; + +class UseSystemInformationDiagnosticTest extends AbstractDiagnosticTest { + UseSystemInformationDiagnosticTest() { + super(UseSystemInformationDiagnostic.class); + } + + @Test + void test() { + + List diagnostics = getDiagnostics(); + + assertThat(diagnostics).hasSize(5); + assertThat(diagnostics, true) + .hasRange(1, 26, 1, 51) + .hasRange(5, 22, 5, 49) + .hasRange(6, 22, 6, 50) + .hasRange(7, 22, 7, 38) + .hasRange(8, 22, 8, 41) + ; + + } +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingCancelParameterDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingCancelParameterDiagnosticTest.java index 82f45c9068c..37dd4a3319a 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingCancelParameterDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingCancelParameterDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingExternalCodeToolsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingExternalCodeToolsDiagnosticTest.java index 46d48599bd5..8ee5e0086b1 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingExternalCodeToolsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingExternalCodeToolsDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnosticTest.java index 479a255d921..321b6232a96 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingFindElementByStringDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -42,7 +42,7 @@ void runTest() { List diagnostics = getDiagnostics(); // then - assertThat(diagnostics).hasSize(6); + assertThat(diagnostics).hasSize(9); assertThat(diagnostics, true) .hasRange(7, 38, 7, 78) .hasRange(9, 40, 9, 61) @@ -50,8 +50,9 @@ void runTest() { .hasRange(24, 35, 24, 53) .hasRange(27, 35, 27, 51) .hasRange(30, 27, 30, 53) + .hasRange(39, 67, 110) + .hasRange(41, 35, 53) + .hasRange(44, 29, 49) ; - } - } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingGotoDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingGotoDiagnosticTest.java index 331f21d55b4..55aaaf7ed8b 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingGotoDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingGotoDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodeNetworkAddressDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodeNetworkAddressDiagnosticTest.java index ab74ec4da3d..2092604875c 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodeNetworkAddressDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodeNetworkAddressDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodePathDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodePathDiagnosticTest.java index 678a74d220b..16fa8b665e9 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodePathDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodePathDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodeSecretInformationDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodeSecretInformationDiagnosticTest.java index 5f4195d1b32..a3746d2903a 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodeSecretInformationDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingHardcodeSecretInformationDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingLikeInQueryDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingLikeInQueryDiagnosticTest.java index 2cfa91bea5d..4e827b1d487 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingLikeInQueryDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingLikeInQueryDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnosticTest.java index 8ae284efa02..f887f272944 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingModalWindowsDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -25,12 +25,13 @@ import com.github._1c_syntax.bsl.languageserver.context.ServerContext; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.mdclasses.Configuration; import com.github._1c_syntax.bsl.mdo.support.UseMode; import com.github._1c_syntax.utils.Absolute; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; -import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import java.nio.file.Paths; import java.util.List; @@ -42,7 +43,7 @@ @DirtiesContext class UsingModalWindowsDiagnosticTest extends AbstractDiagnosticTest { - @SpyBean + @MockitoSpyBean private ServerContext context; UsingModalWindowsDiagnosticTest() { @@ -119,11 +120,9 @@ private DocumentContext getDocumentContextWithUseFlag(UseMode useMode) { initServerContext(path); var configuration = spy(context.getConfiguration()); - when(configuration.getModalityUseMode()).thenReturn(useMode); + when(((Configuration) configuration).getModalityUseMode()).thenReturn(useMode); when(context.getConfiguration()).thenReturn(configuration); return TestUtils.getDocumentContext(testFile.toUri(), getText()); } - } - diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingObjectNotAvailableUnixDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingObjectNotAvailableUnixDiagnosticTest.java index e13b6bf905a..fd6365b650e 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingObjectNotAvailableUnixDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingObjectNotAvailableUnixDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingServiceTagDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingServiceTagDiagnosticTest.java index 5a53fa49d7c..4f17512631a 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingServiceTagDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingServiceTagDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnosticTest.java index a88773060a3..2cc4aec2644 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingSynchronousCallsDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,10 +24,13 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import com.github._1c_syntax.bsl.mdclasses.Configuration; import com.github._1c_syntax.bsl.mdo.support.UseMode; import com.github._1c_syntax.utils.Absolute; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.test.annotation.DirtiesContext; import java.nio.file.Paths; @@ -44,7 +47,10 @@ class UsingSynchronousCallsDiagnosticTest extends AbstractDiagnosticTest diagnostics = getDiagnostics(documentContext); assertThat(diagnostics).isEmpty(); } + @ParameterizedTest + @ValueSource(strings = {PATH_TO_OBJECT_MODULE_FILE, PATH_TO_MANAGER_MODULE_FILE, PATH_TO_SERVER_MODULE_FILE}) + void testServerModules(String file) { + var context = getDocumentContextWithUseFlag(UseMode.DONT_USE, file); + + List diagnostics = getDiagnostics(context); + assertThat(diagnostics).isEmpty(); + } + private DocumentContext getDocumentContextWithUseFlag(UseMode useMode) { + return getDocumentContextWithUseFlag(useMode, PATH_TO_CLIENT_MODULE_FILE); + } + + private DocumentContext getDocumentContextWithUseFlag(UseMode useMode, String moduleFile) { var path = Absolute.path(PATH_TO_METADATA); - var testFile = Paths.get(PATH_TO_MODULE_FILE).toAbsolutePath(); + var testFile = Paths.get(moduleFile).toAbsolutePath(); initServerContext(path); var serverContext = spy(context); var configuration = spy(serverContext.getConfiguration()); - when(configuration.getSynchronousExtensionAndAddInCallUseMode()).thenReturn(useMode); + when(((Configuration) configuration).getSynchronousExtensionAndAddInCallUseMode()).thenReturn(useMode); when(serverContext.getConfiguration()).thenReturn(configuration); var documentContext = spy(TestUtils.getDocumentContext(testFile.toUri(), getText(), serverContext)); @@ -135,5 +153,4 @@ private DocumentContext getDocumentContextWithUseFlag(UseMode useMode) { return documentContext; } - } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingThisFormDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingThisFormDiagnosticTest.java index bad63ee0915..f4e1c817704 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingThisFormDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/UsingThisFormDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,7 +21,6 @@ */ package com.github._1c_syntax.bsl.languageserver.diagnostics; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import org.eclipse.lsp4j.CodeAction; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/VirtualTableCallWithoutParametersDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/VirtualTableCallWithoutParametersDiagnosticTest.java index b1314e1db74..5f14e90d786 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/VirtualTableCallWithoutParametersDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/VirtualTableCallWithoutParametersDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongDataPathForFormElementsDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongDataPathForFormElementsDiagnosticTest.java index 62f90bcc943..0cb3a300801 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongDataPathForFormElementsDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongDataPathForFormElementsDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,8 +22,8 @@ package com.github._1c_syntax.bsl.languageserver.diagnostics; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; -import com.github._1c_syntax.mdclasses.Configuration; -import com.github._1c_syntax.mdclasses.mdo.children.Form; +import com.github._1c_syntax.bsl.mdclasses.CF; +import com.github._1c_syntax.bsl.mdo.Form; import com.github._1c_syntax.utils.Absolute; import org.eclipse.lsp4j.Diagnostic; import org.junit.jupiter.api.BeforeEach; @@ -33,8 +33,6 @@ import java.nio.file.Paths; import java.util.Collections; import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; import static com.github._1c_syntax.bsl.languageserver.util.TestUtils.PATH_TO_METADATA; @@ -64,9 +62,8 @@ void testNoFormModule() { context = spy(context); final var configuration = spy(context.getConfiguration()); - when(context.getConfiguration()).thenReturn(configuration); - fillConfigChildrenByFormsWithoutModule(configuration); + when(context.getConfiguration()).thenReturn(configuration); List diagnostics = getDiagnosticListForMockedFile(pathToManagedApplicationModuleFile); @@ -100,21 +97,24 @@ void testDynamicListFormModule() { } - private void fillConfigChildrenByFormsWithoutModule(Configuration configuration) { - final var childrenByMdoRefFromConfig = configuration.getChildrenByMdoRef(); - var childrenByMdoRef = childrenByMdoRefFromConfig.entrySet().stream() - .filter(entry -> entry.getValue() instanceof Form) - .collect(Collectors.toMap(Map.Entry::getKey, entry -> { - ((Form) entry.getValue()).setModules(Collections.emptyList()); - return entry.getValue(); - })); - when(configuration.getChildrenByMdoRef()).thenReturn(childrenByMdoRef); + private void fillConfigChildrenByFormsWithoutModule(CF configuration) { + var plainChildren = configuration.getPlainChildren().stream() + .filter(md -> md instanceof Form) + .map(md -> { + var mockMD = spy(md); + when(((Form) mockMD).getModules()).thenReturn(Collections.emptyList()); + return mockMD; + }) + .toList(); + + when(configuration.getPlainChildren()).thenReturn(plainChildren); } private List getDiagnosticListForMockedFile(String pathToDynamicListModuleFile) { var testFile = Paths.get(PATH_TO_METADATA + pathToDynamicListModuleFile).toAbsolutePath(); - var documentContext = TestUtils.getDocumentContext(testFile.toUri(), getText()); + var documentContext = spy(TestUtils.getDocumentContext(testFile.toUri(), getText())); + when(documentContext.getServerContext()).thenReturn(context); return getDiagnostics(documentContext); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongHttpServiceHandlerDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongHttpServiceHandlerDiagnosticTest.java index 3f0549f9439..8ea22ab974d 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongHttpServiceHandlerDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongHttpServiceHandlerDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongUseFunctionProceedWithCallDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongUseFunctionProceedWithCallDiagnosticTest.java index 4c4696aec14..03ab4be3a3c 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongUseFunctionProceedWithCallDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongUseFunctionProceedWithCallDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongUseOfRollbackTransactionMethodDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongUseOfRollbackTransactionMethodDiagnosticTest.java index 30aa491c1b0..a2942b3625d 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongUseOfRollbackTransactionMethodDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongUseOfRollbackTransactionMethodDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongWebServiceHandlerDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongWebServiceHandlerDiagnosticTest.java index 5a3173a7f26..ecc229b6df4 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongWebServiceHandlerDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/WrongWebServiceHandlerDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/YoLetterUsageDiagnosticTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/YoLetterUsageDiagnosticTest.java index 768f8f61b2b..2c3244ac868 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/YoLetterUsageDiagnosticTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/YoLetterUsageDiagnosticTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfoTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfoTest.java index 9756bba78b6..ded8a686c35 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfoTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/diagnostics/metadata/DiagnosticInfoTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -25,6 +25,7 @@ import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; import com.github._1c_syntax.bsl.languageserver.diagnostics.DeprecatedAttributes8312Diagnostic; import com.github._1c_syntax.bsl.languageserver.diagnostics.EmptyCodeBlockDiagnostic; +import com.github._1c_syntax.bsl.languageserver.diagnostics.ForbiddenMetadataNameDiagnostic; import com.github._1c_syntax.bsl.languageserver.diagnostics.MultilingualStringHasAllDeclaredLanguagesDiagnostic; import com.github._1c_syntax.bsl.languageserver.diagnostics.UnusedLocalMethodDiagnostic; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterClass; @@ -36,8 +37,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import java.util.Optional; - import static com.github._1c_syntax.bsl.languageserver.util.Assertions.assertThat; @SpringBootTest @@ -52,7 +51,7 @@ class DiagnosticInfoTest { @Test void testParameter() { - DiagnosticInfo diagnosticInfo = new DiagnosticInfo(EmptyCodeBlockDiagnostic.class, configuration, stringInterner); + var diagnosticInfo = new DiagnosticInfo(EmptyCodeBlockDiagnostic.class, configuration, stringInterner); Assertions.assertThat(diagnosticInfo.getCode()).isEqualTo(Either.forLeft("EmptyCodeBlock")); Assertions.assertThat(diagnosticInfo.getName()).isNotEmpty(); @@ -66,25 +65,25 @@ void testParameter() { Assertions.assertThat(diagnosticInfo.getScope()).isEqualTo(DiagnosticScope.ALL); Assertions.assertThat(diagnosticInfo.getMinutesToFix()).isEqualTo(5); Assertions.assertThat(diagnosticInfo.isActivatedByDefault()).isTrue(); - Assertions.assertThat(diagnosticInfo.getTags().size()).isPositive(); + Assertions.assertThat(diagnosticInfo.getTags()).isNotEmpty(); Assertions.assertThat(diagnosticInfo.getLSPTags()).isEmpty(); + Assertions.assertThat(diagnosticInfo.canLocateOnProject()).isFalse(); - Assertions.assertThat(diagnosticInfo.getDefaultConfiguration().size()).isPositive(); - + Assertions.assertThat(diagnosticInfo.getDefaultConfiguration()).isNotEmpty(); - DiagnosticParameterInfo parameter = diagnosticInfo.getParameters().get(0); + var parameter = diagnosticInfo.getParameters().get(0); assertThat(parameter.getDescription()) .isEqualTo("Считать комментарий в блоке кодом"); assertThat(parameter.getDefaultValue()).isEqualTo(false); assertThat(parameter.getType()).isEqualTo(Boolean.class); - Optional maybeParameter = diagnosticInfo.getParameter(parameter.getName()); + var maybeParameter = diagnosticInfo.getParameter(parameter.getName()); assertThat(maybeParameter) .isPresent() .hasValue(parameter); - Optional maybeFakeParameter = diagnosticInfo.getParameter("fakeParameterName"); + var maybeFakeParameter = diagnosticInfo.getParameter("fakeParameterName"); assertThat(maybeFakeParameter).isEmpty(); } @@ -102,10 +101,11 @@ void testLSPTags() { // then assertThat(diagnosticInfo.getLSPTags()).contains(DiagnosticTag.Deprecated); } + @Test void testParameterSuper() { - DiagnosticInfo diagnosticInfo = new DiagnosticInfo(MultilingualStringHasAllDeclaredLanguagesDiagnostic.class, configuration, stringInterner); + var diagnosticInfo = new DiagnosticInfo(MultilingualStringHasAllDeclaredLanguagesDiagnostic.class, configuration, stringInterner); Assertions.assertThat(diagnosticInfo.getCode()).isEqualTo(Either.forLeft("MultilingualStringHasAllDeclaredLanguages")); Assertions.assertThat(diagnosticInfo.getName()).isNotEmpty(); @@ -118,28 +118,46 @@ void testParameterSuper() { Assertions.assertThat(diagnosticInfo.getScope()).isEqualTo(DiagnosticScope.BSL); Assertions.assertThat(diagnosticInfo.getMinutesToFix()).isEqualTo(2); Assertions.assertThat(diagnosticInfo.isActivatedByDefault()).isTrue(); - Assertions.assertThat(diagnosticInfo.getTags().size()).isNotZero(); - - Assertions.assertThat(diagnosticInfo.getDefaultConfiguration().size()).isNotZero(); - Assertions.assertThat(diagnosticInfo.getParameters().size()).isEqualTo(1); + Assertions.assertThat(diagnosticInfo.getTags()).isNotEmpty(); + Assertions.assertThat(diagnosticInfo.getDefaultConfiguration()).isNotEmpty(); + Assertions.assertThat(diagnosticInfo.getParameters()).hasSize(1); + Assertions.assertThat(diagnosticInfo.canLocateOnProject()).isFalse(); - DiagnosticParameterInfo parameter = diagnosticInfo.getParameters().get(0); + var parameter = diagnosticInfo.getParameters().get(0); assertThat(parameter.getDescription()) .isEqualTo("Заявленные языки"); assertThat(parameter.getDefaultValue()).isEqualTo("ru"); assertThat(parameter.getType()).isEqualTo(String.class); - Optional maybeParameter = diagnosticInfo.getParameter(parameter.getName()); + var maybeParameter = diagnosticInfo.getParameter(parameter.getName()); assertThat(maybeParameter) .isPresent() .hasValue(parameter); - Optional maybeFakeParameter = diagnosticInfo.getParameter("fakeParameterName"); + var maybeFakeParameter = diagnosticInfo.getParameter("fakeParameterName"); assertThat(maybeFakeParameter).isEmpty(); } + @Test + void testCanLocateOnProject() { + var diagnosticInfo = new DiagnosticInfo(ForbiddenMetadataNameDiagnostic.class, configuration, stringInterner); + Assertions.assertThat(diagnosticInfo.getCode()).isEqualTo(Either.forLeft("ForbiddenMetadataName")); + Assertions.assertThat(diagnosticInfo.getName()).isNotEmpty(); + Assertions.assertThat(diagnosticInfo.getMessage()).isNotEmpty(); + Assertions.assertThat(diagnosticInfo.getType()).isEqualTo(DiagnosticType.ERROR); + Assertions.assertThat(diagnosticInfo.getSeverity()).isEqualTo(DiagnosticSeverity.BLOCKER); + Assertions.assertThat(diagnosticInfo.getLSPSeverity()).isEqualTo(org.eclipse.lsp4j.DiagnosticSeverity.Error); + Assertions.assertThat(diagnosticInfo.getCompatibilityMode()).isEqualTo(DiagnosticCompatibilityMode.UNDEFINED); + Assertions.assertThat(diagnosticInfo.getScope()).isEqualTo(DiagnosticScope.BSL); + Assertions.assertThat(diagnosticInfo.getMinutesToFix()).isEqualTo(30); + Assertions.assertThat(diagnosticInfo.isActivatedByDefault()).isTrue(); + Assertions.assertThat(diagnosticInfo.getTags()).isNotEmpty(); + Assertions.assertThat(diagnosticInfo.canLocateOnProject()).isTrue(); + Assertions.assertThat(diagnosticInfo.getExtraMinForComplexity()).isZero(); + } + @Test void testParameterEn() { @@ -147,12 +165,10 @@ void testParameterEn() { configuration.setLanguage(Language.EN); // when - DiagnosticInfo diagnosticEnInfo = new DiagnosticInfo(EmptyCodeBlockDiagnostic.class, configuration, stringInterner); + var diagnosticEnInfo = new DiagnosticInfo(EmptyCodeBlockDiagnostic.class, configuration, stringInterner); // then assertThat(diagnosticEnInfo.getParameters().get(0).getDescription()) .isEqualTo("Comment as code"); - } - -} \ No newline at end of file +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/documentlink/DiagnosticDescriptionDocumentLinkSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/documentlink/DiagnosticDescriptionDocumentLinkSupplierTest.java index 3ee82ce4c6b..a3b62fe70fe 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/documentlink/DiagnosticDescriptionDocumentLinkSupplierTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/documentlink/DiagnosticDescriptionDocumentLinkSupplierTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -25,13 +25,12 @@ 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.util.TestUtils; -import org.jetbrains.annotations.NotNull; +import jakarta.annotation.PostConstruct; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; -import javax.annotation.PostConstruct; import java.io.File; import static org.assertj.core.api.Assertions.assertThat; @@ -195,11 +194,10 @@ void testSiteRoot() { ; } - @NotNull private DocumentContext getDocumentContext() { var filePath = "./src/test/resources/documentlink/diagnosticDescriptionDocumentLinkSupplier.bsl"; var documentContext = TestUtils.getDocumentContextFromFile(filePath); documentContext.getDiagnostics(); return documentContext; } -} \ No newline at end of file +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryCommentFoldingRangeSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryCommentFoldingRangeSupplierTest.java index 2e5be8e8dbe..1629c6624cf 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryCommentFoldingRangeSupplierTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryCommentFoldingRangeSupplierTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryPackageFoldingRangeSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryPackageFoldingRangeSupplierTest.java index 3f6664d20b7..be00315429d 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryPackageFoldingRangeSupplierTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/folding/QueryPackageFoldingRangeSupplierTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatterTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatterTest.java new file mode 100644 index 00000000000..bc477aa2390 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/hover/DescriptionFormatterTest.java @@ -0,0 +1,51 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.hover; + +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +@SpringBootTest +class DescriptionFormatterTest { + + @Autowired + private DescriptionFormatter descriptionFormatter; + + @Test + void whenParameterOfMethodHasAnnotations_thenAnnotationIsAddedToParameterSignatureDescription() { + // given + var documentContext = TestUtils.getDocumentContextFromFile("./src/test/resources/hover/DescriptionFormatter.bsl"); + var methodSymbol = documentContext.getSymbolTree().getMethodSymbol("МетодСАннотациямиПараметров").orElseThrow(); + + // when + var description = descriptionFormatter.getParametersSignatureDescription(methodSymbol); + + // then + assertThat(description).isEqualTo("&Повторяемый Парам1, Парам2"); + } + +} \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/hover/MethodSymbolMarkupContentBuilderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/hover/MethodSymbolMarkupContentBuilderTest.java index b1ae194b7f3..34164e8d37f 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/hover/MethodSymbolMarkupContentBuilderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/hover/MethodSymbolMarkupContentBuilderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -25,11 +25,11 @@ import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterClass; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import com.github._1c_syntax.bsl.types.ModuleType; +import jakarta.annotation.PostConstruct; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import javax.annotation.PostConstruct; import java.nio.file.Paths; import java.util.Arrays; @@ -68,43 +68,52 @@ void testContentFromDirectFile() { var blocks = Arrays.asList(content.split("---\n?")); assertThat(blocks).hasSize(5); - assertThat(blocks.get(0)).isEqualTo("```bsl\n" + - "Функция ИмяФункции(Знач П1: Дата | Число, П2: Число = -10, П2_5, Знач П3: Структура = \"\", " + - "П4: Массив | СписокЗначений, ПДата: См. ОбщийМодуль.СуперМетод() = '20100101', ПДатаВремя = '20110101121212', " + - "П6 = Ложь, П7 = Истина, П8 = Неопределено, П9 = NULL) Экспорт: Строка | Структура\n```\n\n"); + assertThat(blocks.get(0)).isEqualTo(""" + ```bsl + Функция ИмяФункции(Знач П1: Дата | Число, П2: Число = -10, П2_5, Знач П3: Структура = "", П4: Массив | СписокЗначений, ПДата: См. ОбщийМодуль.СуперМетод() = '20100101', ПДатаВремя = '20110101121212', П6 = Ложь, П7 = Истина, П8 = Неопределено, П9 = NULL) Экспорт: Строка | Структура + ``` + + """); assertThat(blocks.get(1)).matches("\\[file://.*/src/test/resources/hover/methodSymbolMarkupContentBuilder.bsl]\\(.*src/test/resources/hover/methodSymbolMarkupContentBuilder.bsl#\\d+\\)\n\n"); assertThat(blocks.get(2)).isEqualTo("Описание функции.\nМногострочное.\n\n"); - assertThat(blocks.get(3)).isEqualTo("**Параметры:**\n\n" + - "* **П1**: `Дата` | `Число` - Описание даты/числа \n" + - "* **П2**: `Число` - Описание числа \n" + - "* **П2_5**: \n" + - "* **П3**: `Структура` - Описание строки
  продолжается на следующей строкке: \n" + - " * **Поле1**: `Число` - Описание поле1 \n" + - " * **Поле2**: `Строка` - Описание поле2 \n" + - " * **Поле3**: `Структура` : \n" + - " * **Поле31**: `строка` \n" + - " * **Поле32**: `Структура` : \n" + - " * **Поле321**: `Число` - Описание поля 321 \n" + - " * **Поле33**: `строка` \n" + - " * **Поле4**: `строка` \n" + - "* **П4**: \n" + - "  `Массив` - Описание Массива \n" + - "  `СписокЗначений` - Описание списка \n" + - "* **ПДата**: [См. ОбщийМодуль.СуперМетод()](ОбщийМодуль.СуперМетод()) \n" + - "* **ПДатаВремя**: \n" + - "* **П6**: \n" + - "* **П7**: \n" + - "* **П8**: \n" + - "* **П9**: \n" + - "\n"); - assertThat(blocks.get(4)).isEqualTo("**Возвращаемое значение:**\n\n" + - "  `Строка` - вернувшаяся строка \n" + - "  `Структура` - Описание строки
  продолжается на следующей строкке: \n" + - " * **Поле1**: `Число` - Описание поле1 \n" + - " * **Поле2**: `Строка` - Описание поле2 \n" + - " * **Поле3**: `Структура` : \n" + - " * **Поле31**: `строка` \n" + - " * **Поле32**: `Структура`\n\n"); + assertThat(blocks.get(3)).isEqualTo(""" + **Параметры:** + + * **П1**: `Дата` | `Число` - Описание даты/числа \s + * **П2**: `Число` - Описание числа \s + * **П2_5**: \s + * **П3**: `Структура` - Описание строки
  продолжается на следующей строкке: \s + * **Поле1**: `Число` - Описание поле1 \s + * **Поле2**: `Строка` - Описание поле2 \s + * **Поле3**: `Структура` : \s + * **Поле31**: `строка` \s + * **Поле32**: `Структура` : \s + * **Поле321**: `Число` - Описание поля 321 \s + * **Поле33**: `строка` \s + * **Поле4**: `строка` \s + * **П4**: \s +   `Массив` - Описание Массива \s +   `СписокЗначений` - Описание списка \s + * **ПДата**: [См. ОбщийМодуль.СуперМетод()](ОбщийМодуль.СуперМетод()) \s + * **ПДатаВремя**: \s + * **П6**: \s + * **П7**: \s + * **П8**: \s + * **П9**:\s + + """); + assertThat(blocks.get(4)).isEqualTo(""" + **Возвращаемое значение:** + +   `Строка` - вернувшаяся строка \s +   `Структура` - Описание строки
  продолжается на следующей строкке: \s + * **Поле1**: `Число` - Описание поле1 \s + * **Поле2**: `Строка` - Описание поле2 \s + * **Поле3**: `Структура` : \s + * **Поле31**: `строка` \s + * **Поле32**: `Структура` + + """); } @Test @@ -123,8 +132,12 @@ void testContentFromManagerModule() { var blocks = Arrays.asList(content.split("---\n?")); assertThat(blocks).hasSize(2); - assertThat(blocks.get(0)).isEqualTo("```bsl\n" + - "Процедура ТестЭкспортная() Экспорт\n```\n\n"); + assertThat(blocks.get(0)).isEqualTo(""" + ```bsl + Процедура ТестЭкспортная() Экспорт + ``` + + """); assertThat(blocks.get(1)).matches("\\[Catalog.Справочник1]\\(.*Catalogs/.*/Ext/ManagerModule.bsl#\\d+\\)\n\n"); } @@ -143,8 +156,12 @@ void testMethodsFromCommonModule() { var blocks = Arrays.asList(content.split("---\n?")); assertThat(blocks).hasSize(3); - assertThat(blocks.get(0)).isEqualTo("```bsl\n" + - "Процедура УстаревшаяПроцедура() Экспорт\n```\n\n"); + assertThat(blocks.get(0)).isEqualTo(""" + ```bsl + Процедура УстаревшаяПроцедура() Экспорт + ``` + + """); assertThat(blocks.get(1)).matches("\\[CommonModule.ПервыйОбщийМодуль]\\(.*CommonModules/.*/Ext/Module.bsl#\\d+\\)\n\n"); assertThat(blocks.get(2)).isEqualTo("Процедура - Устаревшая процедура\n\n"); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/hover/VariableSymbolMarkupContentBuilderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/hover/VariableSymbolMarkupContentBuilderTest.java index f1d70479a97..a17f96ef9bd 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/hover/VariableSymbolMarkupContentBuilderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/hover/VariableSymbolMarkupContentBuilderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -25,11 +25,11 @@ import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterClass; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import com.github._1c_syntax.bsl.types.ModuleType; +import jakarta.annotation.PostConstruct; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import javax.annotation.PostConstruct; import java.nio.file.Paths; import java.util.Arrays; @@ -69,12 +69,16 @@ void testFileVarContentFromDirectFile_NoComments() { var blocks = Arrays.asList(content.split("---\n?")); assertThat(blocks).hasSize(2); - assertThat(blocks.get(0)).isEqualTo("```bsl\n" + - "Перем ИмяБезОписания\n" + - "```\n" + - "\n"); - assertThat(blocks.get(1)).matches("\\[file://.*/src/test/resources/hover/variableSymbolMarkupContentBuilder.bsl]\\(.*src/test/resources/hover/variableSymbolMarkupContentBuilder.bsl#\\d+\\)\n" + - "\n"); + assertThat(blocks.get(0)).isEqualTo(""" + ```bsl + Перем ИмяБезОписания + ``` + + """); + assertThat(blocks.get(1)).matches(""" + \\[file://.*/src/test/resources/hover/variableSymbolMarkupContentBuilder.bsl]\\(.*src/test/resources/hover/variableSymbolMarkupContentBuilder.bsl#\\d+\\) + + """); } @Test @@ -92,14 +96,20 @@ void testFileVarContentFromDirectFile_OneCommentsStringFromRight() { var blocks = Arrays.asList(content.split("---\n?")); assertThat(blocks).hasSize(3); - assertThat(blocks.get(0)).isEqualTo("```bsl\n" + - "Перем Имя_ОписаниеСправаОднойСтрокой\n" + - "```\n" + - "\n"); - assertThat(blocks.get(1)).matches("\\[file://.*/src/test/resources/hover/variableSymbolMarkupContentBuilder.bsl]\\(.*src/test/resources/hover/variableSymbolMarkupContentBuilder.bsl#\\d+\\)\n" + - "\n"); - assertThat(blocks.get(2)).matches("описание\n" + - "\n"); + assertThat(blocks.get(0)).isEqualTo(""" + ```bsl + Перем Имя_ОписаниеСправаОднойСтрокой + ``` + + """); + assertThat(blocks.get(1)).matches(""" + \\[file://.*/src/test/resources/hover/variableSymbolMarkupContentBuilder.bsl]\\(.*src/test/resources/hover/variableSymbolMarkupContentBuilder.bsl#\\d+\\) + + """); + assertThat(blocks.get(2)).matches(""" + описание + + """); } @Test @@ -118,15 +128,22 @@ void testMethodVarContentFromDirectFile_2_comments_strings() { var blocks = Arrays.asList(content.split("---\n?")); assertThat(blocks).hasSize(3); - assertThat(blocks.get(0)).isEqualTo("```bsl\n" + - "Перем Имя_ОписаниеСверхуДвеСтроки_Функция\n" + - "```\n" + - "\n"); - assertThat(blocks.get(1)).matches("\\[file://.*/src/test/resources/hover/variableSymbolMarkupContentBuilder.bsl.ИмяФункции]\\(.*src/test/resources/hover/variableSymbolMarkupContentBuilder.bsl#\\d+\\)\n" + - "\n"); + assertThat(blocks.get(0)).isEqualTo(""" + ```bsl + Перем Имя_ОписаниеСверхуДвеСтроки_Функция + ``` + + """); + assertThat(blocks.get(1)).matches(""" + \\[file://.*/src/test/resources/hover/variableSymbolMarkupContentBuilder.bsl.ИмяФункции]\\(.*src/test/resources/hover/variableSymbolMarkupContentBuilder.bsl#\\d+\\) + + """); // TODO баг - нет \n для многострочного описания переменной - assertThat(blocks.get(2)).matches("описание 1 строка\n2 строка\n" + - "\n"); + assertThat(blocks.get(2)).matches(""" + описание 1 строка + 2 строка + + """); } @Test @@ -145,14 +162,21 @@ void testMethodVarContentFromDirectFile_3_comments_strings() { var blocks = Arrays.asList(content.split("---\n?")); assertThat(blocks).hasSize(3); - assertThat(blocks.get(0)).isEqualTo("```bsl\n" + - "Перем Имя_ОписаниеСверхуТриСтрокиПоследняяПустая_Функция\n" + - "```\n" + - "\n"); - assertThat(blocks.get(1)).matches("\\[file://.*/src/test/resources/hover/variableSymbolMarkupContentBuilder.bsl.ИмяФункции]\\(.*src/test/resources/hover/variableSymbolMarkupContentBuilder.bsl#\\d+\\)\n" + - "\n"); - assertThat(blocks.get(2)).matches("описание 1 строка\n2 строка\n" + - "\n"); + assertThat(blocks.get(0)).isEqualTo(""" + ```bsl + Перем Имя_ОписаниеСверхуТриСтрокиПоследняяПустая_Функция + ``` + + """); + assertThat(blocks.get(1)).matches(""" + \\[file://.*/src/test/resources/hover/variableSymbolMarkupContentBuilder.bsl.ИмяФункции]\\(.*src/test/resources/hover/variableSymbolMarkupContentBuilder.bsl#\\d+\\) + + """); + assertThat(blocks.get(2)).matches(""" + описание 1 строка + 2 строка + + """); } @Test @@ -172,8 +196,12 @@ void testContentFromObjectModule() { var blocks = Arrays.asList(content.split("---\n?")); assertThat(blocks).hasSize(2); - assertThat(blocks.get(0)).isEqualTo("```bsl\n" + - "Перем ВалютаУчета\n```\n\n"); + assertThat(blocks.get(0)).isEqualTo(""" + ```bsl + Перем ВалютаУчета + ``` + + """); assertThat(blocks.get(1)).matches("\\[Catalog.Справочник1]\\(.*Catalogs/.*/Ext/ObjectModule.bsl#\\d+\\)\n\n"); } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/CognitiveComplexityInlayHintSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/CognitiveComplexityInlayHintSupplierTest.java new file mode 100644 index 00000000000..374cfb39cc6 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/CognitiveComplexityInlayHintSupplierTest.java @@ -0,0 +1,84 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.inlayhints; + +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import org.eclipse.lsp4j.InlayHint; +import org.eclipse.lsp4j.InlayHintKind; +import org.eclipse.lsp4j.InlayHintParams; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@CleanupContextBeforeClassAndAfterEachTestMethod +class CognitiveComplexityInlayHintSupplierTest { + + private final static String FILE_PATH = "./src/test/resources/inlayhints/CognitiveComplexityInlayHintSupplier.bsl"; + + @Autowired + private CognitiveComplexityInlayHintSupplier supplier; + + @Test + void testGetInlayHints() { + + // given + var documentContext = TestUtils.getDocumentContextFromFile(FILE_PATH); + MethodSymbol firstMethod = documentContext.getSymbolTree().getMethods().get(0); + var methodName = firstMethod.getName(); + + var textDocumentIdentifier = TestUtils.getTextDocumentIdentifier(documentContext.getUri()); + var range = Ranges.create(); + var params = new InlayHintParams(textDocumentIdentifier, range); + + // when + List inlayHints = supplier.getInlayHints(documentContext, params); + + // then + assertThat(inlayHints).isEmpty(); + + // when + supplier.toggleHints(documentContext.getUri(), methodName); + inlayHints = supplier.getInlayHints(documentContext, params); + + // then + assertThat(inlayHints) + .hasSize(1) + .anySatisfy(inlayHint -> { + assertThat(inlayHint.getLabel()).isEqualTo(Either.forLeft("+1")); + assertThat(inlayHint.getKind()).isEqualTo(InlayHintKind.Parameter); + assertThat(inlayHint.getPosition()).isEqualTo(new Position(1, 4)); + assertThat(inlayHint.getPaddingRight()).isTrue(); + assertThat(inlayHint.getPaddingLeft()).isNull(); + }); + } + +} \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/CyclomaticComplexityInlayHintSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/CyclomaticComplexityInlayHintSupplierTest.java new file mode 100644 index 00000000000..388825cddf2 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/CyclomaticComplexityInlayHintSupplierTest.java @@ -0,0 +1,92 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.inlayhints; + +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import org.eclipse.lsp4j.InlayHint; +import org.eclipse.lsp4j.InlayHintKind; +import org.eclipse.lsp4j.InlayHintParams; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@CleanupContextBeforeClassAndAfterEachTestMethod +class CyclomaticComplexityInlayHintSupplierTest { + + private final static String FILE_PATH = "./src/test/resources/inlayhints/CyclomaticComplexityInlayHintSupplier.bsl"; + + @Autowired + private CyclomaticComplexityInlayHintSupplier supplier; + + @Test + void testGetInlayHints() { + + // given + var documentContext = TestUtils.getDocumentContextFromFile(FILE_PATH); + MethodSymbol firstMethod = documentContext.getSymbolTree().getMethods().get(0); + var methodName = firstMethod.getName(); + + var textDocumentIdentifier = TestUtils.getTextDocumentIdentifier(documentContext.getUri()); + var range = Ranges.create(); + var params = new InlayHintParams(textDocumentIdentifier, range); + + // when + List inlayHints = supplier.getInlayHints(documentContext, params); + + // then + assertThat(inlayHints).isEmpty(); + + // when + supplier.toggleHints(documentContext.getUri(), methodName); + inlayHints = supplier.getInlayHints(documentContext, params); + + // then + assertThat(inlayHints) + .hasSize(2) + .anySatisfy(inlayHint -> { + assertThat(inlayHint.getLabel()).isEqualTo(Either.forLeft("+1")); + assertThat(inlayHint.getKind()).isEqualTo(InlayHintKind.Parameter); + assertThat(inlayHint.getPosition()).isEqualTo(new Position(1, 4)); + assertThat(inlayHint.getPaddingRight()).isTrue(); + assertThat(inlayHint.getPaddingLeft()).isNull(); + }) + .anySatisfy(inlayHint -> { + assertThat(inlayHint.getLabel()).isEqualTo(Either.forLeft("+1")); + assertThat(inlayHint.getKind()).isEqualTo(InlayHintKind.Parameter); + assertThat(inlayHint.getPosition()).isEqualTo(new Position(0, 10)); + assertThat(inlayHint.getPaddingRight()).isTrue(); + assertThat(inlayHint.getPaddingLeft()).isNull(); + }) + ; + } + +} \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/SourceDefinedMethodCallInlayHintSupplierTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/SourceDefinedMethodCallInlayHintSupplierTest.java new file mode 100644 index 00000000000..12790013dde --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/inlayhints/SourceDefinedMethodCallInlayHintSupplierTest.java @@ -0,0 +1,140 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.inlayhints; + +import com.github._1c_syntax.bsl.languageserver.configuration.LanguageServerConfiguration; +import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; +import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import org.eclipse.lsp4j.InlayHint; +import org.eclipse.lsp4j.InlayHintKind; +import org.eclipse.lsp4j.InlayHintParams; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@CleanupContextBeforeClassAndAfterEachTestMethod +class SourceDefinedMethodCallInlayHintSupplierTest { + + private final static String FILE_PATH = "./src/test/resources/inlayhints/SourceDefinedMethodCallInlayHintSupplier.bsl"; + + @Autowired + private SourceDefinedMethodCallInlayHintSupplier supplier; + + @Autowired + private LanguageServerConfiguration configuration; + + @Test + void testDefaultInlayHints() { + + // given + var documentContext = TestUtils.getDocumentContextFromFile(FILE_PATH); + MethodSymbol firstMethod = documentContext.getSymbolTree().getMethods().get(0); + + var textDocumentIdentifier = TestUtils.getTextDocumentIdentifier(documentContext.getUri()); + var range = firstMethod.getRange(); + var params = new InlayHintParams(textDocumentIdentifier, range); + + // when + List inlayHints = supplier.getInlayHints(documentContext, params); + + // then + assertThat(inlayHints) + .hasSize(2) + .anySatisfy(inlayHint -> { + assertThat(inlayHint.getLabel()).isEqualTo(Either.forLeft("PlayersHealth:")); + assertThat(inlayHint.getKind()).isEqualTo(InlayHintKind.Parameter); + assertThat(inlayHint.getPosition()).isEqualTo(new Position(3, 23)); + assertThat(inlayHint.getPaddingRight()).isTrue(); + assertThat(inlayHint.getPaddingLeft()).isNull(); + assertThat(inlayHint.getTooltip().getRight().getValue()).isEqualTo("* **PlayersHealth**: "); + }) + .anySatisfy(inlayHint -> { + assertThat(inlayHint.getLabel()).isEqualTo(Either.forLeft("Amount:")); + assertThat(inlayHint.getKind()).isEqualTo(InlayHintKind.Parameter); + assertThat(inlayHint.getPosition()).isEqualTo(new Position(3, 32)); + assertThat(inlayHint.getPaddingRight()).isTrue(); + assertThat(inlayHint.getPaddingLeft()).isNull(); + assertThat(inlayHint.getTooltip().getRight().getValue()).isEqualTo("* **Amount**: "); + }) + ; + } + + @Test + void testInlayHintsShowParametersWithTheSameName() { + + // given + configuration.getInlayHintOptions().getParameters().put( + supplier.getId(), + Either.forRight(Map.of("showParametersWithTheSameName", true)) + ); + + var documentContext = TestUtils.getDocumentContextFromFile(FILE_PATH); + MethodSymbol firstMethod = documentContext.getSymbolTree().getMethods().get(0); + + var textDocumentIdentifier = TestUtils.getTextDocumentIdentifier(documentContext.getUri()); + var range = firstMethod.getRange(); + var params = new InlayHintParams(textDocumentIdentifier, range); + + // when + List inlayHints = supplier.getInlayHints(documentContext, params); + + // then + assertThat(inlayHints) + .hasSize(3) + .anySatisfy(inlayHint -> { + assertThat(inlayHint.getLabel()).isEqualTo(Either.forLeft("Player:")); + assertThat(inlayHint.getKind()).isEqualTo(InlayHintKind.Parameter); + assertThat(inlayHint.getPosition()).isEqualTo(new Position(3, 14)); + assertThat(inlayHint.getPaddingRight()).isTrue(); + assertThat(inlayHint.getPaddingLeft()).isNull(); + assertThat(inlayHint.getTooltip().getRight().getValue()).isEqualTo("* **Player**: "); + }) + .anySatisfy(inlayHint -> { + assertThat(inlayHint.getLabel()).isEqualTo(Either.forLeft("PlayersHealth:")); + assertThat(inlayHint.getKind()).isEqualTo(InlayHintKind.Parameter); + assertThat(inlayHint.getPosition()).isEqualTo(new Position(3, 23)); + assertThat(inlayHint.getPaddingRight()).isTrue(); + assertThat(inlayHint.getPaddingLeft()).isNull(); + assertThat(inlayHint.getTooltip().getRight().getValue()).isEqualTo("* **PlayersHealth**: "); + }) + .anySatisfy(inlayHint -> { + assertThat(inlayHint.getLabel()).isEqualTo(Either.forLeft("Amount:")); + assertThat(inlayHint.getKind()).isEqualTo(InlayHintKind.Parameter); + assertThat(inlayHint.getPosition()).isEqualTo(new Position(3, 32)); + assertThat(inlayHint.getPaddingRight()).isTrue(); + assertThat(inlayHint.getPaddingLeft()).isNull(); + assertThat(inlayHint.getTooltip().getRight().getValue()).isEqualTo("* **Amount**: "); + }) + ; + } + + +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CallHierarchyProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CallHierarchyProviderTest.java index 32c9e026f62..bdaa449c1b9 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CallHierarchyProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CallHierarchyProviderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -52,7 +52,7 @@ class CallHierarchyProviderTest { private final Position firstProcedureDeclarationPosition = new Position(0, 15); private final Position firstFunctionCallPosition = new Position(1, 15); - private final Position secondFunctionDeclarationPosition = new Position(14, 15); + private final Position secondFunctionDeclarationPosition = new Position(16, 15); private final Position secondFunctionCallPosition = new Position(2, 15); @BeforeEach diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeActionProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeActionProviderTest.java index 0bcdea55c55..702c9942d2f 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeActionProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeActionProviderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,6 +28,7 @@ import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import com.github._1c_syntax.utils.StringInterner; +import edu.umd.cs.findbugs.annotations.Nullable; import org.eclipse.lsp4j.CodeAction; import org.eclipse.lsp4j.CodeActionContext; import org.eclipse.lsp4j.CodeActionKind; @@ -42,7 +43,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import javax.annotation.CheckForNull; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -167,7 +167,7 @@ void testOnly() { ; } - private static boolean toBoolean(@CheckForNull Boolean value) { + private static boolean toBoolean(@Nullable Boolean value) { if (value == null) { return false; } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeLensProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeLensProviderTest.java index 66969c9db22..6550f774636 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeLensProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CodeLensProviderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/ColorProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/ColorProviderTest.java index e6090bde704..0f9d1de563e 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/ColorProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/ColorProviderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CommandProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CommandProviderTest.java new file mode 100644 index 00000000000..1a869ef1e23 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/CommandProviderTest.java @@ -0,0 +1,104 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.providers; + +import com.github._1c_syntax.bsl.languageserver.commands.CommandSupplier; +import com.github._1c_syntax.bsl.languageserver.commands.DefaultCommandArguments; +import org.eclipse.lsp4j.ExecuteCommandParams; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; + +import java.net.URI; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +class CommandProviderTest { + + @Autowired + private CommandProvider commandProvider; + + @Test + void commandsIdsContainsTestCommand() { + // given + // TestCommandSupplier test component. + + // when + var commandIds = commandProvider.getCommandIds(); + + // then + assertThat(commandIds).contains("test"); + } + + @Test + void executeCommandArgumentsExtractedCorrectly() { + // given + var rawCommandArguments = "{ \"id\": \"test\", \"uri\": \"someUri\"}"; + var params = new ExecuteCommandParams("Some command", List.of(rawCommandArguments)); + + // when + var commandArguments = commandProvider.extractArguments(params); + + // then + assertThat(commandArguments) + .isOfAnyClassIn(DefaultCommandArguments.class) + ; + } + + @Test + void commandExecutesCorrectly() { + // given + var commandArguments = new DefaultCommandArguments(URI.create("fake:///fake-uri"), "test"); + + // when + var result = commandProvider.executeCommand(commandArguments); + + // then + assertThat(result) + .isEqualTo(1); + } + + @TestConfiguration + static class Configuration { + @Bean + CommandSupplier commandSupplier() { + return new TestCommandSupplier(); + } + } + + static class TestCommandSupplier implements CommandSupplier { + @Override + public Class getCommandArgumentsClass() { + return DefaultCommandArguments.class; + } + + @Override + public Optional execute(DefaultCommandArguments arguments) { + return Optional.of(1); + } + } +} \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DefinitionProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DefinitionProviderTest.java index 78acc9ffac9..d7c3dd7da16 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DefinitionProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DefinitionProviderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -26,13 +26,13 @@ import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import com.github._1c_syntax.bsl.types.ModuleType; +import jakarta.annotation.PostConstruct; import org.eclipse.lsp4j.DefinitionParams; import org.eclipse.lsp4j.Position; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import javax.annotation.PostConstruct; import java.nio.file.Paths; import static com.github._1c_syntax.bsl.languageserver.util.TestUtils.PATH_TO_METADATA; @@ -76,7 +76,7 @@ void testDefinitionOfLocalMethod() { var methodSymbol = documentContext.getSymbolTree().getMethodSymbol("ИмяФункции").orElseThrow(); var params = new DefinitionParams(); - params.setPosition(new Position(4, 10)); + params.setPosition(new Position(4, 9)); // when var definitions = definitionProvider.getDefinition(documentContext, params); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProviderTest.java index 10321f4719c..2e17100eb9f 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProviderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProviderTest.java index 8e407ca161e..e1ed337d54a 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentLinkProviderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProviderTest.java index 2189ca791d1..50f8795a26c 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DocumentSymbolProviderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/FoldingRangeProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/FoldingRangeProviderTest.java index c64b8a99fd5..1fbf905b63a 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/FoldingRangeProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/FoldingRangeProviderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,7 +21,6 @@ */ package com.github._1c_syntax.bsl.languageserver.providers; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import org.eclipse.lsp4j.FoldingRange; import org.eclipse.lsp4j.FoldingRangeKind; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/FormatProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/FormatProviderTest.java index ccebed2abca..ba614f1aed9 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/FormatProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/FormatProviderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -31,7 +31,6 @@ import org.eclipse.lsp4j.DocumentRangeFormattingParams; import org.eclipse.lsp4j.FormattingOptions; import org.eclipse.lsp4j.TextDocumentIdentifier; -import org.eclipse.lsp4j.TextDocumentItem; import org.eclipse.lsp4j.TextEdit; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -216,7 +215,7 @@ void testFormatEngKeywords() throws IOException { URI.create(params.getTextDocument().getUri()), fileContent ); - + var configuration = new LanguageServerConfiguration(); configuration.setLanguage(Language.EN); documentContext.setConfiguration(configuration); @@ -276,8 +275,6 @@ void testFormatUnaryMinus() { // then assertThat(textEdits).hasSize(1); - - TextEdit textEdit = textEdits.get(0); assertThat(textEdits.get(0).getNewText()).isEqualTo("Возврат -1 > -2"); } @@ -290,16 +287,8 @@ private File getFormattedTestFile() { return new File("./src/test/resources/providers/format_formatted.bsl"); } - private TextDocumentItem getTextDocumentItem() throws IOException { - File file = getTestFile(); - String uri = file.toURI().toString(); - - String fileContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8); - - return new TextDocumentItem(uri, "bsl", 1, fileContent); - } - private TextDocumentIdentifier getTextDocumentIdentifier() { + // TODO: Переделать на TestUtils.getTextDocumentIdentifier(); File file = getTestFile(); String uri = file.toURI().toString(); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/HoverProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/HoverProviderTest.java index fd924c1d53a..0a7c417135d 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/HoverProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/HoverProviderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,7 +21,6 @@ */ package com.github._1c_syntax.bsl.languageserver.providers; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import org.eclipse.lsp4j.Hover; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/InlayHintProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/InlayHintProviderTest.java new file mode 100644 index 00000000000..b69640f69a7 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/InlayHintProviderTest.java @@ -0,0 +1,136 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.providers; + +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.inlayhints.CognitiveComplexityInlayHintSupplier; +import com.github._1c_syntax.bsl.languageserver.inlayhints.InlayHintSupplier; +import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import org.eclipse.lsp4j.InlayHint; +import org.eclipse.lsp4j.InlayHintParams; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@CleanupContextBeforeClassAndAfterEachTestMethod +class InlayHintProviderTest { + + @Autowired + private InlayHintProvider provider; + @Autowired + private LanguageServerConfiguration configuration; + @Autowired + private CognitiveComplexityInlayHintSupplier supplier; + @Autowired + @Qualifier("enabledInlayHintSuppliers") + private ObjectProvider> enabledInlayHintSuppliersProvider; + + private DocumentContext documentContext; + + @BeforeEach + void init() { + String filePath = "./src/test/resources/providers/inlayHints.bsl"; + documentContext = TestUtils.getDocumentContextFromFile(filePath); + } + + @Test + void getInlayHint() { + + // given + var params = new InlayHintParams(); + params.setTextDocument(new TextDocumentIdentifier(documentContext.getUri().toString())); + params.setRange(Ranges.create(documentContext.getAst())); + + // when + var inlayHints = provider.getInlayHint(documentContext, params); + + // then + assertThat(inlayHints) + .contains(getTestHint()); + } + + @Test + void testDefaultEnabledSuppliers() { + + // given + // default config + + // when + List suppliers = enabledInlayHintSuppliersProvider.getObject(); + + // then + assertThat(suppliers).contains(supplier); + } + + @Test + void testDisabledSupplierIsNotEnabled() { + + // given + configuration.getInlayHintOptions().getParameters().put(supplier.getId(), Either.forLeft(false)); + + // when + List suppliers = enabledInlayHintSuppliersProvider.getObject(); + + // then + assertThat(suppliers) + .isNotEmpty() + .doesNotContain(supplier); + + } + + private static InlayHint getTestHint() { + return new InlayHint(new Position(0, 0), Either.forLeft("test hint")); + } + + @TestConfiguration + static class Configuration { + @Bean + InlayHintSupplier inlayHintSupplier() { + return new TestInlayHintSupplier(); + } + } + + static class TestInlayHintSupplier implements InlayHintSupplier { + @Override + public List getInlayHints(DocumentContext documentContext, InlayHintParams params) { + var inlayHint = getTestHint(); + return List.of(inlayHint); + } + } + +} diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/ReferencesProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/ReferencesProviderTest.java index 008203f974d..9b6f1878284 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/ReferencesProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/ReferencesProviderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -26,6 +26,7 @@ import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import com.github._1c_syntax.bsl.types.ModuleType; +import jakarta.annotation.PostConstruct; import org.eclipse.lsp4j.Location; import org.eclipse.lsp4j.Position; import org.eclipse.lsp4j.ReferenceParams; @@ -33,7 +34,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import javax.annotation.PostConstruct; import java.nio.file.Paths; import static com.github._1c_syntax.bsl.languageserver.util.TestUtils.PATH_TO_METADATA; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/RenameProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/RenameProviderTest.java index 94b7258a48f..eba1e36f009 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/RenameProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/RenameProviderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -25,6 +25,7 @@ import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterClass; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import jakarta.annotation.PostConstruct; import org.eclipse.lsp4j.Position; import org.eclipse.lsp4j.PrepareRenameParams; import org.eclipse.lsp4j.RenameParams; @@ -33,7 +34,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import javax.annotation.PostConstruct; import java.nio.file.Paths; import static com.github._1c_syntax.bsl.languageserver.util.TestUtils.PATH_TO_METADATA; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/SelectionRangeProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/SelectionRangeProviderTest.java index 59c96fc8949..3c99350ad84 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/SelectionRangeProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/SelectionRangeProviderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -71,7 +71,7 @@ void testGlobalMethodCallCapturesSemicolon() { @Test void testStatementCapturesStatementBlockAfterStatement() { // given - var params = selection(4, 20); + var params = selection(4, 19); // when var selectionRanges = provider.getSelectionRange(documentContext, params); @@ -89,7 +89,7 @@ void testStatementCapturesStatementBlockAfterStatement() { @Test void testStatementCapturesStatementBlockBeforeStatement() { // given - var params = selection(6, 20); + var params = selection(6, 19); // when var selectionRanges = provider.getSelectionRange(documentContext, params); @@ -107,7 +107,7 @@ void testStatementCapturesStatementBlockBeforeStatement() { @Test void testStatementCapturesStatementBlockAroundStatement() { // given - var params = selection(5, 20); + var params = selection(5, 19); // when var selectionRanges = provider.getSelectionRange(documentContext, params); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/SymbolProviderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/SymbolProviderTest.java index e04342dbaa2..d634c1f96ad 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/SymbolProviderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/SymbolProviderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/CamelCaseDetectorTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/CamelCaseDetectorTest.java index a2906680d25..af586795aa0 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/CamelCaseDetectorTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/CamelCaseDetectorTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/ContainsDetectorTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/ContainsDetectorTest.java index 2267d4b0586..aa3d023db75 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/ContainsDetectorTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/ContainsDetectorTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/EndWithDetectorTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/EndWithDetectorTest.java index 16f6d7898ac..521e251d646 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/EndWithDetectorTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/EndWithDetectorTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/KeywordsDetectorTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/KeywordsDetectorTest.java index c93bb997684..5aa1bb8b6d6 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/KeywordsDetectorTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/KeywordsDetectorTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/PatternDetectorTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/PatternDetectorTest.java index 7e4e30bd7ec..06ece48ef95 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/PatternDetectorTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/recognizer/PatternDetectorTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/AnnotationReferenceFinderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/AnnotationReferenceFinderTest.java new file mode 100644 index 00000000000..ec60725616b --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/AnnotationReferenceFinderTest.java @@ -0,0 +1,153 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.references; + +import com.github._1c_syntax.bsl.languageserver.context.AbstractServerContextAwareTest; +import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterClass; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.SymbolKind; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@CleanupContextBeforeClassAndAfterClass +class AnnotationReferenceFinderTest extends AbstractServerContextAwareTest { + + @Autowired + private AnnotationReferenceFinder referenceFinder; + + @Test + void findReferenceOfAnnotation() { + // given + initServerContext("./src/test/resources/references/annotations"); + var documentContext = TestUtils.getDocumentContextFromFile("./src/test/resources/references/AnnotationReferenceFinder.os"); + + var module = documentContext.getSymbolTree().getModule(); + + // when + var optionalReference = referenceFinder.findReference(documentContext.getUri(), new Position(0, 2)); + + // then + assertThat(optionalReference) + .isPresent() + .hasValueSatisfying(reference -> assertThat(reference.getFrom()).isEqualTo(module)) + .hasValueSatisfying(reference -> assertThat(reference.getSymbol().getName()).isEqualTo("ТестоваяАннотация")) + .hasValueSatisfying(reference -> assertThat(reference.getSymbol().getSymbolKind()).isEqualTo(SymbolKind.Interface)) + .hasValueSatisfying(reference -> assertThat(reference.getSelectionRange()).isEqualTo(Ranges.create(0, 0, 76))) + .hasValueSatisfying(reference -> assertThat(reference.getSourceDefinedSymbol().orElseThrow().getSelectionRange()).isEqualTo(Ranges.create(7, 10, 28))) + ; + } + + @Test + void findReferenceOfAnnotationParameterName() { + // given + initServerContext("./src/test/resources/references/annotations"); + var documentContext = TestUtils.getDocumentContextFromFile("./src/test/resources/references/AnnotationReferenceFinder.os"); + + var module = documentContext.getSymbolTree().getModule(); + + // when + var optionalReference = referenceFinder.findReference(documentContext.getUri(), new Position(0, 25)); + + // then + assertThat(optionalReference) + .isPresent() + .hasValueSatisfying(reference -> assertThat(reference.getFrom()).isEqualTo(module)) + .hasValueSatisfying(reference -> assertThat(reference.getSymbol().getName()).isEqualTo("ВторойПараметр")) + .hasValueSatisfying(reference -> assertThat(reference.getSymbol().getSymbolKind()).isEqualTo(SymbolKind.TypeParameter)) + .hasValueSatisfying(reference -> assertThat(reference.getSelectionRange()).isEqualTo(Ranges.create(0, 19, 33))) + .hasValueSatisfying(reference -> assertThat(reference.getSourceDefinedSymbol().orElseThrow().getSelectionRange()).isEqualTo(Ranges.create(7, 10, 28))) + ; + } + + @Test + void findReferenceOfAnnotationParameterValue() { + // given + initServerContext("./src/test/resources/references/annotations"); + var documentContext = TestUtils.getDocumentContextFromFile("./src/test/resources/references/AnnotationReferenceFinder.os"); + + var module = documentContext.getSymbolTree().getModule(); + + // when + var optionalReference = referenceFinder.findReference(documentContext.getUri(), new Position(0, 60)); + + // then + assertThat(optionalReference) + .isPresent() + .hasValueSatisfying(reference -> assertThat(reference.getFrom()).isEqualTo(module)) + .hasValueSatisfying(reference -> assertThat(reference.getSymbol().getName()).isEqualTo("Значение")) + .hasValueSatisfying(reference -> assertThat(reference.getSymbol().getSymbolKind()).isEqualTo(SymbolKind.TypeParameter)) + .hasValueSatisfying(reference -> assertThat(reference.getSelectionRange()).isEqualTo(Ranges.create(0, 56, 75))) + .hasValueSatisfying(reference -> assertThat(reference.getSourceDefinedSymbol().orElseThrow().getSelectionRange()).isEqualTo(Ranges.create(7, 10, 28))) + ; + } + + @ParameterizedTest + @CsvSource(textBlock = """ + 6, 24, 6, 19, 6, 27 + 8, 10, 8, 4, 9, 12 + 9, 10, 8, 4, 9, 12 + 11, 19, 11, 19, 11, 21 + 12, 19, 12, 19, 12, 22 + 13, 19, 13, 19, 13, 25 + 14, 19, 14, 19, 14, 29 + 15, 19, 15, 19, 15, 31 + 16, 19, 16, 19, 16, 23 + 18, 4, 18, 4, 18, 6 + 19, 4, 19, 4, 19, 7 + 20, 4, 20, 4, 20, 12 + 21, 4, 21, 4, 22, 12 + 22, 4, 21, 4, 22, 12 + 23, 4, 23, 4, 23, 10 + 24, 4, 24, 4, 24, 14 + 25, 4, 25, 4, 25, 16 + 26, 4, 26, 4, 26, 8 + """ + ) + void findReferenceOfAnnotationParameterValue_allLiterals(int positionLine, int positionCharacter, int selectionRangeStartLine, int selectionRangeStartCharacter, int selectionRangeEndLine, int selectionRangeEndCharacter) { + // given + initServerContext("./src/test/resources/references/annotations"); + var documentContext = TestUtils.getDocumentContextFromFile("./src/test/resources/references/AnnotationReferenceFinder.os"); + + var module = documentContext.getSymbolTree().getModule(); + + // when + var optionalReference = referenceFinder.findReference(documentContext.getUri(), new Position(positionLine, positionCharacter)); + + // then + assertThat(optionalReference) + .isPresent() + .hasValueSatisfying(reference -> assertThat(reference.getFrom()).isEqualTo(module)) + .hasValueSatisfying(reference -> assertThat(reference.getSymbol().getName()).isEqualTo("Значение")) + .hasValueSatisfying(reference -> assertThat(reference.getSymbol().getSymbolKind()).isEqualTo(SymbolKind.TypeParameter)) + .hasValueSatisfying(reference -> assertThat(reference.getSelectionRange()).isEqualTo(Ranges.create(selectionRangeStartLine, selectionRangeStartCharacter, selectionRangeEndLine, selectionRangeEndCharacter))) + .hasValueSatisfying(reference -> assertThat(reference.getSourceDefinedSymbol().orElseThrow().getSelectionRange()).isEqualTo(Ranges.create(7, 10, 28))) + ; + } +} \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexFillerTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexFillerTest.java index 0652d6bf8fd..cda194d139b 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexFillerTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexFillerTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -203,7 +203,7 @@ void testFindVariablesRangesCallStatement() { var referencedSymbol = referenceIndex.getReference( documentContext.getUri(), - new Position(33, 10) + new Position(33, 9) ); assertThat(referencedSymbol).isPresent(); assertThat(referencedSymbol).get() diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexReferenceFinderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexReferenceFinderTest.java index cb082fc7c7e..1926b043659 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexReferenceFinderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexReferenceFinderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,14 +28,14 @@ import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import com.github._1c_syntax.bsl.types.ModuleType; +import jakarta.annotation.PostConstruct; import org.eclipse.lsp4j.Location; import org.eclipse.lsp4j.Position; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; -import javax.annotation.PostConstruct; import java.nio.file.Paths; import java.util.Optional; @@ -54,7 +54,7 @@ class ReferenceIndexReferenceFinderTest { @Autowired private ServerContext serverContext; - @SpyBean + @MockitoSpyBean private ReferenceIndex referenceIndex; private static final String PATH_TO_FILE = "./src/test/resources/references/ReferenceIndexReferenceFinder.bsl"; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexTest.java index ef2880eb1ab..217cec0fe37 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceIndexTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -27,6 +27,7 @@ import com.github._1c_syntax.bsl.languageserver.util.TestUtils; import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import com.github._1c_syntax.bsl.types.ModuleType; +import jakarta.annotation.PostConstruct; import org.eclipse.lsp4j.Location; import org.eclipse.lsp4j.Position; import org.eclipse.lsp4j.SymbolKind; @@ -35,7 +36,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; -import javax.annotation.PostConstruct; import java.nio.file.Paths; import java.util.stream.Collectors; @@ -82,7 +82,9 @@ void getReferencesToLocalMethod() { @Test void getReferencesToLocalMethodFromFormModule() { // given - var documentContext = serverContext.getDocument("Catalog.Справочник1.Form.ФормаСписка", ModuleType.FormModule).orElseThrow(); + var documentContext = serverContext + .getDocument("Catalog.Справочник1.Form.ФормаСписка", ModuleType.FormModule) + .orElseThrow(); var method = documentContext.getSymbolTree().getMethodSymbol("ЛокальнаяПроцедура").orElseThrow(); var module = documentContext.getSymbolTree().getModule(); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceResolverTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceResolverTest.java index 80746a21b75..003dc5343a5 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceResolverTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/ReferenceResolverTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -90,8 +90,7 @@ ReferenceResolver referenceResolver( ReferenceFinder zeroLineReferenceFinder, ReferenceFinder firstLineReferenceFinder ) { - var referenceResolver = new ReferenceResolver(List.of(zeroLineReferenceFinder, firstLineReferenceFinder)); - return referenceResolver; + return new ReferenceResolver(List.of(zeroLineReferenceFinder, firstLineReferenceFinder)); } @Bean diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/SourceDefinedSymbolDeclarationReferenceFinderTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/SourceDefinedSymbolDeclarationReferenceFinderTest.java index d806ef39844..53c68422961 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/SourceDefinedSymbolDeclarationReferenceFinderTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/SourceDefinedSymbolDeclarationReferenceFinderTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/model/ReferenceTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/model/ReferenceTest.java index 57d5ebb132f..a262f68faa7 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/model/ReferenceTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/references/model/ReferenceTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,8 +23,6 @@ import com.github._1c_syntax.bsl.languageserver.context.symbol.MethodSymbol; import com.github._1c_syntax.bsl.languageserver.context.symbol.ModuleSymbol; -import com.github._1c_syntax.bsl.languageserver.references.model.OccurrenceType; -import com.github._1c_syntax.bsl.languageserver.references.model.Reference; import org.eclipse.lsp4j.Location; import org.eclipse.lsp4j.Range; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReportEntryTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReportEntryTest.java new file mode 100644 index 00000000000..d7533febd47 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReportEntryTest.java @@ -0,0 +1,64 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.reporters; + +import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import org.eclipse.lsp4j.Diagnostic; +import org.eclipse.lsp4j.DiagnosticSeverity; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +class CodeQualityReportEntryTest { + + @Autowired + private Map diagnosticInfosByCode; + + @Test + void testConstructor() { + var diagnostic = new Diagnostic( + Ranges.create(0, 1, 2, 3), + "message", + DiagnosticSeverity.Error, + "test-source", + "Typo" + ); + var diagnosticInfo = diagnosticInfosByCode.get("Typo"); + var entry = new CodeQualityReportEntry("file.txt", diagnostic, diagnosticInfo); + + assertThat(entry) + .hasNoNullFieldsOrProperties() + .hasFieldOrPropertyWithValue("description", "message") + .hasFieldOrPropertyWithValue("checkName", "Typo") + .hasFieldOrPropertyWithValue("severity", CodeQualityReportEntry.Severity.INFO) + .hasFieldOrPropertyWithValue("location.path", "file.txt") + .hasFieldOrPropertyWithValue("location.lines.begin", 1) + ; + } + +} \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReporterTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReporterTest.java new file mode 100644 index 00000000000..f6fe80bd6f3 --- /dev/null +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/CodeQualityReporterTest.java @@ -0,0 +1,99 @@ +/* + * This file is a part of BSL Language Server. + * + * Copyright (c) 2018-2025 + * Alexey Sosnoviy , Nikita Fedkin 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.reporters; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github._1c_syntax.bsl.languageserver.reporters.data.AnalysisInfo; +import com.github._1c_syntax.bsl.languageserver.reporters.data.FileInfo; +import com.github._1c_syntax.bsl.languageserver.util.TestUtils; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; +import org.apache.commons.io.FileUtils; +import org.eclipse.lsp4j.Diagnostic; +import org.eclipse.lsp4j.DiagnosticSeverity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +class CodeQualityReporterTest { + + private final File file = new File("./bsl-code-quality.json"); + + @Autowired + private CodeQualityReporter reporter; + + @BeforeEach + void setUp() { + FileUtils.deleteQuietly(file); + } + + @AfterEach + void tearDown() { + System.gc(); + FileUtils.deleteQuietly(file); + } + + @Test + void report() throws IOException { + + // given + Diagnostic diagnostic = new Diagnostic( + Ranges.create(0, 1, 2, 3), + "message", + DiagnosticSeverity.Error, + "test-source", + "Typo" + ); + + var documentContext = TestUtils.getDocumentContext(""); + String sourceDir = "."; + FileInfo fileInfo = new FileInfo(sourceDir, documentContext, Collections.singletonList(diagnostic)); + AnalysisInfo analysisInfo = new AnalysisInfo(LocalDateTime.now(), Collections.singletonList(fileInfo), sourceDir); + + // when + reporter.report(analysisInfo, Path.of(sourceDir)); + + // then + ObjectMapper mapper = new ObjectMapper(); + List report = mapper.readValue( + file, + new TypeReference>() { + } + ); + + assertThat(report).hasSize(1); + + } +} \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/ConsoleReporterTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/ConsoleReporterTest.java index 78477b1e98b..19762255b55 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/ConsoleReporterTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/ConsoleReporterTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,7 +21,6 @@ */ package com.github._1c_syntax.bsl.languageserver.reporters; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.reporters.data.AnalysisInfo; import com.github._1c_syntax.bsl.languageserver.reporters.data.FileInfo; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/GenericReporterTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/GenericReporterTest.java index 3d206ce69fb..ed33b67c1fc 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/GenericReporterTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/GenericReporterTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,7 +22,6 @@ package com.github._1c_syntax.bsl.languageserver.reporters; import com.fasterxml.jackson.databind.ObjectMapper; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.reporters.data.AnalysisInfo; import com.github._1c_syntax.bsl.languageserver.reporters.data.FileInfo; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/JUnitReporterTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/JUnitReporterTest.java index 91f282c6d07..f0baed09666 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/JUnitReporterTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/JUnitReporterTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,7 +23,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.reporters.data.AnalysisInfo; import com.github._1c_syntax.bsl.languageserver.reporters.data.FileInfo; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/JsonReporterTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/JsonReporterTest.java index ffce1b70abb..ec476dde2fb 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/JsonReporterTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/JsonReporterTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,7 +22,6 @@ package com.github._1c_syntax.bsl.languageserver.reporters; import com.fasterxml.jackson.databind.ObjectMapper; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.reporters.data.AnalysisInfo; import com.github._1c_syntax.bsl.languageserver.reporters.data.FileInfo; import com.github._1c_syntax.bsl.languageserver.reporters.databind.AnalysisInfoObjectMapper; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/ReportersAggregatorTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/ReportersAggregatorTest.java index 7d1b2254a8e..52307e0218c 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/ReportersAggregatorTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/ReportersAggregatorTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,7 +21,6 @@ */ package com.github._1c_syntax.bsl.languageserver.reporters; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.reporters.data.AnalysisInfo; import com.github._1c_syntax.bsl.languageserver.reporters.data.FileInfo; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/SarifReporterTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/SarifReporterTest.java index 1d83ac680e2..79013b37416 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/SarifReporterTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/SarifReporterTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -27,7 +27,6 @@ import com.contrastsecurity.sarif.SarifSchema210; import com.fasterxml.jackson.databind.ObjectMapper; 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.diagnostics.metadata.DiagnosticInfo; import com.github._1c_syntax.bsl.languageserver.reporters.data.AnalysisInfo; import com.github._1c_syntax.bsl.languageserver.reporters.data.FileInfo; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/TSLintReportEntryTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/TSLintReportEntryTest.java index 7dcf7325d3d..6bec1951a54 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/TSLintReportEntryTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/TSLintReportEntryTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/TSLintReporterTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/TSLintReporterTest.java index 2b4aeaf7a96..7aeb7933c7c 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/TSLintReporterTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/reporters/TSLintReporterTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -23,7 +23,6 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.reporters.data.AnalysisInfo; import com.github._1c_syntax.bsl.languageserver.reporters.data.FileInfo; import com.github._1c_syntax.bsl.languageserver.util.TestUtils; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/AbstractDirtyContextTestExecutionListener.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/AbstractDirtyContextTestExecutionListener.java index 31d63042002..5bb36ab7e7f 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/AbstractDirtyContextTestExecutionListener.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/AbstractDirtyContextTestExecutionListener.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/Assertions.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/Assertions.java index 2ddf9227221..e2c67792373 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/Assertions.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/Assertions.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -29,6 +29,7 @@ import com.github._1c_syntax.bsl.languageserver.util.assertions.FoldingRangeAssert; import com.github._1c_syntax.bsl.languageserver.util.assertions.FoldingRangesAssert; import com.github._1c_syntax.bsl.languageserver.util.assertions.SelectionRangesAssert; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.eclipse.lsp4j.CodeAction; import org.eclipse.lsp4j.ColorInformation; import org.eclipse.lsp4j.ColorPresentation; @@ -38,6 +39,7 @@ import java.util.List; +@SuppressFBWarnings("NM_SAME_SIMPLE_NAME_AS_SUPERCLASS") public class Assertions extends org.assertj.core.api.Assertions { public static DiagnosticAssert assertThat(Diagnostic actual) { diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/CleanupContextBeforeClassAndAfterClass.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/CleanupContextBeforeClassAndAfterClass.java index 555f66bf121..7076aeaa217 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/CleanupContextBeforeClassAndAfterClass.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/CleanupContextBeforeClassAndAfterClass.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/CleanupContextBeforeClassAndAfterEachTestMethod.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/CleanupContextBeforeClassAndAfterEachTestMethod.java index 727bf2aabc4..e6c2ef93c2e 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/CleanupContextBeforeClassAndAfterEachTestMethod.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/CleanupContextBeforeClassAndAfterEachTestMethod.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/DirtyContextBeforeClassAndAfterClassTestExecutionListener.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/DirtyContextBeforeClassAndAfterClassTestExecutionListener.java index c634e150ffc..d8fa66acc79 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/DirtyContextBeforeClassAndAfterClassTestExecutionListener.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/DirtyContextBeforeClassAndAfterClassTestExecutionListener.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/DirtyContextBeforeClassAndAfterTestMethodTestExecutionListener.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/DirtyContextBeforeClassAndAfterTestMethodTestExecutionListener.java index cdf5b248018..81c7f8c3cb3 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/DirtyContextBeforeClassAndAfterTestMethodTestExecutionListener.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/DirtyContextBeforeClassAndAfterTestMethodTestExecutionListener.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/RefreshContextTestExecutionListener.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/RefreshContextTestExecutionListener.java index fc3ac6d256c..0ab4ed04f76 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/RefreshContextTestExecutionListener.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/RefreshContextTestExecutionListener.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/TestApplicationContext.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/TestApplicationContext.java index 459500c3eac..064be4492b9 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/TestApplicationContext.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/TestApplicationContext.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,7 +21,6 @@ */ package com.github._1c_syntax.bsl.languageserver.util; -import org.jetbrains.annotations.NotNull; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; @@ -32,7 +31,7 @@ public class TestApplicationContext implements ApplicationContextAware { private static ApplicationContext CONTEXT; @Override - public void setApplicationContext(@NotNull ApplicationContext context) throws BeansException { + public void setApplicationContext(ApplicationContext context) throws BeansException { CONTEXT = context; } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/TestUtils.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/TestUtils.java index 0f79b160d27..f5df2698598 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/TestUtils.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/TestUtils.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,10 +24,11 @@ import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; import com.github._1c_syntax.bsl.languageserver.context.ServerContext; import com.github._1c_syntax.utils.Absolute; +import edu.umd.cs.findbugs.annotations.Nullable; import lombok.SneakyThrows; import org.apache.commons.io.FileUtils; +import org.eclipse.lsp4j.TextDocumentIdentifier; -import javax.annotation.Nullable; import java.io.File; import java.net.URI; import java.nio.charset.StandardCharsets; @@ -71,4 +72,9 @@ public static DocumentContext getDocumentContext(URI uri, String fileContent, Se context.rebuildDocument(documentContext, fileContent, 0); return documentContext; } + + public static TextDocumentIdentifier getTextDocumentIdentifier(URI uri) { + return new TextDocumentIdentifier(uri.toString()); + } + } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/CodeActionAssert.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/CodeActionAssert.java index 4bf2a9163a9..0d57bc55445 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/CodeActionAssert.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/CodeActionAssert.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorInformationAssert.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorInformationAssert.java index 3196983883b..b39f82bc033 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorInformationAssert.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorInformationAssert.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorInformationAssertFactory.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorInformationAssertFactory.java index 0c7c50032c1..b652924c883 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorInformationAssertFactory.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorInformationAssertFactory.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorInformationsAssert.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorInformationsAssert.java index a4ea696db49..5fa45b787b6 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorInformationsAssert.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorInformationsAssert.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorPresentationAssert.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorPresentationAssert.java index 35c31eaf10d..a0b88c4e3dc 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorPresentationAssert.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorPresentationAssert.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorPresentationAssertFactory.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorPresentationAssertFactory.java index 62929b76a86..0b8311a007e 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorPresentationAssertFactory.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorPresentationAssertFactory.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorPresentationsAssert.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorPresentationsAssert.java index 6e261f90144..f5c7b85f1eb 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorPresentationsAssert.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/ColorPresentationsAssert.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/DiagnosticAssert.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/DiagnosticAssert.java index 676017b165e..406b7431439 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/DiagnosticAssert.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/DiagnosticAssert.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -24,8 +24,10 @@ import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import org.assertj.core.api.AbstractAssert; import org.eclipse.lsp4j.Diagnostic; +import org.eclipse.lsp4j.DiagnosticRelatedInformation; import org.eclipse.lsp4j.Range; +import java.util.List; import java.util.Objects; public class DiagnosticAssert extends AbstractAssert { @@ -81,4 +83,45 @@ public DiagnosticAssert hasMessageOnRange(String message, int startLine, int sta // return the current assertion for method chaining return this; } + + /** + * Проверка на совпадение сообщения диагностики и диапазона текста, где она обнаружена + * + * @param expectedRange Первая строка диапазона + * @param expectedMessage Сообщение диагностики + * @param expectedRelatedInformation Список связанных диапазонов + * @return Ссылка на объект для текучести + */ + public DiagnosticAssert hasIssueOnRange(Range expectedRange, String expectedMessage, List expectedRelatedInformation) { + // check that actual TolkienCharacter we want to make assertions on is not null. + isNotNull(); + + // check condition + Range actualRange = actual.getRange(); + if (!Objects.equals(actualRange, expectedRange)) { + failWithMessage("Expected diagnostic's range to be <%s> but was <%s>", expectedRange.toString(), actualRange.toString()); + } + + if (!Objects.equals(expectedMessage, actual.getMessage())) { + failWithMessage("Expected diagnostic's expectedMessage to be <%s> but was <%s>", expectedMessage, actual.getMessage()); + } + + List actualRelatedInformation = actual.getRelatedInformation(); + if (expectedRelatedInformation.size() != actualRelatedInformation.size()){ + failWithMessage("Expected size of diagnostic's RelatedInformation to be <%d> but was <%d>", + expectedRelatedInformation.size(), actualRelatedInformation.size()); + } + + for (int i = 0; i < expectedRelatedInformation.size(); i++) { + var actualElem = actualRelatedInformation.get(i); + final var actualRelatedRange = actualElem.getLocation().getRange(); + var expectedRelatedRange = expectedRelatedInformation.get(i); + if (!Objects.equals(actualRelatedRange, expectedRelatedRange)) { + failWithMessage("Expected diagnostic's actualRange to be <%s> but was <%s>", expectedRelatedRange.toString(), actualRelatedRange.toString()); + } + } + + // return the current assertion for method chaining + return this; + } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/DiagnosticAssertFactory.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/DiagnosticAssertFactory.java index 282a337f091..28c10124f1a 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/DiagnosticAssertFactory.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/DiagnosticAssertFactory.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/DiagnosticsAssert.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/DiagnosticsAssert.java index a989bc17fea..a9e713204c2 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/DiagnosticsAssert.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/DiagnosticsAssert.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -21,9 +21,11 @@ */ package com.github._1c_syntax.bsl.languageserver.util.assertions; +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; import org.assertj.core.api.AbstractListAssert; import org.assertj.core.util.Lists; import org.eclipse.lsp4j.Diagnostic; +import org.eclipse.lsp4j.Range; import java.util.List; @@ -82,6 +84,41 @@ public DiagnosticsAssert hasMessageOnRange(String message, int lineNo, int start ); } + /** + * Ассерт для проверки совпадения диапазона-строки и сообщения + * + * @param lineNo Номер строки диапазона + * @param startChar Первый символ диапазона + * @param endChar Последний символ диапазона + * @param message Сообщение диагностики + * @param relatedLocationRanges Список связанных диапазонов + * @return Ссылка на объект для текучести + */ + public DiagnosticsAssert hasIssueOnRange(int lineNo, int startChar, int endChar, String message, + List relatedLocationRanges) { + return hasIssueOnRange(lineNo, startChar, lineNo, endChar, + message, relatedLocationRanges); + } + + /** + * Ассерт для проверки совпадения диапазона-строки и сообщения + * + * @param startLine Номер строки диапазона + * @param startChar Первый символ диапазона + * @param endLine Последняя строка диапазона + * @param endChar Последний символ диапазона + * @param message Сообщение диагностики + * @param relatedLocationRanges Список связанных диапазонов + * @return Ссылка на объект для текучести + */ + public DiagnosticsAssert hasIssueOnRange(int startLine, int startChar, int endLine, int endChar, String message, + List relatedLocationRanges) { + return anySatisfy(diagnostic -> + assertFactory.createAssert(diagnostic).hasIssueOnRange(Ranges.create(startLine, startChar, endLine, endChar), + message, relatedLocationRanges) + ); + } + @Override protected DiagnosticAssert toAssert(Diagnostic value, String description) { return assertFactory.createAssert(value); diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/FoldingRangeAssert.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/FoldingRangeAssert.java index 922739c58e4..61fd0626e3e 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/FoldingRangeAssert.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/FoldingRangeAssert.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/FoldingRangeAssertFactory.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/FoldingRangeAssertFactory.java index da011c6279a..323b00c8206 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/FoldingRangeAssertFactory.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/FoldingRangeAssertFactory.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/FoldingRangesAssert.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/FoldingRangesAssert.java index b19f8e6c918..ef145686c2f 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/FoldingRangesAssert.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/FoldingRangesAssert.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/SelectionRangeAssert.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/SelectionRangeAssert.java index 015f231fcda..d82c99cbb80 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/SelectionRangeAssert.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/SelectionRangeAssert.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/SelectionRangeAssertFactory.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/SelectionRangeAssertFactory.java index 39bfcf28939..ad1e8423c2d 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/SelectionRangeAssertFactory.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/SelectionRangeAssertFactory.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/SelectionRangesAssert.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/SelectionRangesAssert.java index 2fbf9a9eaa7..5cdc97e3c7f 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/SelectionRangesAssert.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/SelectionRangesAssert.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/package-info.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/package-info.java index 98c0d02a558..9519f8dfab5 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/package-info.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/assertions/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/package-info.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/package-info.java index c4573559f5d..b85db4c5af8 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/package-info.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/util/package-info.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -19,6 +19,8 @@ * You should have received a copy of the GNU Lesser General Public * License along with BSL Language Server. */ -@ParametersAreNonnullByDefault package com.github._1c_syntax.bsl.languageserver.util; +@DefaultAnnotation(NonNull.class) +package com.github._1c_syntax.bsl.languageserver.util; -import javax.annotation.ParametersAreNonnullByDefault; +import edu.umd.cs.findbugs.annotations.DefaultAnnotation; +import edu.umd.cs.findbugs.annotations.NonNull; diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/ExpressionParseTreeRewriterTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/ExpressionParseTreeRewriterTest.java index 3893037cf21..00bf93d84ab 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/ExpressionParseTreeRewriterTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/ExpressionParseTreeRewriterTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -28,7 +28,7 @@ import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.BslOperator; import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.ConstructorCallNode; import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.ExpressionNodeType; -import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.ExpressionParseTreeRewriter; +import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.ExpressionTreeBuildingVisitor; import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.MethodCallNode; import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.SkippedCallArgumentNode; import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.UnaryOperationNode; @@ -36,7 +36,6 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; -import static org.assertj.core.api.Assertions.as; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest @@ -147,6 +146,21 @@ void booleanPriority() { } + @Test + void booleanNotPriority() { + var code = "Рез = Не Б <> Неопределено И Ложь"; + var expressionTree = getExpressionTree(code); + var binary = (BinaryOperationNode) expressionTree; + + assertThat(binary.getOperator()).isEqualTo(BslOperator.AND); + + var negation = binary.getLeft().cast(); + assertThat(negation.getNodeType()).isEqualTo(ExpressionNodeType.UNARY_OP); + assertThat(negation.getOperator()).isEqualTo(BslOperator.NOT); + + assertThat((binary.getRight()).getNodeType()).isEqualTo(ExpressionNodeType.LITERAL); + } + @Test void dereferenceOfProperty() { var code = "Рез = Структура.Свойство"; @@ -296,9 +310,10 @@ BSLParser.ExpressionContext parse(String code) { @Test void realLifeHardExpression() { - var code = "СодержитПоля = ВложенныеЭлементы.Количество() > 0\n" + - "И Не (ВложенныеЭлементы.Количество() = 1\n" + - "И ТипЗнч(ВложенныеЭлементы[0]) = Тип(\"АвтоВыбранноеПолеКомпоновкиДанных\"));"; + var code = """ + СодержитПоля = ВложенныеЭлементы.Количество() > 0 + И Не (ВложенныеЭлементы.Количество() = 1 + И ТипЗнч(ВложенныеЭлементы[0]) = Тип("АвтоВыбранноеПолеКомпоновкиДанных"));"""; var expressionTree = getExpressionTree(code); var binary = (BinaryOperationNode) expressionTree; @@ -317,8 +332,46 @@ void realLifeHardExpression() { assertThat(binary.getRight().cast().getOperator()).isEqualTo(BslOperator.EQUAL); } + @Test + void notOperatorPriority() { + var code = "А = Не Разыменование.Метод() = Неопределено"; + + var expressionTree = getExpressionTree(code); + + assertThat(expressionTree.getNodeType()).isEqualTo(ExpressionNodeType.UNARY_OP); + + var unary = expressionTree.cast(); + assertThat(unary.getOperator()).isEqualTo(BslOperator.NOT); + assertThat(unary.getOperand()).isInstanceOf(BinaryOperationNode.class); + + var binary = unary.getOperand().cast(); + assertThat(binary.getOperator()).isEqualTo(BslOperator.EQUAL); + assertThat(binary.getLeft().cast().getOperator()).isEqualTo(BslOperator.DEREFERENCE); + assertThat(binary.getRight().getNodeType()).isEqualTo(ExpressionNodeType.LITERAL); + + } + + @Test + void notOperatorPriority_with_parenthesis() { + var code = "А = Не (Разыменование.Метод() = Неопределено)"; + + var expressionTree = getExpressionTree(code); + + assertThat(expressionTree.getNodeType()).isEqualTo(ExpressionNodeType.UNARY_OP); + + var unary = expressionTree.cast(); + assertThat(unary.getOperator()).isEqualTo(BslOperator.NOT); + assertThat(unary.getOperand()).isInstanceOf(BinaryOperationNode.class); + + var binary = unary.getOperand().cast(); + assertThat(binary.getOperator()).isEqualTo(BslOperator.EQUAL); + assertThat(binary.getLeft().cast().getOperator()).isEqualTo(BslOperator.DEREFERENCE); + assertThat(binary.getRight().getNodeType()).isEqualTo(ExpressionNodeType.LITERAL); + + } + BslExpression getExpressionTree(String code) { var expression = parse(code); - return ExpressionParseTreeRewriter.buildExpressionTree(expression); + return ExpressionTreeBuildingVisitor.buildExpressionTree(expression); } } \ No newline at end of file diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/ExpressionTreeComparersTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/ExpressionTreeComparersTest.java index ce0059d062a..dfd50778e91 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/ExpressionTreeComparersTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/ExpressionTreeComparersTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -26,7 +26,7 @@ import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.BslExpression; import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.BslOperator; import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.DefaultNodeEqualityComparer; -import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.ExpressionParseTreeRewriter; +import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.ExpressionTreeBuildingVisitor; import com.github._1c_syntax.bsl.languageserver.utils.expressiontree.TransitiveOperationsIgnoringComparer; import com.github._1c_syntax.bsl.parser.BSLParser; import org.junit.jupiter.api.Test; @@ -72,7 +72,7 @@ BSLParser.ExpressionContext parse(String code) { BslExpression getExpressionTree(String code) { var expression = parse(code); - return ExpressionParseTreeRewriter.buildExpressionTree(expression); + return ExpressionTreeBuildingVisitor.buildExpressionTree(expression); } } diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/RangesTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/RangesTest.java index 8d7571b71a1..6b413e522f8 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/RangesTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/RangesTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/StringsTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/StringsTest.java index fe80a902f46..15a21e87d0c 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/StringsTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/utils/StringsTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/test/java/com/github/_1c_syntax/bsl/languageserver/websocket/WebsocketLauncherTest.java b/src/test/java/com/github/_1c_syntax/bsl/languageserver/websocket/WebsocketLauncherTest.java index a0f5159bf33..e435603ff92 100644 --- a/src/test/java/com/github/_1c_syntax/bsl/languageserver/websocket/WebsocketLauncherTest.java +++ b/src/test/java/com/github/_1c_syntax/bsl/languageserver/websocket/WebsocketLauncherTest.java @@ -1,7 +1,7 @@ /* * This file is a part of BSL Language Server. * - * Copyright (c) 2018-2022 + * Copyright (c) 2018-2025 * Alexey Sosnoviy , Nikita Fedkin and contributors * * SPDX-License-Identifier: LGPL-3.0-or-later @@ -22,6 +22,13 @@ package com.github._1c_syntax.bsl.languageserver.websocket; import com.github._1c_syntax.bsl.languageserver.util.CleanupContextBeforeClassAndAfterEachTestMethod; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import jakarta.websocket.ClientEndpoint; +import jakarta.websocket.ContainerProvider; +import jakarta.websocket.DeploymentException; +import jakarta.websocket.OnOpen; +import jakarta.websocket.Session; +import jakarta.websocket.WebSocketContainer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -30,12 +37,6 @@ import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.test.context.ActiveProfiles; -import javax.websocket.ClientEndpoint; -import javax.websocket.ContainerProvider; -import javax.websocket.DeploymentException; -import javax.websocket.OnOpen; -import javax.websocket.Session; -import javax.websocket.WebSocketContainer; import java.io.ByteArrayOutputStream; import java.io.FileDescriptor; import java.io.FileOutputStream; @@ -101,6 +102,7 @@ void connectClientToServer(int websocketPort) throws URISyntaxException, Deploym session = webSocketContainer.connectToServer(client, new URI("ws://localhost:" + websocketPort + endpointPath)); } + @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED") void testWebsocketServer(int websocketPort) { try { latch.await(1, TimeUnit.SECONDS); diff --git a/src/test/resources/.bsl-language-server.json b/src/test/resources/.bsl-language-server.json index 2e404350461..04de080aa5c 100644 --- a/src/test/resources/.bsl-language-server.json +++ b/src/test/resources/.bsl-language-server.json @@ -4,6 +4,12 @@ "parameters": { "cognitiveComplexity": true, "cyclomaticComplexity": true + }, + "testRunner": { + "annotations": [ + "Test", + "Test2" + ] } }, "diagnostics": { diff --git a/src/test/resources/.partial-bsl-language-server.json b/src/test/resources/.partial-bsl-language-server.json index f3e3b85a302..070725801a3 100644 --- a/src/test/resources/.partial-bsl-language-server.json +++ b/src/test/resources/.partial-bsl-language-server.json @@ -4,6 +4,13 @@ "cyclomaticComplexity": false } }, + "inlayHint": { + "parameters": { + "sourceDefinedMethodCall": { + "showParametersWithTheSameName": true + } + } + }, "diagnostics": { "mode": "on" } diff --git a/src/test/resources/application-measures.properties b/src/test/resources/application-measures.properties index acf3564038e..b3b3c53fc65 100644 --- a/src/test/resources/application-measures.properties +++ b/src/test/resources/application-measures.properties @@ -10,7 +10,9 @@ logging.level.org.hibernate.engine.jdbc.spi.SqlExceptionHelper=fatal logging.level.org.springframework.data.repository.config.RepositoryConfigurationDelegate=warn logging.level.org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean=warn logging.level.org.springframework.context.support.PostProcessorRegistrationDelegate=warn +logging.level.org.springframework.core.LocalVariableTableParameterNameDiscoverer=error spring.application.name=BSL Language Server +logging.level.org.eclipse.lsp4j.jsonrpc.RemoteEndpoint=fatal logging.level.org.springframework.test.context.support.AnnotationConfigContextLoaderUtils=warn logging.level.org.springframework.test.context.support.AbstractContextLoader=warn @@ -20,4 +22,4 @@ app.globalConfiguration.path= app.configuration.path= app.websocket.lsp-path=/lsp sentry.environment=measures -sentry.logging.minimum-breadcrumb-level=debug +sentry.use-git-commit-id-as-release=false diff --git a/src/test/resources/application-websocket.properties b/src/test/resources/application-websocket.properties index d3c156204d6..9aa2bbcf105 100644 --- a/src/test/resources/application-websocket.properties +++ b/src/test/resources/application-websocket.properties @@ -10,6 +10,7 @@ logging.level.org.hibernate.engine.jdbc.spi.SqlExceptionHelper=fatal logging.level.org.springframework.data.repository.config.RepositoryConfigurationDelegate=warn logging.level.org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean=warn logging.level.org.springframework.context.support.PostProcessorRegistrationDelegate=warn +logging.level.org.springframework.core.LocalVariableTableParameterNameDiscoverer=error spring.application.name=BSL Language Server logging.level.org.springframework.test.context.support.AnnotationConfigContextLoaderUtils=warn @@ -19,4 +20,4 @@ app.globalConfiguration.path= app.configuration.path= app.websocket.lsp-path=/lsp sentry.environment=test -sentry.logging.minimum-breadcrumb-level=debug +sentry.use-git-commit-id-as-release=false diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties index 70a567bad3c..c07b3c59a53 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/application.properties @@ -10,7 +10,9 @@ logging.level.org.hibernate.engine.jdbc.spi.SqlExceptionHelper=fatal logging.level.org.springframework.data.repository.config.RepositoryConfigurationDelegate=warn logging.level.org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean=warn logging.level.org.springframework.context.support.PostProcessorRegistrationDelegate=warn +logging.level.org.springframework.core.LocalVariableTableParameterNameDiscoverer=error spring.application.name=BSL Language Server +logging.level.org.eclipse.lsp4j.jsonrpc.RemoteEndpoint=fatal logging.level.org.springframework.test.context.support.AnnotationConfigContextLoaderUtils=warn logging.level.org.springframework.test.context.support.AbstractContextLoader=warn @@ -19,4 +21,4 @@ app.globalConfiguration.path= app.configuration.path= app.websocket.lsp-path=/lsp sentry.environment=test -sentry.logging.minimum-breadcrumb-level=debug +sentry.use-git-commit-id-as-release=false diff --git a/src/test/resources/codelenses/AbstractRunTestCodeLensSupplier.os b/src/test/resources/codelenses/AbstractRunTestCodeLensSupplier.os new file mode 100644 index 00000000000..36cbb010e60 --- /dev/null +++ b/src/test/resources/codelenses/AbstractRunTestCodeLensSupplier.os @@ -0,0 +1,6 @@ +&Тест +Процедура Тест1() Экспорт +КонецПроцедуры + +Процедура НеТест1() Экспорт +КонецПроцедуры \ No newline at end of file diff --git a/src/test/resources/codelenses/CognitiveComplexityCodeLensSupplier.bsl b/src/test/resources/codelenses/CognitiveComplexityCodeLensSupplier.bsl index 584106879e1..813fcdd54f4 100644 --- a/src/test/resources/codelenses/CognitiveComplexityCodeLensSupplier.bsl +++ b/src/test/resources/codelenses/CognitiveComplexityCodeLensSupplier.bsl @@ -6,3 +6,6 @@ Процедура ИмяПроцедуры2() КонецПроцедуры + +Процедура () +КонецПроцедуры diff --git a/src/test/resources/codelenses/RunAllTestsCodeLensSupplier.os b/src/test/resources/codelenses/RunAllTestsCodeLensSupplier.os new file mode 100644 index 00000000000..654be9d9a9f --- /dev/null +++ b/src/test/resources/codelenses/RunAllTestsCodeLensSupplier.os @@ -0,0 +1,9 @@ +&Тест +Процедура Тест1() Экспорт + А = 0; +КонецПроцедуры + +&Тест +Процедура Тест2() Экспорт + Б = 0; +КонецПроцедуры diff --git a/src/test/resources/codelenses/RunTestCodeLensSupplier.os b/src/test/resources/codelenses/RunTestCodeLensSupplier.os new file mode 100644 index 00000000000..654be9d9a9f --- /dev/null +++ b/src/test/resources/codelenses/RunTestCodeLensSupplier.os @@ -0,0 +1,9 @@ +&Тест +Процедура Тест1() Экспорт + А = 0; +КонецПроцедуры + +&Тест +Процедура Тест2() Экспорт + Б = 0; +КонецПроцедуры diff --git a/src/test/resources/codelenses/testrunner/TestRunnerAdapter.os b/src/test/resources/codelenses/testrunner/TestRunnerAdapter.os new file mode 100644 index 00000000000..4c60847796f --- /dev/null +++ b/src/test/resources/codelenses/testrunner/TestRunnerAdapter.os @@ -0,0 +1,6 @@ +&Тест +Процедура Тест1() Экспорт +КонецПроцедуры + +Процедура НеТест1() Экспорт +КонецПроцедуры diff --git a/src/test/resources/codelenses/tests/AbstractRunTestCodeLensSupplier.os b/src/test/resources/codelenses/tests/AbstractRunTestCodeLensSupplier.os new file mode 100644 index 00000000000..36cbb010e60 --- /dev/null +++ b/src/test/resources/codelenses/tests/AbstractRunTestCodeLensSupplier.os @@ -0,0 +1,6 @@ +&Тест +Процедура Тест1() Экспорт +КонецПроцедуры + +Процедура НеТест1() Экспорт +КонецПроцедуры \ No newline at end of file diff --git a/src/test/resources/commands/ToggleCognitiveComplexityInlayHintsCommandSupplier.bsl b/src/test/resources/commands/ToggleCognitiveComplexityInlayHintsCommandSupplier.bsl new file mode 100644 index 00000000000..584106879e1 --- /dev/null +++ b/src/test/resources/commands/ToggleCognitiveComplexityInlayHintsCommandSupplier.bsl @@ -0,0 +1,8 @@ +Процедура ИмяПроцедуры() + Если Истина Тогда + А = 0; + КонецЕсли; +КонецПроцедуры + +Процедура ИмяПроцедуры2() +КонецПроцедуры diff --git a/src/test/resources/commands/ToggleCyclomaticComplexityInlayHintsCommandSupplier.bsl b/src/test/resources/commands/ToggleCyclomaticComplexityInlayHintsCommandSupplier.bsl new file mode 100644 index 00000000000..584106879e1 --- /dev/null +++ b/src/test/resources/commands/ToggleCyclomaticComplexityInlayHintsCommandSupplier.bsl @@ -0,0 +1,8 @@ +Процедура ИмяПроцедуры() + Если Истина Тогда + А = 0; + КонецЕсли; +КонецПроцедуры + +Процедура ИмяПроцедуры2() +КонецПроцедуры diff --git a/src/test/resources/context/computer/MethodSymbolComputerTest.bsl b/src/test/resources/context/computer/MethodSymbolComputerTest.bsl index 48e45d7b444..3cf9ded7919 100644 --- a/src/test/resources/context/computer/MethodSymbolComputerTest.bsl +++ b/src/test/resources/context/computer/MethodSymbolComputerTest.bsl @@ -115,5 +115,8 @@ // Параметры: // Парам1 - Строка - Парам // Парам3 - Строка - Парам -Процедура Метод25(Парам1, Парам2, Парам3) -КонецПроцедуры \ No newline at end of file +Процедура Метод24(Парам1, Парам2, Парам3) +КонецПроцедуры + +Процедура Метод25(&Повторяемый Парам1, &ДругаяАннотация("СПараметром") Парам2, Парам3) +КонецПроцедуры diff --git a/src/test/resources/context/symbol/MethodDescription.bsl b/src/test/resources/context/symbol/MethodDescription.bsl index 1abed2994d4..c66e7ccdd08 100644 --- a/src/test/resources/context/symbol/MethodDescription.bsl +++ b/src/test/resources/context/symbol/MethodDescription.bsl @@ -143,3 +143,13 @@ // Функция BUG_1495(Ссылки, Знач Реквизиты, ВыбратьРазрешенные = Ложь) Экспорт КонецФункции + +// Описание процедуры +&Аннотация("Параметр") +Процедура ПроцедураСАннотацией() +КонецПроцедуры + +&Аннотация("Параметр") +// Описание процедуры +Процедура ПроцедураСАннотациейПередОписанием() +КонецПроцедуры diff --git a/src/test/resources/context/symbol/variableSymbolTest.bsl b/src/test/resources/context/symbol/variableSymbolTest.bsl index de17b2730e2..bf6e7ce5f32 100644 --- a/src/test/resources/context/symbol/variableSymbolTest.bsl +++ b/src/test/resources/context/symbol/variableSymbolTest.bsl @@ -55,4 +55,20 @@ ПеременнаяСоздаваемаяВКодеВнеМетода = Неопределенно; ПеременнаяСоздаваемаяВКодеВнеМетодаВторойПример = МойМетод(); -А.ЭтоНеПеременная = Неопределенно; \ No newline at end of file +А.ЭтоНеПеременная = Неопределенно; + +Для Каждого МетодБезКоментария Из Методы Цикл + МойМетод(Метод); +КонецЦикла; + +Для Каждого МетодСКоментарием Из Методы Цикл // Висячий комментарий для цикла + МойМетод(Метод); +КонецЦикла; + +Для СчДляБезКоментария = 1 По 100 Цикл + МойМетод(Метод); +КонецЦикла; + +Для СчДляСКоментарием = 1 По 100 Цикл // Висячий комментарий для цикла + МойМетод(Метод); +КонецЦикла; \ No newline at end of file diff --git a/src/test/resources/diagnostics/DenyIncompleteValuesDiagnostic.bsl b/src/test/resources/diagnostics/DenyIncompleteValuesDiagnostic.bsl new file mode 100644 index 00000000000..b0aa62f601a --- /dev/null +++ b/src/test/resources/diagnostics/DenyIncompleteValuesDiagnostic.bsl @@ -0,0 +1,2 @@ +Процедура Метод1() +КонецПроцедуры diff --git a/src/test/resources/diagnostics/DisableSafeModeDiagnostic.bsl b/src/test/resources/diagnostics/DisableSafeModeDiagnostic.bsl new file mode 100644 index 00000000000..e51acd2d709 --- /dev/null +++ b/src/test/resources/diagnostics/DisableSafeModeDiagnostic.bsl @@ -0,0 +1,16 @@ +&НаСервере +Процедура Метод() + УстановитьБезопасныйРежим(Ложь); // есть замечание + + Значение = Ложь; + УстановитьБезопасныйРежим(Значение); // есть замечание + + УстановитьБезопасныйРежим(Истина); // нет замечания + + УстановитьОтключениеБезопасногоРежима(Истина); // есть замечание + + Значение = Истина; + УстановитьОтключениеБезопасногоРежима(Значение); // есть замечание + + УстановитьОтключениеБезопасногоРежима(Ложь); // нет замечания +КонецПроцедуры diff --git a/src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl b/src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl new file mode 100644 index 00000000000..8c78d16da94 --- /dev/null +++ b/src/test/resources/diagnostics/DoubleNegativesDiagnostic.bsl @@ -0,0 +1,69 @@ +// Выражение в условии +Если Не ТаблицаЗначений.Найти(ИскомоеЗначение, "Колонка") <> Неопределено Тогда + // Сделать действие +КонецЕсли; + +А = Не Отказ <> Ложь; +А = Не (Отказ <> Ложь); +А = Не НекотороеЗначение() <> Неопределено; +А = Не Неопределено <> НекотороеЗначение(); +А = Не (А <> Неопределено); // срабатывает +А = Не А <> Неопределено И Б = 5; // срабатывает +А = Не (А <> Неопределено и Б = 5); // не срабатывает +А = Не (А <> Неопределено или Б = 5); // не срабатывает +А = Не (Б = 5 и А <> Неопределено); // не срабатывает + +Пока Не Таблица.Данные <> Неопределено Цикл +КонецЦикла; + +Б = Не (Не А = 1 или Б <> Неопределено); // не срабатывает на "Не А = 1" +Б = Не (А <> 1 или Не Б <> Неопределено); // срабатывает на "Не Б <> Неопределено" +Б = Не (А <> 1 или Не Б = Неопределено); // не срабатывает на "Не Б <> Неопределено" т.к. сравнения вида Не Х = Неопределено популярны + +Если Не Т.Найти(Значение) = Неопределено Тогда + // не срабатывает, т.к. популярный код +КонецЕсли; + +// Отрицание с проверкой на неравенство нелитералу + +А = Не (Отказ <> НеЛитерал); // срабатывает +А = Не СложнаяФункция() <> НеЛитерал; // срабатывает + +Б = Не (А = 1 или Б <> НеЛитерал); // не срабатывает + +// Прямое двойное отрицание + +Б = Не (Не Значение); +Б = Не (Не Значение И ДругоеЗначение); // не срабатывает + +// NoSuchElementException +Запись = РегистрыСведений.ЗаданияКПересчетуСтатуса.СоздатьМенеджерЗаписи(); +Запись.Записать(Истина); + +// C ошибкой разбора +// Вынесено в отдельную процедуру в блоке subAfterCodeBlock, т.к. иначе парсер ломается целиком и expression tree builder +// ничего не строит +Процедура Тест() + + Если Истина Тогда + + // C ошибкой разбора + Если Тогда + + КонецЕсли; + + // С ошибкой разбора + Пока А Цикл + Если + #Если Сервер Тогда + F + #Иначе + G + #КонецЕсли + Тогда + КонецЕсли; + КонецЦикла; + + КонецЕсли; + +КонецПроцедуры \ No newline at end of file diff --git a/src/test/resources/diagnostics/DuplicatedInsertionIntoCollectionDiagnostic.bsl b/src/test/resources/diagnostics/DuplicatedInsertionIntoCollectionDiagnostic.bsl new file mode 100644 index 00000000000..5d99e9badbf --- /dev/null +++ b/src/test/resources/diagnostics/DuplicatedInsertionIntoCollectionDiagnostic.bsl @@ -0,0 +1,278 @@ +&НаСервере +Процедура Тест1() + Массив = Новый Массив; + Массив.Добавить(СтрокаТаблицы); + Массив.Добавить(СтрокаТаблицы); // ошибка + + Коллекция = Новый Структура; + Коллекция.Вставить("Ключ1", 1); + Коллекция.Вставить("Ключ1", 1); // ошибка + + Коллекция2 = Новый Структура; + Коллекция2.Вставить("Ключ1", 1); + Коллекция2.Вставить("Ключ1", 2); // ошибка - вставка разных значений для одного ключа + + Если Условие() Тогда + Массив.Добавить(СтрокаТаблицы); // не ошибка + Коллекция.Вставить("Ключ1", 1); // не ошибка + Коллекция2.Вставить("Ключ1", 2); // не ошибка + КонецЕсли; + + Если Условие() Тогда + Коллекция.Вставить("Ключ1", 1); + Коллекция.Вставить("Ключ1", 3); // новая ошибка, а не повторение ошибки выше + КонецЕсли; + + Для Каждого Элемент Из Коллекция Цикл + Итог.Коллекция.Индексы.Добавить("Пользователь"); + Итог.Коллекция.Индексы.Добавить("Пользователь"); // ошибка + + Итог.ПерваяКоллекция.Индексы.Добавить("Пользователь"); + Итог.ВтораяКоллекция.Индексы.Добавить("Пользователь"); // не ошибка + КонецЦикла; + + Если Условие() Тогда + ПовторнаяСоздаваемаяКоллекция = Новый Массив; + ПовторнаяСоздаваемаяКоллекция.Добавить("Пользователь"); + ОбщаяКоллекция.Добавить(ПовторнаяСоздаваемаяКоллекция); + ПовторнаяСоздаваемаяКоллекция = Новый Массив; + ПовторнаяСоздаваемаяКоллекция.Добавить("Пользователь"); // не ошибка + ОбщаяКоллекция.Добавить(ПовторнаяСоздаваемаяКоллекция); // не ошибка + + Контекст.Коллекция.Вставить("ИмяПрава", "Чтение"); + ЗаполнитьСтруктуруРасчетаПрава(Результат.СтруктураРасчетаПраваЧтение, Контекст.Коллекция); + Контекст.Коллекция.Вставить("ИмяПрава", "Изменение"); // не ошибка + + Контекст2.Коллекция.Вставить("ИмяПрава", "Чтение"); + Если Условие() Тогда + ЕщеМетод(Контекст2); + КонецЕсли; + Контекст2.Коллекция.Вставить("ИмяПрава", "Изменение"); //не ошибка + КонецЕсли; + + Если Условие() Тогда + + // ошибка далее валидна и возникает из-за того, что код не режется препроцессором + #Если ТолстыйКлиентОбычноеПриложение Тогда + ЭлементыСтиля.Вставить(ЭлементСтиля.Ключ, ЭлементСтиля.Значение.Получить()); // ошибка + #Иначе + ЭлементыСтиля.Вставить(ЭлементСтиля.Ключ, ЭлементСтиля.Значение); + #КонецЕсли + КонецЕсли; + + Если Условие() Тогда + Элементы.ТипСтрокой.СписокВыбора.Вставить(0, "Дата", НСтр("ru = 'Дата'")); + Элементы.ТипСтрокой.СписокВыбора.Вставить(0, "Строка", НСтр("ru = 'Строка'")); // не ошибка + КонецЕсли; + +КонецПроцедуры + +Функция ПрерываниеПотокаВыполнения_Возврат(Ссылка, УчитыватьПометкуУдаления = Истина) Экспорт + + ВидыСвойствНабора = Новый Структура; + ВидыСвойствНабора.Вставить("ДополнительныеРеквизиты", Ложь); + + ТипСсылки = Неопределено; + МетаданныеВладельца = МетаданныеВладельцаЗначенийСвойствНабора(Ссылка, УчитыватьПометкуУдаления, ТипСсылки); + + Если МетаданныеВладельца = Неопределено Тогда + Возврат ВидыСвойствНабора; // прерывание потока выполнения + КонецЕсли; + + // Проверка использования дополнительных реквизитов. + ВидыСвойствНабора.Вставить("ДополнительныеРеквизиты", Истина); // не ошибка + + Возврат ВидыСвойствНабора; + +КонецФункции + +Процедура ПрисваиваниеСложногоВыражения(Данные) + Данные.ПовторнаяСоздаваемаяКоллекция = Новый Массив; + Данные.ПовторнаяСоздаваемаяКоллекция.Добавить("Пользователь"); + Данные.ОбщаяКоллекция.Добавить(Данные.ПовторнаяСоздаваемаяКоллекция); + + Данные.ПовторнаяСоздаваемаяКоллекция = Новый Массив; + Данные.ПовторнаяСоздаваемаяКоллекция.Добавить("Пользователь"); // не ошибка + Данные.ОбщаяКоллекция.Добавить(Данные.ПовторнаяСоздаваемаяКоллекция); // не ошибка + + Данные.Метод().ПовторнаяСоздаваемаяКоллекция = Новый Массив; + Данные.Метод().ПовторнаяСоздаваемаяКоллекция.Добавить("Пользователь"); + Данные.Метод().ПовторнаяСоздаваемаяКоллекция.Добавить("Пользователь"); // ошибка + + Данные.Метод().ОбщаяКоллекция.Добавить(Данные.Метод().ПовторнаяСоздаваемаяКоллекция); + Данные.Метод().ОбщаяКоллекция.Добавить(Данные.Метод().ПовторнаяСоздаваемаяКоллекция); // ошибка + + Данные.Метод().ПовторнаяСоздаваемаяКоллекция = Новый Массив; + Данные.Метод().ПовторнаяСоздаваемаяКоллекция.Добавить("Пользователь"); // не ошибка + Данные.Метод().ОбщаяКоллекция.Добавить(Данные.Метод().ПовторнаяСоздаваемаяКоллекция); // не ошибка +КонецПроцедуры + +Функция ВнутреннееПрерываниеПотокаВыполнения_ЦиклВнутриБлока() + + ВидыСвойствНабора = Новый Структура; + ВидыСвойствНабора.Вставить("ДополнительныеРеквизиты", Ложь); + + Для Каждого Элемент Из Коллекция Цикл + Прервать; + КонецЦикла; + + // Проверка использования дополнительных реквизитов. + ВидыСвойствНабора.Вставить("ДополнительныеРеквизиты", Истина); // ошибка + + Возврат ВидыСвойствНабора; + +КонецФункции + +Функция ДублированиеВПоследующихЭлементах() + + ПовторнаяСоздаваемаяКоллекция = Новый Массив; + ПовторнаяСоздаваемаяКоллекция.Добавить("Пользователь"); + ОбщаяКоллекция.Добавить(ПовторнаяСоздаваемаяКоллекция); + + ПовторнаяСоздаваемаяКоллекция = Новый Массив; + ПовторнаяСоздаваемаяКоллекция.Добавить("Пользователь"); // не ошибка + ПовторнаяСоздаваемаяКоллекция.Добавить("Пользователь"); // ошибка + + ОбщаяКоллекция.Добавить(ПовторнаяСоздаваемаяКоллекция); // не ошибка + ОбщаяКоллекция.Добавить(ПовторнаяСоздаваемаяКоллекция); // ошибка + +КонецФункции + +Процедура ЧастиКлюча(Данные) + Данные.ОбщаяКоллекция.Вставить(Данные.Реквизит.ПовторнаяСоздаваемаяКоллекция); + Данные.Реквизит = Выражение(); + Данные.ОбщаяКоллекция.Вставить(Данные.Реквизит.ПовторнаяСоздаваемаяКоллекция); // не ошибка + + Данные2.ОбщаяКоллекция2.Вставить(Данные2.Реквизит2.ПовторнаяСоздаваемаяКоллекция2); + Реквизит2.ПовторнаяСоздаваемаяКоллекция2 = Новый Массив; + Данные2.ОбщаяКоллекция2.Вставить(Данные2.Реквизит2.ПовторнаяСоздаваемаяКоллекция2); // ошибка + + Данные3.ОбщаяКоллекция3.Вставить(Данные3.Реквизит3.ПовторнаяСоздаваемаяКоллекция3); + ПовторнаяСоздаваемаяКоллекция3 = Новый Массив; + Данные3.ОбщаяКоллекция3.Вставить(Данные3.Реквизит3.ПовторнаяСоздаваемаяКоллекция3); // ошибка +КонецПроцедуры + +Процедура ОдинаковыеИменаКлючаИМетода(Описания) + Описания.Добавить(Ключ); + Метод(Ключ()); + Описания.Добавить(Ключ); // ошибка + + Описания2.Добавить(Часть1.Часть2); + Метод(Часть1().Часть2()); + Описания2.Добавить(Часть1.Часть2); // ошибка + Описания2.Добавить(Часть1.Часть2); // а эта строка должна попасть в связанные элементы +КонецПроцедуры + +Процедура СписокЗначений(Результат) + Сведения = Новый СписокЗначений; + Сведения.Добавить("", "ИННЮЛ"); + Сведения.Добавить("", "КППЮЛ"); // не ошибка + + Сведения2.ДобавленныеЭлементы.Добавить(ИмяКоманды, 1); + Сведения2.ДобавленныеЭлементы.Добавить(ИмяКоманды, 9, Истина); // не ошибка, если включен параметр для исключения метода Добавить +КонецПроцедуры + +Процедура ПрисваиваниеРодителюИОбращениеКПотомку(Данные) + ПовторнаяСоздаваемаяКоллекция = Новый Массив; + ПовторнаяСоздаваемаяКоллекция.Данные.Добавить("Пользователь"); + + ПовторнаяСоздаваемаяКоллекция = Новый Массив; + ПовторнаяСоздаваемаяКоллекция.Данные.Добавить("Пользователь"); // не ошибка +КонецПроцедуры + +Процедура ДублированиеПустыхЗначений(Сведения, Метаданные) + Сведения = Новый Массив; + Сведения.Добавить(""); + + Сведения.Добавить(СтроковыеФункцииКлиентСервер.ПодставитьПараметрыВСтроку(НСтр("ru = 'Конфигурация: %1'"), Метаданные.Представление())); + Сведения.Добавить(СтроковыеФункцииКлиентСервер.ПодставитьПараметрыВСтроку(НСтр("ru = 'Версия конфигурации: %1'"), Метаданные.Версия)); + Сведения.Добавить(СтроковыеФункцииКлиентСервер.ПодставитьПараметрыВСтроку(НСтр("ru = 'Версия Библиотеки стандартных подсистем: %1'"), СтандартныеПодсистемыСервер.ВерсияБиблиотеки())); + Сведения.Добавить(СтроковыеФункцииКлиентСервер.ПодставитьПараметрыВСтроку(НСтр("ru = 'Версия приложения: %1 (%2)'"), СистемнаяИнформация.ВерсияПриложения, СистемнаяИнформация.ТипПлатформы)); + + Сведения.Добавить(""); // не ошибка + + Сведения.Добавить(НСтр("ru = 'Системная информация'")); + + Текст.Добавить(, Тип("ПереводСтрокиФорматированногоДокумента")); + Текст.Добавить(, Тип("ПереводСтрокиФорматированногоДокумента")); // не ошибка + + ЧастиСтроки.Добавить(" "); + ЧастиСтроки.Добавить(" "); // не ошибка + + ОписаниеВызова.Добавить(Неопределено); + ОписаниеВызова.Добавить(Неопределено); // не ошибка + + ЧастиСтроки.Добавить(Символы.ПС); + ЧастиСтроки.Добавить(Символы.ПС); // не ошибка +КонецПроцедуры + +Процедура ИзменениеРеквизитаВставленногоОбъекта(Результат) + Описание.ИмяРеквизита = "ТабельныйНомер"; + Описания.Добавить(Описание); + Описание.ИмяРеквизита = "ДатаПриема"; + Описания.Добавить(Описание); // не ошибка + + Описания2.Добавить(Метод(Описание) + Коллекция.Значение); + Коллекция.Значение.ИмяРеквизита = "ДатаПриема"; + Описания2.Добавить(Метод(Описание) + Коллекция.Значение); // не ошибка +КонецПроцедуры + +Процедура ИзменениеРеквизитаВставленногоОбъекта(Результат) + ИменаПромежуточныхВТ = Новый Массив; + ИмяВТСотрудники = ""; + + // Отбор сотрудников по документам-основаниям. + СоздатьВТСотрудникиДляВедомостиПоОснованиям(МенеджерВременныхТаблиц, ОписаниеОперации, ИмяВТСотрудники); + ИменаПромежуточныхВТ.Добавить(ИмяВТСотрудники); + + // Отбор сотрудников по организации и подразделению. + СоздатьВТСотрудникиДляВедомостиПоМестуРаботы(МенеджерВременныхТаблиц, ОписаниеОперации, ОтборСотрудников, ИмяВТСотрудники); + ИменаПромежуточныхВТ.Добавить(ИмяВТСотрудники); // не ошибка +КонецПроцедуры + +Процедура ИзменениеЗначенияИспользуемогоВКлюче(Результат) + Лист.Данные.Вставить("П000001000102_" + Формат(НомСуффикса, "ЧГ="), "1000"); + + НомСуффикса = НомСуффикса + 1; + + Лист.Данные.Вставить("П000001000102_" + Формат(НомСуффикса, "ЧГ="), "5000"); // не ошибка + + Протокол = "HTTP"; + Разрешения.Добавить(МодульРаботаВБезопасномРежиме.РазрешениеНаИспользованиеИнтернетРесурса(Протокол)); + + Протокол = "HTTPS"; + Разрешения.Добавить(МодульРаботаВБезопасномРежиме.РазрешениеНаИспользованиеИнтернетРесурса(Протокол)); // не ошибка + + // Добавим имена событий механизмов расчета партий и себестоимости + ПараметрыРасчета = Новый Структура("ЗапущенРасчетПартий", Истина); + ОтборПоСобытию.Добавить(ИмяСобытияОшибкиДляЖурналаРегистрации(ПараметрыРасчета)); + + ПараметрыРасчета = Новый Структура("ЗапущенРасчетПартий", Ложь); + ОтборПоСобытию.Добавить(ИмяСобытияОшибкиДляЖурналаРегистрации(ПараметрыРасчета)); // не ошибка +КонецПроцедуры + +Процедура ПрерываниеПотокаВыполнения_БлокВЦикле(Коллекция, Коллекция2) + Для Каждого Элемент Из Коллекция Цикл + Коллекция2.Добавить(Элемент); + Если Условие() Тогда + Прервать; + КонецЕсли; + Коллекция2.Добавить(Элемент); // не ошибка + КонецЦикла; +КонецПроцедуры + +Процедура ДубльПриВызовеГлобальногоМетода(СтрокаТаблицы) + Коллекция().Добавить(СтрокаТаблицы); + Коллекция().Добавить(СтрокаТаблицы); // ошибка + + Коллекция2().Реквизит.Добавить(СтрокаТаблицы2); + Коллекция2().Реквизит.Добавить(СтрокаТаблицы2); // ошибка +КонецПроцедуры + +Процедура СтранноеДляПокрытия() + Коллекция.Вставить(); + Коллекция.Вставить(); //не ошибка + + Коллекция2().Реквизит.Добавить(); + Коллекция2().Реквизит.Добавить(); // не ошибка +КонецПроцедуры diff --git a/src/test/resources/diagnostics/ExternalAppStartingDiagnostic.bsl b/src/test/resources/diagnostics/ExternalAppStartingDiagnostic.bsl new file mode 100644 index 00000000000..80924867e83 --- /dev/null +++ b/src/test/resources/diagnostics/ExternalAppStartingDiagnostic.bsl @@ -0,0 +1,58 @@ + +Процедура Метод() + СтрокаКоманды = ""; + ТекущийКаталог = ""; + ДождатьсяЗавершения = Истина; + ОписаниеОповещения = Неопределено; + ПараметрыКоманды = Новый Структура; + + КомандаСистемы(СтрокаКоманды, ТекущийКаталог); // есть замечание + ЗапуститьПриложение(СтрокаКоманды, ТекущийКаталог); // есть замечание + ЗапуститьПриложение(СтрокаКоманды, ТекущийКаталог, Истина); // есть замечание + + НачатьЗапускПриложения(ОписаниеОповещения, СтрокаКоманды, ТекущийКаталог, ДождатьсяЗавершения); // есть замечание + + ПерейтиПоНавигационнойСсылке(СтрокаКоманды); // есть замечание + ФайловаяСистемаКлиент.ОткрытьНавигационнуюСсылку(СтрокаКоманды); // есть замечание + ФайловаяСистемаКлиент.ОткрытьНавигационнуюСсылку(СтрокаКоманды, ОписаниеОповещения); // есть замечание + + ФайловаяСистемаКлиент.ЗапуститьПрограмму("ping 127.0.0.1 -n 5", ПараметрыКоманды); // есть замечание + ФайловаяСистемаКлиент.ЗапуститьПрограмму(СтрокаКоманды, ПараметрыКоманды); // есть замечание + ФайловаяСистема.ЗапуститьПрограмму(СтрокаКоманды); // есть замечание + ФайловаяСистема.ЗапуститьПрограмму(СтрокаКоманды, ПараметрыКоманды); // есть замечание + + ФайловаяСистемаКлиент.ОткрытьПроводник("C:\Users"); // есть замечание + ФайловаяСистемаКлиент.ОткрытьФайл(СтрокаКоманды); // есть замечание + ФайловаяСистемаКлиент.ОткрытьФайл(СтрокаКоманды, ОписаниеОповещения); // есть замечание + +КонецПроцедуры + +&НаКлиенте +Асинх Процедура Подключить() + СтрокаКоманды = ""; + ТекущийКаталог = ""; + ДождатьсяЗавершения = Истина; + + Ждать ЗапуститьПриложениеАсинх(СтрокаКоманды, ТекущийКаталог, ДождатьсяЗавершения); // есть замечание +КонецПроцедуры + +&НаСервере +Процедура ПараметрНаИмяВнешнегоПриложения() + СтрокаКоманды = ""; + ТекущийКаталог = ""; + ДождатьсяЗавершения = Истина; + + МойОбщийМодуль.ЗапуститьВнешнееПриложение(СтрокаКоманды, ТекущийКаталог, ДождатьсяЗавершения); // есть замечание +КонецПроцедуры + +&НаКлиенте +Процедура ПроверкаЗапуститьСистему() + ДополнительныеПараметрыКоманднойСтроки = ""; + ДождатьсяЗавершения = Истина; + КодВозврата = Неопределено; + + ЗапуститьСистему(); // есть замечание + ЗапуститьСистему(ДополнительныеПараметрыКоманднойСтроки); // есть замечание + ЗапуститьСистему(ДополнительныеПараметрыКоманднойСтроки, ДождатьсяЗавершения); // есть замечание + ЗапуститьСистему(ДополнительныеПараметрыКоманднойСтроки, ДождатьсяЗавершения, КодВозврата); // есть замечание +КонецПроцедуры diff --git a/src/test/resources/diagnostics/FileSystemAccessDiagnostic.bsl b/src/test/resources/diagnostics/FileSystemAccessDiagnostic.bsl new file mode 100644 index 00000000000..84333a26b2c --- /dev/null +++ b/src/test/resources/diagnostics/FileSystemAccessDiagnostic.bsl @@ -0,0 +1,41 @@ +Процедура Метод1() + Значение = Новый File(ИмяФайла); // есть ошибка + Значение = Новый xBase("C:\temp.dbf"); // есть ошибка + Значение = Новый HTMLWriter; // есть ошибка + Значение = Новый HTMLReader; // есть ошибка + Значение = Новый FastInfosetReader; // есть ошибка + Значение = Новый FastInfosetWriter; // есть ошибка + Значение = Новый XSLTransform; // есть ошибка + Значение = Новый ZipFileWriter(ИмяФайла); // есть ошибка + Значение = Новый ZipFileReader(ИмяФайла); // есть ошибка + Значение = Новый TextReader(ИмяФайла); // есть ошибка + Значение = Новый TextWriter(ИмяФайла); // есть ошибка + Значение = Новый TextExtraction(ИмяФайла); // есть ошибка + Значение = Новый BinaryData(ИмяФайла); // есть ошибка + Значение = Новый FileStream(ИмяФайла, РежимОткрытия); // есть ошибка +КонецПроцедуры + +&НаСервере +Процедура Метод2() + Значение = Новый xBase("C:\temp.dbf"); // есть ошибка +КонецПроцедуры + +&НаСервереБезКонтекста +Процедура Метод3() + Значение = Новый xBase; // есть ошибка +КонецПроцедуры + +&НаКлиенте +Процедура Метод4() + ЗначениеВФайл("C:\Temp\PersonalData.txt", ЛичныеДанные); // есть ошибка + КопироватьФайл("C:\Temp\Order.htm", "C:\My Documents\Order.htm"); // есть ошибка + + МассивИмен = Новый Массив(); + МассивИмен.Добавить("C:\Windows\Temp\Presentation.ppt.1"); + ОбъединитьФайлы(МассивИмен, "C:\Windows\Temp\Presentation.ppt"); // есть ошибка + + ПереместитьФайл("C:\Temp\Order.htm", "C:\My Documents\Order.htm"); // есть ошибка + РазделитьФайл("C:\Windows\Temp\Presentation.ppt", 1024 * 1024 ); // есть ошибка + СоздатьКаталог("C:\Temp"); // есть ошибка + УдалитьФайлы("C:\temp\Works"); // есть ошибка +КонецПроцедуры diff --git a/src/test/resources/diagnostics/InternetAccessDiagnostic.bsl b/src/test/resources/diagnostics/InternetAccessDiagnostic.bsl new file mode 100644 index 00000000000..f556f167b3a --- /dev/null +++ b/src/test/resources/diagnostics/InternetAccessDiagnostic.bsl @@ -0,0 +1,35 @@ +Процедура Тест1() + FTPСоединение = Новый FTPСоединение(Сервер, Порт, Пользователь, Пароль); // ошибка + + Определения = Новый WSОпределения("http://localhost/test.asmx?WSDL"); // ошибка + + ПроксиДва = Новый WSПрокси(Определения, "http://localhost/", "test", "test"); // ошибка + + Определения = + Новый WSОпределения("http://localhost/test.asmx?WSDL", "Пользователь", "Пароль", Неопределено, Таймаут); // ошибка + +КонецПроцедуры + +Процедура HTTP() + HTTPСоединение = Новый HTTPСоединение("zabbix.localhost", 80); // ошибка + HTTPЗапрос = Новый HTTPЗапрос(); // ошибка + HTTPЗапрос = Новый HTTPЗапрос("zabbix", 80); // ошибка + HTTPЗапрос = Новый HTTPЗапрос("zabbix"); // ошибка + ИнтернетПрокси = Новый ИнтернетПрокси("zabbix"); // ошибка +КонецПроцедуры + +Функция НовыйИнтернетПочтовыйПрофильБезТаймАута() + Профиль = Новый ИнтернетПочтовыйПрофиль; // ошибка + Профиль.Пользователь = "admin"; + Возврат Профиль; +КонецФункции + +Функция InternetMail() + Профиль = Новый InternetMail; // ошибка +КонецФункции + +Функция InternetMail_НовыйИмя() + Профиль = Новый("InternetMail"); // ошибка +КонецФункции + +Профиль = Новый Почта; // ошибка diff --git a/src/test/resources/diagnostics/MagicDateDiagnostic.bsl b/src/test/resources/diagnostics/MagicDateDiagnostic.bsl index 044f4133257..201c9c8311c 100644 --- a/src/test/resources/diagnostics/MagicDateDiagnostic.bsl +++ b/src/test/resources/diagnostics/MagicDateDiagnostic.bsl @@ -1,3 +1,13 @@ +Функция МаксимальнаяДата() Экспорт + Возврат '39991231235959'; +КонецФункции + +Функция МаксимальнаяДатаПриПродолжении() + Возврат '99990101000000'; +КонецФункции + +Процедура Тест3() + День = Дата("00020101"); День = Дата("00020101") + Шаг; // ошибка День = Дата("00020101121314") + Шаг; // ошибка @@ -11,4 +21,47 @@ КонецЦикла; День = Дата("00010101") + Шаг; // исключение День = '0001-01why not?01' + Шаг; // исключение -День = '0001-01why not?02' + Шаг; // ошибка \ No newline at end of file +День = '0001-01why not?02' + Шаг; // ошибка + +ИменаПараметров = СтроковыеФункции.РазложитьСтрокуВМассивПодстрок(ИмяПараметра, , Дата("00050101")); // замечание +ИменаПараметров = СтроковыеФункции.РазложитьСтрокуВМассивПодстрок(ИмяПараметра, "00050101", "00050101"); // замечание +Настройки = Настройки('12350101'); // замечание +Настройки.Свойство("00020501121314", ЗначениеЕдиничногоПараметра); // замечание +Выполнить("00020501121314" + '12350101'); // замечание + +ОтборЭлемента.ПравоеЗначение = Новый СтандартнаяДатаНачала(Дата('19800101000000')); + +Значение = Метод("%1/%2"); +Если Условие Тогда + ВызватьИсключение "Не указано значение константы ХХХ"; +КонецЕсли; + +УИДЗамера = Новый УникальныйИдентификатор("00000000-0000-0000-0000-000000000000"); +ПосторонниеСимволы = СтрСоединить(СтрРазделить(СтрокаСЧислом, "0123456789", Ложь), ""); +Объект.GetStringValue("2147483649","Software\Buhphone","ProgramPath", Значение); +НедопустимыеСимволы = НедопустимыеСимволыВСтроке(СтрАдрес.АдресСервера, + "0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ_-.:*?"); +НедопустимыеСимволы = НедопустимыеСимволы + "1234567890 "; + +Дата = Метод("04937803-5dba-11df-a1d4-005056c00008"); +Набор.Идентификатор = Новый УникальныйИдентификатор("70425541-23e3-4e5a-8bd3-9587cc949dfa"); + +НецифровыеСимволы = СтрСоединить(СтрРазделить(Значение, "1234567890,.")); +Результат = Сред("0123456789abcdef", ОстатокОтДеления + 1, 1) + Результат; + +Результат.Добавить(СтрокаОбъектаАдресации("10100000", НСтр("ru = 'Почтовый индекс'"))); +КодСтроки = КодРодителя + Прав("00000000" + Формат(Счетчик, "ЧГ="), ЧислоЦифр); +КлючНаборовСвойств = НачалоКлюча + Лев(КлючНазначения + "00000000000000000000000000000000", 32); + +КодыКЛАДР.Регион = Лев(КодКЛАДР, 2) + "00000000000"; +КодыКЛАДР.Район = Лев(КодКЛАДР, 5) + "00000000"; + +Значение = ?(А = '39990202', '39991231235959', '39990101000000'); + +Если Сейчас < Дата("12340101") Тогда +КонецЕсли; + +КонецПроцедуры + +Функция Метод(Дата1 = '39990202') +КонецФункции diff --git a/src/test/resources/diagnostics/MagicNumberDiagnostic.bsl b/src/test/resources/diagnostics/MagicNumberDiagnostic.bsl index b522921512d..d64f41dbb9f 100644 --- a/src/test/resources/diagnostics/MagicNumberDiagnostic.bsl +++ b/src/test/resources/diagnostics/MagicNumberDiagnostic.bsl @@ -1,7 +1,7 @@ Процедура ПроверкаЧисел() ПонятнаяПеременная = 6; // Нет ошибки - СекундВЧасе = 60 * 60; // Ошибкат на двух числах + СекундВЧасе = 60 * 60; // Ошибка на двух числах Если ТекущаяДатаИВремя > СекундВЧасе Тогда // Нет ошибки @@ -25,22 +25,21 @@ КонецЕсли; - ЭтоВоскресенье = ДеньНедели = 7; // Тут ошибка, хоть и вглядит нормально. + ЭтоВоскресенье = ДеньНедели = 7; // Тут ошибка, хоть и выглядит нормально. ДеньНеделиВоскресенье = 7; ЭтоВоскресенье = ДеньНедели = ДеньНеделиВоскресенье; // А вот тут уже ошибки нет - // Далеше без ошибок ПроверочноеПеречисление = Новый Массив; - ПроверочноеПеречисление.Добавить(1); - ПроверочноеПеречисление.Добавить(2); - ПроверочноеПеречисление.Добавить(3); + ПроверочноеПеречисление.Добавить(1); // Нет ошибки из-за исключения + ПроверочноеПеречисление.Добавить(2); // ошибка + ПроверочноеПеречисление.Добавить(3); // ошибка - ПроверочнаяСтруктура = Новый Структура("Авто,ПростойВариант,СложныйВариант", 0, 1, 2); - ПроверочнаяСтруктура.Добавить("ЭкспертныйВариант", 3); + ПроверочнаяСтруктура = Новый Структура("Авто,ПростойВариант,СложныйВариант", 0, 1, 2); // ошибка только на 2 + ПроверочнаяСтруктура.Добавить("ЭкспертныйВариант", 3); // ошибка КонецПроцедуры -Процедура А(А = 566) +Процедура А(А = 566) // пропущенная ошибка КонецПроцедуры @@ -51,6 +50,6 @@ КонецФункции Процедура Индексы() - Индекс1 = Коллекция.Индексы[20]; - Метод(Индексы[21]) + Индекс1 = Коллекция.Индексы[20]; // замечание при allowMagicIndexes = false + Метод(Индексы[21]) // замечание при allowMagicIndexes = false КонецПроцедуры \ No newline at end of file diff --git a/src/test/resources/diagnostics/MissedRequiredParameterDiagnostic.bsl b/src/test/resources/diagnostics/MissedRequiredParameterDiagnostic.bsl new file mode 100644 index 00000000000..98053044559 --- /dev/null +++ b/src/test/resources/diagnostics/MissedRequiredParameterDiagnostic.bsl @@ -0,0 +1,46 @@ +Процедура Рассчет() + + Результат = Сложение(, 2); // Range(2, 16, 2, 29) + Сообщить(Результат); + + Инкремент(Результат); + Сообщить(Результат); + + Результат = Сложение(5); // Range(8, 16, 8, 27) + Сообщить(Результат); + + Результат = Сложение(5, 4, 3); + Сообщить(Результат); + + Результат = Сложение(); // 2xRange(14, 16, 14, 26) + Сообщить(Результат); + + Сообщить(Сложение(,)); // 2хRange(17, 13, 17, 24) + Сообщить(Менеджер("Справочник")); // Range(18, 13, 18, 35) +КонецПроцедуры + +Процедура Версионирование() + ВерсионированиеПриЗаписи(1); + Документы.ПКО.ВерсионированиеПриЗаписи(1); + ПервыйОбщийМодуль.ВерсионированиеПриЗаписи(1); // Range(24, 22, 24, 49) + ПервыйОбщийМодуль.ВерсионированиеПриЗаписи(2,); // Range(25, 22, 25, 50) + ПервыйОбщийМодуль.ВерсионированиеПриЗаписи(); // 2xRange(26, 22, 26, 48) + Сообщить(ПервыйОбщийМодуль.ВерсионированиеПриЗаписи()); // 2xRange(27, 31, 27, 57) + Справочники.Справочник1.Тест(); // Range(28, 28, 28, 34); + Результат = ЭтотОбъект.Сложение(, 2); + +КонецПроцедуры + +Функция Сложение(Левый, Правый) Экспорт + Возврат Левый + Правый; +КонецФункции + +Функция Инкремент(Значение, Приращение = 1) + Значение = Значение + Приращение; + Возврат Значение; +КонецФункции + +Функция Менеджер(Тип = "Справочник", Вид) + ИмяТипа = СтрШаблон("%1Менеджер.%2", Тип, Вид); + Возврат Новый(Тип(ИмяТипа)); +КонецФункции diff --git a/src/test/resources/diagnostics/MissingCommonModuleMethodDiagnostic.bsl b/src/test/resources/diagnostics/MissingCommonModuleMethodDiagnostic.bsl new file mode 100644 index 00000000000..aa665cee4fb --- /dev/null +++ b/src/test/resources/diagnostics/MissingCommonModuleMethodDiagnostic.bsl @@ -0,0 +1,37 @@ +Процедура Тест1() + ПервыйОбщийМодуль.МетодНесуществующий(1, 2); // ошибка + А = ПервыйОбщийМодуль.ДругойМетодНесуществующий(); // ошибка + ПервыйОбщийМодуль.ЕщеМетодНесуществующий().Добавить(); // ошибка + ПервыйОбщийМодуль.ЕщеОдинМетодНесуществующий().Реквизит = 10; // ошибка + Б = ПервыйОбщийМодуль.ЕщеДругойМетодНесуществующий().Добавить(); // ошибка + + НесуществующийОбщийМодульИлиПростоПеременная.МетодНесуществующий(1, 2); // не ошибка +КонецПроцедуры + +Процедура Тест2_ОбращениеКПриватномуМетоду() + ПервыйОбщийМодуль.РегистрацияИзмененийПередУдалением(Источник, Отказ); // ошибка + А = ПервыйОбщийМодуль.Тест(); // ошибка + ПервыйОбщийМодуль.Тест().Добавить(); // ошибка + ПервыйОбщийМодуль.Тест().Реквизит = 10; // ошибка + Б = ПервыйОбщийМодуль.Тест().Добавить(); // ошибка +КонецПроцедуры + +Процедура Тест3() + ПервыйОбщийМодуль.НеУстаревшаяПроцедура(); // не ошибка + А = ПервыйОбщийМодуль.НеУстаревшаяФункция(); // не ошибка + ПервыйОбщийМодуль.НеУстаревшаяФункция().Добавить(); // не ошибка + ПервыйОбщийМодуль.НеУстаревшаяФункция().Реквизит = 10; // не ошибка + Б = ПервыйОбщийМодуль.НеУстаревшаяФункция().Добавить(); // не ошибка +КонецПроцедуры + +Процедура Тест4_ИмяПараметр(ПервыйОбщийМодуль) + ПервыйОбщийМодуль.МетодНесуществующий(1, 2); // не ошибка + А = ПервыйОбщийМодуль.ДругойМетодНесуществующий(); // не ошибка + ПервыйОбщийМодуль.ЕщеМетодНесуществующий().Добавить(); // не ошибка + ПервыйОбщийМодуль.ЕщеОдинМетодНесуществующий().Реквизит = 10; // не ошибка + Б = ПервыйОбщийМодуль.ЕщеДругойМетодНесуществующий().Добавить(); // не ошибка +КонецПроцедуры + +Процедура Тест5_МодулиМенеджеров() + Справочники.Справочник1.НесуществующийМетод(); // пока не ошибка +КонецПроцедуры \ No newline at end of file diff --git a/src/test/resources/diagnostics/PrivilegedModuleMethodCallDiagnostic.bsl b/src/test/resources/diagnostics/PrivilegedModuleMethodCallDiagnostic.bsl new file mode 100644 index 00000000000..7058aac790b --- /dev/null +++ b/src/test/resources/diagnostics/PrivilegedModuleMethodCallDiagnostic.bsl @@ -0,0 +1,17 @@ +#Область ПрограммныйИнтерфейс + +Функция Тест1() + Значение = ПривилегированныйМодуль1.ПубличнаяФункция(); // ошибка + ПривилегированныйМодуль1.ПубличнаяПроцедура(); // ошибка +КонецФункции + +Процедура Тест2() + Значение = ПривилегированныйМодуль1.ПриватнаяФункция(); // не ошибка в данном правиле + ПривилегированныйМодуль1.ПриватнаяПроцедура(); // не ошибка в данном правиле +КонецПроцедуры + +#КонецОбласти + +#Область СлужебныеПроцедурыИФункции + +#КонецОбласти diff --git a/src/test/resources/diagnostics/ProtectedModuleDiagnostic.bsl b/src/test/resources/diagnostics/ProtectedModuleDiagnostic.bsl new file mode 100644 index 00000000000..6293b7b948f --- /dev/null +++ b/src/test/resources/diagnostics/ProtectedModuleDiagnostic.bsl @@ -0,0 +1,2 @@ +Процедура Метод() +КонецПроцедуры diff --git a/src/test/resources/diagnostics/RefOveruseDiagnostic.bsl b/src/test/resources/diagnostics/RefOveruseDiagnostic.bsl index 0d15fde0ba0..e1d4b64730f 100644 --- a/src/test/resources/diagnostics/RefOveruseDiagnostic.bsl +++ b/src/test/resources/diagnostics/RefOveruseDiagnostic.bsl @@ -98,7 +98,7 @@ Процедура Тест11() Запрос = Новый Запрос; -ТекстЗапроса = + ТекстЗапроса = "ВЫБРАТЬ РАЗРЕШЕННЫЕ РАЗЛИЧНЫЕ | ТаблицаКонтактнаяИнформация.АдресЭП КАК Адрес, | ТаблицаКонтакт.Ссылка КАК Контакт @@ -242,7 +242,7 @@ Процедура Тест22() ТекстЗапроса = "ВЫБРАТЬ - | УпаковкиНоменклатуры.Ссылка КАК Упаковка + | УпаковкиНоменклатуры.Ссылка КАК Упаковка |ИЗ | ТоварыКОтгрузке КАК ТоварыКОтгрузке | ЛЕВОЕ СОЕДИНЕНИЕ Справочник.УпаковкиНоменклатуры КАК УпаковкиНоменклатуры @@ -250,3 +250,131 @@ | ЛЕВОЕ СОЕДИНЕНИЕ Справочник.УпаковкиНоменклатуры КАК УпаковкиНоменклатуры // спец.дубль имени, было падение анализа | ПО Истина"; // не ошибка КонецПроцедуры + +Процедура Тест23() + ТекстЗапроса = + "ВЫБРАТЬ + | СкладскиеЯчейки.Ссылка КАК Ячейка, + | СкладскиеЯчейки.Контейнер КАК Контейнер + |ИЗ + | РегистрСведений.ПериодичностьИнвентаризацииЗон КАК ПериодичностьИнвентаризацииЗон + | ВНУТРЕННЕЕ СОЕДИНЕНИЕ Справочник.СкладскиеЯчейки КАК СкладскиеЯчейки + | ЛЕВОЕ СОЕДИНЕНИЕ Документ.ЗадачаПересчет КАК ЗадачаПересчет + | ПО СкладскиеЯчейки.Ссылка = ЗадачаПересчет.Ячейка + | ПО ПериодичностьИнвентаризацииЗон.Зона = СкладскиеЯчейки.СкладскаяЗона + |ГДЕ + | ЗадачаПересчет.Ссылка ЕСТЬ NULL"; +КонецПроцедуры + +Процедура Тест24() + Запрос.Текст = + "ВЫБРАТЬ + | КОЛИЧЕСТВО(РАЗЛИЧНЫЕ усОстаткиТоваровОстатки.Контейнер) КАК Контейнер + |ИЗ + | РегистрНакопления.усОстаткиТоваров.Остатки( + | , + | Контейнер В + | (ВЫБРАТЬ РАЗЛИЧНЫЕ + | ЗадачаПеремещениеТовара.ТекущийКонтейнер КАК ТекущийКонтейнер + | ИЗ + | Документ.ЗадачаПеремещениеТовара КАК ЗадачаПеремещениеТовара + | ГДЕ + | ЗадачаПеремещениеТовара.Ссылка В (&МассивЗадач) // не ошибка + | ) + | ) КАК усОстаткиТоваровОстатки + |"; +КонецПроцедуры + +Процедура Тест25() + Запрос.Текст = + "ВЫБРАТЬ + | КОЛИЧЕСТВО(РАЗЛИЧНЫЕ усОстаткиТоваровОстатки.Контейнер) КАК Контейнер + |ИЗ + | РегистрНакопления.усОстаткиТоваров.Остатки( + | , + | Контейнер В + | (ВЫБРАТЬ РАЗЛИЧНЫЕ + | ЗадачаПеремещениеТовара.ТекущийКонтейнер.Ссылка КАК ТекущийКонтейнер // ошибка + | ИЗ + | Документ.ЗадачаПеремещениеТовара КАК ЗадачаПеремещениеТовара + | ГДЕ + | ЗадачаПеремещениеТовара.Ссылка.Ссылка В (&МассивЗадач) // ошибка + | ) + | ) КАК усОстаткиТоваровОстатки + |"; +КонецПроцедуры + +Процедура Тест26() + Запрос.Текст = + "ВЫБРАТЬ + | Звеньевой.Ссылка // ошибка, обращение к реквизиту без псевдонима таблицы + |ИЗ + | РегистрСведений.Звеньевые"; +КонецПроцедуры + +Процедура Тест27() + Запрос.Текст = + "ВЫБРАТЬ ПЕРВЫЕ 1 + | Справочник.Пользователи.ТекущееПодразделение + |ИЗ + | Справочник.Пользователи + |ГДЕ + | Справочник.Пользователи.Ссылка = &Пользователь"; +КонецПроцедуры + +Процедура Тест28() + Запрос.Текст = + "ВЫБРАТЬ + |ЗаявкаНаХранение.Товары.( + | Номенклатура КАК Номенклатура, + | Ссылка.Склад КАК Склад // не ошибка + |) КАК Товары + |ИЗ + | Документ.ЗаявкаНаХранение КАК ЗаявкаНаХранение + |ГДЕ + | ЗаявкаНаХранение.Ссылка = &ДокументОснование + |"; +КонецПроцедуры + +Процедура Тест29() + Запрос.Текст = + "ВЫБРАТЬ + | Пользователи.ТекущееПодразделение.Код КАК ТекущееПодразделениеКод, + | Пользователи.Ссылка.ТекущееПодразделение.Код КАК СсылкаТекущееПодразделениеКод, // ошибка + | Пользователи.ТекущееПодразделение.Ссылка.Код КАК ТекущееПодразделениеСсылкаКод // ошибка + |ИЗ + | Справочник.Пользователи КАК Пользователи"; +КонецПроцедуры + +Процедура Тест30() + Запрос.Текст = + "ВЫБРАТЬ + | ПользователиДополнительныеРеквизиты.Ссылка, + | ВЫБОР + | КОГДА ПользователиДополнительныеРеквизиты.Ссылка.ПометкаУдаления // Не ошибка + | ТОГДА ПользователиДополнительныеРеквизиты.Ссылка.ТекущееПодразделение.Ссылка // ошибка + | ИНАЧЕ ПользователиДополнительныеРеквизиты.Ссылка.ТекущееПодразделение // Не ошибка + | КОНЕЦ КАК Поле1 + |ИЗ + | Справочник.Пользователи.ДополнительныеРеквизиты КАК ПользователиДополнительныеРеквизиты"; +КонецПроцедуры + +Процедура Тест31() + Запрос.Текст = + "ВЫБРАТЬ + | Справочник31.ТабличнаяЧасть1.Ссылка // ошибка без метаданных + |ИЗ + | Справочник.Справочник1 КАК Справочник31"; +КонецПроцедуры + +Процедура Тест32() + Запрос.Текст = + "ВЫБРАТЬ + | Справочник32.Ссылка + |ИЗ + | Справочник.Справочник1 КАК Справочник32 + |СГРУППИРОВАТЬ ПО + | Справочник32.Ссылка + |ИМЕЮЩИЕ + | КОЛИЧЕСТВО(Справочник32.ТабличнаяЧасть1.Ссылка) > 0"; // ошибка без метаданных +КонецПроцедуры diff --git a/src/test/resources/diagnostics/ReservedParameterNamesDiagnostic.bsl b/src/test/resources/diagnostics/ReservedParameterNamesDiagnostic.bsl new file mode 100644 index 00000000000..0ab58041572 --- /dev/null +++ b/src/test/resources/diagnostics/ReservedParameterNamesDiagnostic.bsl @@ -0,0 +1,7 @@ +// при наличии в списке зарезервированного имени перечисления ВидГруппыФормы должен сработать тест + +Процедура Тест1(ВидГруппыФормы) // здесь должен сработать тест + + А = ВидГруппыФормы.ОбычнаяГруппа; + +КонецПроцедуры diff --git a/src/test/resources/diagnostics/SetPrivilegedModeDiagnostic.bsl b/src/test/resources/diagnostics/SetPrivilegedModeDiagnostic.bsl new file mode 100644 index 00000000000..a10678f92c7 --- /dev/null +++ b/src/test/resources/diagnostics/SetPrivilegedModeDiagnostic.bsl @@ -0,0 +1,8 @@ +&НаСервере +Процедура Метод() + УстановитьПривилегированныйРежим(Истина); // есть замечание + Значение = Истина; + УстановитьПривилегированныйРежим(Значение); // есть замечание + + УстановитьПривилегированныйРежим(Ложь); // нет замечания +КонецПроцедуры diff --git a/src/test/resources/diagnostics/TransferringParametersBetweenClientAndServerDiagnostic.bsl b/src/test/resources/diagnostics/TransferringParametersBetweenClientAndServerDiagnostic.bsl new file mode 100644 index 00000000000..5efadc81e2b --- /dev/null +++ b/src/test/resources/diagnostics/TransferringParametersBetweenClientAndServerDiagnostic.bsl @@ -0,0 +1,46 @@ +&НаКлиенте +Процедура Клиент1() + Сервер1(2); +КонецПроцедуры + +&НаСервере +Процедура Сервер1(Парам1) // ошибка + Метод(Парам1); +КонецПроцедуры + +&НаКлиенте +Процедура Клиент2() + Сервер2(2); +КонецПроцедуры + +&НаСервере +Процедура Сервер2(Знач Парам1) // не ошибка +КонецПроцедуры + +&НаКлиенте +Процедура Клиент3() + Сервер3(2); +КонецПроцедуры + +&НаСервере +Процедура Сервер3(Парам1) // не ошибка + Парам1 = 10; +КонецПроцедуры + +&НаКлиентеНаСервереБезКонтекста +Процедура КлиентСервер4(Парам1) // не ошибка + Сервер4(2); +КонецПроцедуры + +&НаСервере +Процедура Сервер4(Парам1) // не ошибка + ЕщеМетод(Парам1); +КонецПроцедуры + +&НаСервере +Процедура Метод(Парам1) +КонецПроцедуры + +&НаСервере +Процедура ЕщеМетод(Парам1) +КонецПроцедуры diff --git a/src/test/resources/diagnostics/UnusedParametersDiagnostic.bsl b/src/test/resources/diagnostics/UnusedParametersDiagnostic.bsl index 953702ac01c..eb0edc26d15 100644 --- a/src/test/resources/diagnostics/UnusedParametersDiagnostic.bsl +++ b/src/test/resources/diagnostics/UnusedParametersDiagnostic.bsl @@ -24,4 +24,8 @@ Объект.Поле = 1; Объект2.Поле.Метод(2); Чтото[Объект3]; -КонецПроцедуры \ No newline at end of file +КонецПроцедуры + +Процедура нпе( , знач "") + Объект.Поле = 1; +КонецПроцедуры diff --git a/src/test/resources/diagnostics/UsageWriteLogEventDiagnostic.bsl b/src/test/resources/diagnostics/UsageWriteLogEventDiagnostic.bsl index 27f58ff29bd..572c8d56c5a 100644 --- a/src/test/resources/diagnostics/UsageWriteLogEventDiagnostic.bsl +++ b/src/test/resources/diagnostics/UsageWriteLogEventDiagnostic.bsl @@ -292,3 +292,156 @@ КороткийТекстСообщения); // ошибка КонецПопытки; КонецПроцедуры + +&НаСервере +Процедура Тест2() + + ЗаписьЖурналаРегистрации("Событие", + УровеньЖурналаРегистрации.Ошибка, , , + ПодробноеПредставлениеОшибки(ИнформацияОбОшибке())); + + Попытка + ПравильноеИсключениеВКодеСервер(); + Исключение + ЗаписьЖурналаРегистрации("Событие", УровеньЖР, + , , ОбработкаОшибок.ПодробноеПредставлениеОшибки(ИнформацияОбОшибке())); + КонецПопытки; + + ЗаписьЖурналаРегистрации(НСтр("ru = 'Мой механизм.Действие с возможной ошибкой'", КодОсновногоЯзыка), + УровеньЖурналаРегистрации.Ошибка, , , + НСтр("ru = 'Во время выполнения действия произошла неизвестная ошибка.'") + Символы.ПС + + ОбработкаОшибок.ПодробноеПредставлениеОшибки(ИнформацияОбОшибке())); + + Попытка + ПравильноеИсключениеВКодеСервер(); + Исключение + + ТекстОшибки = ОбработкаОшибок.ПодробноеПредставлениеОшибки(ИнформацияОбОшибке()); + ЗаписьЖурналаРегистрации("Событие", УровеньЖурналаРегистрации.Ошибка, , , + ТекстОшибки); + КонецПопытки; + +КонецПроцедуры + +&НаКлиенте +Процедура ПравильноеИсключениеВКодеКлиент_ОбработкаОшибок() + Попытка + ИсключениеВКодеСервер(); + Исключение + ТекстСообщения = ОбработкаОшибок.КраткоеПредставлениеОшибки(ИнформацияОбОшибке()); + ПоказатьПредупреждение(,НСтр("ru = 'Операция не может быть выполнена по причине:'") + Символы.ПС + ТекстСообщения); + КонецПопытки; +КонецПроцедуры + +&НаКлиенте +Процедура ПравильноСоздатьФайлНаДиске_ОбработкаОшибок() + Попытка + // клиентский код, приводящий к вызову исключения + СоздатьФайлНаДиске(); + Исключение + ТекстСообщения = ОбработкаОшибок.КраткоеПредставлениеОшибки(ИнформацияОбОшибке()); + ПоказатьПредупреждение(,НСтр("ru = 'Операция не может быть выполнена по причине:'") + Символы.ПС + ТекстСообщения); + ЗаписатьОшибкуРаботыСФайлами(ОбработкаОшибок.ПодробноеПредставлениеОшибки(ИнформацияОбОшибке())); + КонецПопытки; +КонецПроцедуры + +&НаКлиенте +Процедура ВИсключенииЕстьКраткоеПредставлениеНоНетПолного_ОбработкаОшибок() + Попытка + // клиентский код, приводящий к вызову исключения + СоздатьФайлНаДиске(); + Исключение + ПоказатьПредупреждение(,НСтр("ru = 'Операция не может быть выполнена по причине:'") + Символы.ПС + ТекстСообщения); + ЗаписьЖурналаРегистрации(НСтр("ru = 'Выполнение операции'"), + УровеньЖурналаРегистрации.Ошибка,,, + ОбработкаОшибок.КраткоеПредставлениеОшибки(ИнформацияОбОшибке())); // ошибка + КонецПопытки; +КонецПроцедуры + +&НаКлиенте +Процедура ВИсключенииЕстьКраткоеПредставлениеНоНетПолного1_ОбработкаОшибок() + Попытка + // клиентский код, приводящий к вызову исключения + СоздатьФайлНаДиске(); + Исключение + ТекстСообщения = ОбработкаОшибок.КраткоеПредставлениеОшибки(ИнформацияОбОшибке()); + ПоказатьПредупреждение(,НСтр("ru = 'Операция не может быть выполнена по причине:'") + Символы.ПС + ТекстСообщения); + ЗаписьЖурналаРегистрации(НСтр("ru = 'Выполнение операции'"), + УровеньЖурналаРегистрации.Ошибка,,, + ТекстСообщения); // ошибка + КонецПопытки; +КонецПроцедуры + +&НаКлиенте +Процедура ВИсключенииЕстьКраткоеПредставлениеНоНетПолного2_ОбработкаОшибок() + Попытка + // клиентский код, приводящий к вызову исключения + СоздатьФайлНаДиске(); + Исключение + ТекстСообщения = ОбработкаОшибок.КраткоеПредставлениеОшибки(ИнформацияОбОшибке()); + ДругойТекстСообщения = ОбработкаОшибок.ПодробноеПредставлениеОшибки(ИнформацияОбОшибке()); + ПоказатьПредупреждение(,НСтр("ru = 'Операция не может быть выполнена по причине:'") + Символы.ПС + ТекстСообщения); + ЗаписьЖурналаРегистрации(НСтр("ru = 'Выполнение операции'"), + УровеньЖурналаРегистрации.Ошибка,,, + ТекстСообщения); // ошибка + КонецПопытки; +КонецПроцедуры + +Процедура СложныйМетодСИспользованиемПодробногоПредставленияВнутриИсключения_ОбработкаОшибок(Знач ИмяСобытия, Знач ОписаниеОшибки, Знач Ответ, Знач СсылкаНаДанные = Неопределено) Экспорт + Попытка + Блокировка.Заблокировать(); + Исключение + ТекстСообщения = СтроковыеФункцииКлиентСервер.ПодставитьПараметрыВСтроку( + НСтр("ru = 'Не удалось обработать график работы по причине: + |%2'"), + ОбработкаОшибок.ПодробноеПредставлениеОшибки(ИнформацияОбОшибке())); + + ЗаписьЖурналаРегистрации( + ИмяСобытия, + УровеньЖурналаРегистрации.Ошибка, + , + СсылкаНаДанные, + ТекстСообщения); // не ошибка + КонецПопытки; +КонецПроцедуры + +Процедура СложныйМетодСИспользованиемПодробногоПредставленияВнутриИсключенияВВыражении_ОбработкаОшибок(Знач Выборка, Знач Блокировка) Экспорт + Попытка + Блокировка.Заблокировать(); + Исключение + ТекстСообщения = + НСтр("ru = 'Не удалось установить разделение сеанса. Область данных'") + " = " + + Формат(Выборка.ОбластьДанных, "ЧГ=0") + + Символы.ПС + ОбработкаОшибок.ПодробноеПредставлениеОшибки(ИнформацияОбОшибке()); + + ЗаписьЖурналаРегистрации( + ИмяСобытия, + УровеньЖурналаРегистрации.Ошибка, + , + СсылкаНаДанные, + ТекстСообщения); // не ошибка + + ЗаписьЖурналаРегистрации( + ИмяСобытия, + УровеньОшибки(), + , + СсылкаНаДанные, + ТекстСообщения); // не ошибка + + КонецПопытки; +КонецПроцедуры + +Процедура Метод2_ОбработкаОшибок(Знач СсылкаНаДанные, Знач Блокировка) + Попытка + Блокировка.Заблокировать(); + Исключение + КороткийТекстСообщения = ОбработкаОшибок.КраткоеПредставлениеОшибки(ИнформацияОбОшибке()) + ОписаниеОшибки(); + + ЗаписьЖурналаРегистрации( + ИмяСобытия, + УровеньЖурналаРегистрации.Ошибка, + , + СсылкаНаДанные, + КороткийТекстСообщения); // ошибка + КонецПопытки; +КонецПроцедуры diff --git a/src/test/resources/diagnostics/UseSystemInformationDiagnostic.bsl b/src/test/resources/diagnostics/UseSystemInformationDiagnostic.bsl new file mode 100644 index 00000000000..8148506c721 --- /dev/null +++ b/src/test/resources/diagnostics/UseSystemInformationDiagnostic.bsl @@ -0,0 +1,13 @@ +Функция ТипТекущейПлатформы() Экспорт + СистемнаяИнформация = Новый СистемнаяИнформация; // Range(1, 26, 1, 51) + Возврат СистемнаяИнформация.ТипПлатформы; +КонецФункции + +СистемнаяИнформация = Новый СистемнаяИнформация(); // Range(5, 22, 5, 49) +СистемнаяИнформация = Новый("СистемнаяИнформация"); // Range(6, 22, 6, 50) +СистемнаяИнформация = Новый SystemInfo; // Range(7, 22, 7, 38) +СистемнаяИнформация = Новый("SystemInfo"); // Range(8, 22, 8, 41) +СистемнаяИнформация = Новый("СистемнаяИнформация2"); + +ИмяТипа = "СистемнаяИнформация"; +СистемнаяИнформация = Новый(ИмяТипа); \ No newline at end of file diff --git a/src/test/resources/diagnostics/UsingFindElementByStringDiagnostic.bsl b/src/test/resources/diagnostics/UsingFindElementByStringDiagnostic.bsl index 2f6d4784cac..8b0ac99391e 100644 --- a/src/test/resources/diagnostics/UsingFindElementByStringDiagnostic.bsl +++ b/src/test/resources/diagnostics/UsingFindElementByStringDiagnostic.bsl @@ -30,4 +30,18 @@ А = Справочники.Валюты.Функция( Справочники.Валюты.НайтиПоНаименованию("777") // сработает ); -КонецПроцедуры \ No newline at end of file +КонецПроцедуры + +Процедура Тест3() + + Наименование = "333"; // Пока не сработает + Значение = Документы.Реализация.НайтиПоНомеру(Наименование); + + ОбъектНазначения = Документы.ПередачаТоваровМеждуОрганизациями.НайтиПоНомеру("0000-000001", ТекущаяДата()); // замечание + + Значение3 = БизнесПроцессы.БП1.НайтиПоНомеру(333); // замечание + + А = Документы.Реализация.Функция( + Документы.Реализация.НайтиПоНомеру("333") // замечание + ); +КонецПроцедуры diff --git a/src/test/resources/hover/DescriptionFormatter.bsl b/src/test/resources/hover/DescriptionFormatter.bsl new file mode 100644 index 00000000000..9b4738bf2e6 --- /dev/null +++ b/src/test/resources/hover/DescriptionFormatter.bsl @@ -0,0 +1,3 @@ +Процедура МетодСАннотациямиПараметров(&Повторяемый Парам1, Парам2) Экспорт + +КонецПроцедуры \ No newline at end of file diff --git a/src/test/resources/inlayhints/CognitiveComplexityInlayHintSupplier.bsl b/src/test/resources/inlayhints/CognitiveComplexityInlayHintSupplier.bsl new file mode 100644 index 00000000000..584106879e1 --- /dev/null +++ b/src/test/resources/inlayhints/CognitiveComplexityInlayHintSupplier.bsl @@ -0,0 +1,8 @@ +Процедура ИмяПроцедуры() + Если Истина Тогда + А = 0; + КонецЕсли; +КонецПроцедуры + +Процедура ИмяПроцедуры2() +КонецПроцедуры diff --git a/src/test/resources/inlayhints/CyclomaticComplexityInlayHintSupplier.bsl b/src/test/resources/inlayhints/CyclomaticComplexityInlayHintSupplier.bsl new file mode 100644 index 00000000000..584106879e1 --- /dev/null +++ b/src/test/resources/inlayhints/CyclomaticComplexityInlayHintSupplier.bsl @@ -0,0 +1,8 @@ +Процедура ИмяПроцедуры() + Если Истина Тогда + А = 0; + КонецЕсли; +КонецПроцедуры + +Процедура ИмяПроцедуры2() +КонецПроцедуры diff --git a/src/test/resources/inlayhints/SourceDefinedMethodCallInlayHintSupplier.bsl b/src/test/resources/inlayhints/SourceDefinedMethodCallInlayHintSupplier.bsl new file mode 100644 index 00000000000..c72278111a2 --- /dev/null +++ b/src/test/resources/inlayhints/SourceDefinedMethodCallInlayHintSupplier.bsl @@ -0,0 +1,106 @@ + +&AtClient +Procedure Player1HealthPlus1(Command) + ChangeHealth(Player1, Health1, 1); +EndProcedure + +&AtClient +Procedure Player1HealthPlus5(Command) + ChangeHealth(Player1, Health1, 5); +EndProcedure + +&AtClient +Procedure Player1HealthMinus1(Command) + ChangeHealth(Player1, Health1, -1); +EndProcedure + +&AtClient +Procedure Player1HealthMinus5(Command) + ChangeHealth(Player1, Health1, -5); +EndProcedure + +&AtClient +Procedure Player2HealthPlus1(Command) + ChangeHealth(Player2, Health2, 1); +EndProcedure + +&AtClient +Procedure Player2HealthPlus5(Command) + ChangeHealth(Player2, Health2, 5); +EndProcedure + +&AtClient +Procedure Player2HealthMinus1(Command) + ChangeHealth(Player2, Health2, -1); +EndProcedure + +&AtClient +Procedure Player2HealthMinus5(Command) + ChangeHealth(Player2, Health2, -5); +EndProcedure + +&AtServer +Procedure OnCreateAtServer(Cancel, StandardProcessing) + NewGameAtServer(True); +EndProcedure + +&AtClient +Procedure NewGame(Command) + NewGameAtServer(); +EndProcedure + +&AtServer +Procedure NewGameAtServer(FirstTime = False) + + Health1 = 20; + Health2 = 20; + + If FirstTime Then + Player1 = Catalogs.Players.Player1; + Player2 = Catalogs.Players.Player2; + + Deck1 = Catalogs.Decks.DefaultDeck; + Deck2 = Catalogs.Decks.DefaultDeck; + EndIf; + + // TODO: Move GUI from logic + ThisObject.ChildItems.PlayerWon.Visible = False; + ThisObject.ChildItems.Buttons.Enabled = True; + +EndProcedure + +&AtClient +Procedure ChangeHealth(Player, PlayersHealth, Amount) + + PlayersHealth = PlayersHealth + Amount; + + If PlayersHealth <= 0 Then + + // TODO: rewrite + PlayerWon = ?(Player = Player1, Player2, Player1); + + // TODO: Move GUI from logic + ThisObject.ChildItems.PlayerWon.Visible = True; + ThisObject.ChildItems.PlayerWon.Title = String(PlayerWon) + " won!"; + ThisObject.ChildItems.Buttons.Enabled = False; + + SaveGameStat(PlayerWon); + + EndIf; + +EndProcedure + +&AtServer +Procedure SaveGameStat(PlayerWon) + + NewRecord = InformationRegisters.GameStats.CreateRecordManager(); + NewRecord.Date = CurrentDate(); + NewRecord.Player1 = Player1; + NewRecord.Player2 = Player2; + NewRecord.Deck1 = Deck1; + NewRecord.Deck2 = Deck2; + NewRecord.Won = PlayerWon; + + NewRecord.Write(); + +EndProcedure diff --git "a/src/test/resources/metadata/designer/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Ext/ManagerModule.bsl" "b/src/test/resources/metadata/designer/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Ext/ManagerModule.bsl" index 5dbe084b1dd..9be9b3f25af 100644 --- "a/src/test/resources/metadata/designer/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Ext/ManagerModule.bsl" +++ "b/src/test/resources/metadata/designer/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\2721/Ext/ManagerModule.bsl" @@ -15,7 +15,7 @@ #Область СлужебныеПроцедурыИФункции -Процедура Тест() +Процедура Тест(Параметр) Справочники.Справочник1.ТестЭкспортная(); // Ошибка: Обращение через менеджер избыточно ТестЭкспортная(); diff --git "a/src/test/resources/metadata/designer/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\272\320\241\320\234\320\265\320\275\320\265\320\264\320\266\320\265\321\200\320\276\320\274.xml" "b/src/test/resources/metadata/designer/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\272\320\241\320\234\320\265\320\275\320\265\320\264\320\266\320\265\321\200\320\276\320\274.xml" new file mode 100644 index 00000000000..d0a7c1002cf --- /dev/null +++ "b/src/test/resources/metadata/designer/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\272\320\241\320\234\320\265\320\275\320\265\320\264\320\266\320\265\321\200\320\276\320\274.xml" @@ -0,0 +1,126 @@ + + + + + + cd5d9910-c790-46e8-8c99-a0f38f3f9e39 + b69e7b91-a362-429c-b5b4-39e1fd765840 + + + c3d8d716-ce70-459f-9a75-2b8c77a0194b + e4215019-0558-438e-b225-b0f926f42b8a + + + 604fe1d0-b22f-48a6-8335-c86562ba654c + fa9ac073-8e89-47de-8aab-9a3badb9a894 + + + e2756a94-423f-4fff-ab71-622cd2d99f62 + 23864a50-78d1-48ab-88a6-e3f4d212b34f + + + 227a9ad8-b4aa-4d7d-8cc0-bed15e263277 + d2fae109-dc57-483e-a56a-f2baf0515b86 + + + + СправочникСМенеджером + + + false + HierarchyFoldersAndItems + false + 2 + true + true + + ToItems + 9 + 25 + String + Variable + WholeCatalog + true + true + AsDescription + + Auto + InDialog + false + BothWays + + Catalog.СправочникСМенеджером.StandardAttribute.Description + Catalog.СправочникСМенеджером.StandardAttribute.Code + + Begin + DontUse + Directly + + + + + + + + + + + false + + + Managed + Use + + + + + + Use + Auto + DontUse + false + false + + + + + Реквизит1 + + + + xs:string + + 10 + Variable + + + false + + + + false + + false + false + + + false + + DontCheck + Items + + + Auto + Auto + + + Auto + ForItem + DontIndex + Use + Use + + + + + \ No newline at end of file diff --git "a/src/test/resources/metadata/designer/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\272\320\241\320\234\320\265\320\275\320\265\320\264\320\266\320\265\321\200\320\276\320\274/Ext/ManagerModule.bsl" "b/src/test/resources/metadata/designer/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\272\320\241\320\234\320\265\320\275\320\265\320\264\320\266\320\265\321\200\320\276\320\274/Ext/ManagerModule.bsl" new file mode 100644 index 00000000000..5f282702bb0 --- /dev/null +++ "b/src/test/resources/metadata/designer/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\272\320\241\320\234\320\265\320\275\320\265\320\264\320\266\320\265\321\200\320\276\320\274/Ext/ManagerModule.bsl" @@ -0,0 +1 @@ + \ No newline at end of file diff --git "a/src/test/resources/metadata/designer/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\272\320\241\320\234\320\265\320\275\320\265\320\264\320\266\320\265\321\200\320\276\320\274/Ext/ObjectModule.bsl" "b/src/test/resources/metadata/designer/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\272\320\241\320\234\320\265\320\275\320\265\320\264\320\266\320\265\321\200\320\276\320\274/Ext/ObjectModule.bsl" new file mode 100644 index 00000000000..5f282702bb0 --- /dev/null +++ "b/src/test/resources/metadata/designer/Catalogs/\320\241\320\277\321\200\320\260\320\262\320\276\321\207\320\275\320\270\320\272\320\241\320\234\320\265\320\275\320\265\320\264\320\266\320\265\321\200\320\276\320\274/Ext/ObjectModule.bsl" @@ -0,0 +1 @@ + \ No newline at end of file diff --git "a/src/test/resources/metadata/privilegedModules/CommonModules/\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\2142.xml" "b/src/test/resources/metadata/privilegedModules/CommonModules/\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\2142.xml" new file mode 100644 index 00000000000..fab8cc555db --- /dev/null +++ "b/src/test/resources/metadata/privilegedModules/CommonModules/\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\2142.xml" @@ -0,0 +1,18 @@ + + + + + ОбщийМодуль2 + + + false + false + true + false + false + false + false + DontUse + + + \ No newline at end of file diff --git "a/src/test/resources/metadata/privilegedModules/CommonModules/\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\2142/Ext/Module.bsl" "b/src/test/resources/metadata/privilegedModules/CommonModules/\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\2142/Ext/Module.bsl" new file mode 100644 index 00000000000..291d5ad6c4b --- /dev/null +++ "b/src/test/resources/metadata/privilegedModules/CommonModules/\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\2142/Ext/Module.bsl" @@ -0,0 +1,90 @@ + +/////Описание +///// +///// + +#Область ОписаниеПеременных + + + + +#КонецОбласти + +#Область ПрограммныйИнтерфейс +// Код процедур и функций +#КонецОбласти + +#Область СлужебныйПрограммныйИнтерфейс +// Код процедур и функций +#КонецОбласти + +#Область СлужебныеПроцедурыИФункции +// Код процедур и функций +#КонецОбласти + + +#Region EventHandlers +// Enter code here. +#EndRegion + +#Region Internal +// Enter code here. +#EndRegion + +#Область ОбработчикиСобытийФормы +// Код процедур и функций +#КонецОбласти + +#Область ОбработчикиСобытийЭлементовШапкиФормы +// Код процедур и функций +#КонецОбласти + +#Область ОбработчикиСобытийЭлементовТаблицыФормыИмяТаблицыФормы +// Код процедур и функций +#КонецОбласти + +#Область ОбработчикиКомандФормы +// Код процедур и функций +#КонецОбласти + +#Область ОбработчикиСобытий +// Код процедур и функций +#КонецОбласти + +#Область СлужебныеПроцедурыИФункции +Функция Тест() + РегистрыСведений.РегистрСведений1.УстаревшаяПроцедура(); +КонецФункции + +#КонецОбласти + +Процедура НеУстаревшаяПроцедура() Экспорт + +КонецПроцедуры + +// Устарела. См. НеУстаревшаяПроцедура. +// Процедура - Устаревшая процедура +Процедура УстаревшаяПроцедура() Экспорт + +КонецПроцедуры + +Функция НеУстаревшаяФункция() Экспорт + +КонецФункции + +// Устарела. См. НеУстаревшаяФункция. +// Функция - Устаревшая функция +Функция УстаревшаяФункция() Экспорт + + ПервыйОбщийМодуль.НеУстаревшаяФункция(); + НеУстаревшаяФункция(); + +КонецФункции + +Процедура ВерсионированиеПриЗаписи(Источник, Отказ) Экспорт + +КонецПроцедуры + +Процедура РегистрацияИзмененийПередУдалением(Источник, Отказ) + +КонецПроцедуры diff --git "a/src/test/resources/metadata/privilegedModules/CommonModules/\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\2143.xml" "b/src/test/resources/metadata/privilegedModules/CommonModules/\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\2143.xml" new file mode 100644 index 00000000000..c3d3f9e69b1 --- /dev/null +++ "b/src/test/resources/metadata/privilegedModules/CommonModules/\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\2143.xml" @@ -0,0 +1,18 @@ + + + + + ОбщийМодуль3 + + + false + false + true + false + false + false + false + DontUse + + + \ No newline at end of file diff --git "a/src/test/resources/metadata/privilegedModules/CommonModules/\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\2143/Ext/Module.bsl" "b/src/test/resources/metadata/privilegedModules/CommonModules/\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\2143/Ext/Module.bsl" new file mode 100644 index 00000000000..291d5ad6c4b --- /dev/null +++ "b/src/test/resources/metadata/privilegedModules/CommonModules/\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\2143/Ext/Module.bsl" @@ -0,0 +1,90 @@ + +/////Описание +///// +///// + +#Область ОписаниеПеременных + + + + +#КонецОбласти + +#Область ПрограммныйИнтерфейс +// Код процедур и функций +#КонецОбласти + +#Область СлужебныйПрограммныйИнтерфейс +// Код процедур и функций +#КонецОбласти + +#Область СлужебныеПроцедурыИФункции +// Код процедур и функций +#КонецОбласти + + +#Region EventHandlers +// Enter code here. +#EndRegion + +#Region Internal +// Enter code here. +#EndRegion + +#Область ОбработчикиСобытийФормы +// Код процедур и функций +#КонецОбласти + +#Область ОбработчикиСобытийЭлементовШапкиФормы +// Код процедур и функций +#КонецОбласти + +#Область ОбработчикиСобытийЭлементовТаблицыФормыИмяТаблицыФормы +// Код процедур и функций +#КонецОбласти + +#Область ОбработчикиКомандФормы +// Код процедур и функций +#КонецОбласти + +#Область ОбработчикиСобытий +// Код процедур и функций +#КонецОбласти + +#Область СлужебныеПроцедурыИФункции +Функция Тест() + РегистрыСведений.РегистрСведений1.УстаревшаяПроцедура(); +КонецФункции + +#КонецОбласти + +Процедура НеУстаревшаяПроцедура() Экспорт + +КонецПроцедуры + +// Устарела. См. НеУстаревшаяПроцедура. +// Процедура - Устаревшая процедура +Процедура УстаревшаяПроцедура() Экспорт + +КонецПроцедуры + +Функция НеУстаревшаяФункция() Экспорт + +КонецФункции + +// Устарела. См. НеУстаревшаяФункция. +// Функция - Устаревшая функция +Функция УстаревшаяФункция() Экспорт + + ПервыйОбщийМодуль.НеУстаревшаяФункция(); + НеУстаревшаяФункция(); + +КонецФункции + +Процедура ВерсионированиеПриЗаписи(Источник, Отказ) Экспорт + +КонецПроцедуры + +Процедура РегистрацияИзмененийПередУдалением(Источник, Отказ) + +КонецПроцедуры diff --git "a/src/test/resources/metadata/privilegedModules/CommonModules/\320\237\321\200\320\270\320\262\320\270\320\273\320\265\320\263\320\270\321\200\320\276\320\262\320\260\320\275\320\275\321\213\320\271\320\234\320\276\320\264\321\203\320\273\321\2141.xml" "b/src/test/resources/metadata/privilegedModules/CommonModules/\320\237\321\200\320\270\320\262\320\270\320\273\320\265\320\263\320\270\321\200\320\276\320\262\320\260\320\275\320\275\321\213\320\271\320\234\320\276\320\264\321\203\320\273\321\2141.xml" new file mode 100644 index 00000000000..24a9c1248c1 --- /dev/null +++ "b/src/test/resources/metadata/privilegedModules/CommonModules/\320\237\321\200\320\270\320\262\320\270\320\273\320\265\320\263\320\270\321\200\320\276\320\262\320\260\320\275\320\275\321\213\320\271\320\234\320\276\320\264\321\203\320\273\321\2141.xml" @@ -0,0 +1,18 @@ + + + + + ПривилегированныйМодуль1 + + + false + false + true + false + false + false + true + DontUse + + + \ No newline at end of file diff --git "a/src/test/resources/metadata/privilegedModules/CommonModules/\320\237\321\200\320\270\320\262\320\270\320\273\320\265\320\263\320\270\321\200\320\276\320\262\320\260\320\275\320\275\321\213\320\271\320\234\320\276\320\264\321\203\320\273\321\2141/Ext/Module.bsl" "b/src/test/resources/metadata/privilegedModules/CommonModules/\320\237\321\200\320\270\320\262\320\270\320\273\320\265\320\263\320\270\321\200\320\276\320\262\320\260\320\275\320\275\321\213\320\271\320\234\320\276\320\264\321\203\320\273\321\2141/Ext/Module.bsl" new file mode 100644 index 00000000000..f7d88c16cfd --- /dev/null +++ "b/src/test/resources/metadata/privilegedModules/CommonModules/\320\237\321\200\320\270\320\262\320\270\320\273\320\265\320\263\320\270\321\200\320\276\320\262\320\260\320\275\320\275\321\213\320\271\320\234\320\276\320\264\321\203\320\273\321\2141/Ext/Module.bsl" @@ -0,0 +1,23 @@ +#Область ПрограммныйИнтерфейс + +Функция ПубличнаяФункция() Экспорт + +КонецФункции + +Процедура ПубличнаяПроцедура() Экспорт + +КонецПроцедуры + +#КонецОбласти + +#Область СлужебныеПроцедурыИФункции + +Функция ПриватнаяФункция() + Значение = ПубличнаяФункция(); +КонецФункции + +Процедура ПриватнаяПроцедура() + ПубличнаяПроцедура(); +КонецПроцедуры + +#КонецОбласти diff --git a/src/test/resources/metadata/privilegedModules/Configuration.xml b/src/test/resources/metadata/privilegedModules/Configuration.xml new file mode 100644 index 00000000000..35e55b12302 --- /dev/null +++ b/src/test/resources/metadata/privilegedModules/Configuration.xml @@ -0,0 +1,209 @@ + + + + + + 9cd510cd-abfc-11d4-9434-004095e12fc7 + f47a8858-7778-47e9-9a9f-4eb4daedec56 + + + 9fcd25a0-4822-11d4-9414-008048da11f9 + 38996962-4abe-4c75-b3fe-8d2fa95cf83c + + + e3687481-0a87-462c-a166-9f34594f9bba + 5af4c67d-90e8-46b7-bff3-009df1043aee + + + 9de14907-ec23-4a07-96f0-85521cb6b53b + c519e804-03e1-428c-b447-9d7682802dcf + + + 51f2d5d8-ea4d-4064-8892-82951750031e + 842dca23-a50c-4a90-99dc-d0b8fa46d6bd + + + e68182ea-4237-4383-967f-90c1e3370bc7 + 1ef3f7d7-1891-4c7e-80b2-497689df7a80 + + + fb282519-d103-4dd3-bc12-cb271d631dfc + d625341b-aef8-4049-888c-681733b130fb + + + + privilegedModules + + + + Version8_3_18 + ManagedApplication + + PlatformApplication + + Russian + + + + + false + false + false + + + + + + + + + + + + + + + + + + + + Biometrics + true + + + Location + false + + + BackgroundLocation + false + + + BluetoothPrinters + false + + + WiFiPrinters + false + + + Contacts + false + + + Calendars + false + + + PushNotifications + false + + + LocalNotifications + false + + + InAppPurchases + false + + + PersonalComputerFileExchange + false + + + Ads + false + + + NumberDialing + false + + + CallProcessing + false + + + CallLog + false + + + AutoSendSMS + false + + + ReceiveSMS + false + + + SMSLog + false + + + Camera + false + + + Microphone + false + + + MusicLibrary + false + + + PictureAndVideoLibraries + false + + + AudioPlaybackAndVibration + false + + + BackgroundAudioPlaybackAndVibration + false + + + InstallPackages + false + + + OSBackup + true + + + ApplicationUsageStatistics + false + + + BarcodeScanning + false + + + + + Normal + + + Language.Русский + + + + + + Managed + NotAutoFree + DontUse + DontUse + Taxi + Version8_3_18 + + + + Русский + ПривилегированныйМодуль1 + ОбщийМодуль2 + ОбщийМодуль3 + + + \ No newline at end of file diff --git "a/src/test/resources/metadata/privilegedModules/Languages/\320\240\321\203\321\201\321\201\320\272\320\270\320\271.xml" "b/src/test/resources/metadata/privilegedModules/Languages/\320\240\321\203\321\201\321\201\320\272\320\270\320\271.xml" new file mode 100644 index 00000000000..a46e619fe47 --- /dev/null +++ "b/src/test/resources/metadata/privilegedModules/Languages/\320\240\321\203\321\201\321\201\320\272\320\270\320\271.xml" @@ -0,0 +1,16 @@ + + + + + Русский + + + ru + Русский + + + + ru + + + \ No newline at end of file diff --git "a/src/test/resources/metadata/subSystemFilter/CommonModules/\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\2141/Ext/Module.bin" "b/src/test/resources/metadata/subSystemFilter/CommonModules/\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\2141/Ext/Module.bin" new file mode 100644 index 00000000000..e69de29bb2d diff --git "a/src/test/resources/metadata/subSystemFilter/CommonModules/\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\2142/Ext/Module.bsl" "b/src/test/resources/metadata/subSystemFilter/CommonModules/\320\236\320\261\321\211\320\270\320\271\320\234\320\276\320\264\321\203\320\273\321\2142/Ext/Module.bsl" new file mode 100644 index 00000000000..e69de29bb2d diff --git a/src/test/resources/providers/callHierarchy.bsl b/src/test/resources/providers/callHierarchy.bsl index e6a6a51e145..4bbae4ff66d 100644 --- a/src/test/resources/providers/callHierarchy.bsl +++ b/src/test/resources/providers/callHierarchy.bsl @@ -5,6 +5,8 @@ КонецПроцедуры Функция ПерваяФункция() + Перем А; + Б = 1; ВтораяПроцедура(); ВтораяФункция(); ВтораяПроцедура(); diff --git a/src/test/resources/providers/inlayHints.bsl b/src/test/resources/providers/inlayHints.bsl new file mode 100644 index 00000000000..c72278111a2 --- /dev/null +++ b/src/test/resources/providers/inlayHints.bsl @@ -0,0 +1,106 @@ + +&AtClient +Procedure Player1HealthPlus1(Command) + ChangeHealth(Player1, Health1, 1); +EndProcedure + +&AtClient +Procedure Player1HealthPlus5(Command) + ChangeHealth(Player1, Health1, 5); +EndProcedure + +&AtClient +Procedure Player1HealthMinus1(Command) + ChangeHealth(Player1, Health1, -1); +EndProcedure + +&AtClient +Procedure Player1HealthMinus5(Command) + ChangeHealth(Player1, Health1, -5); +EndProcedure + +&AtClient +Procedure Player2HealthPlus1(Command) + ChangeHealth(Player2, Health2, 1); +EndProcedure + +&AtClient +Procedure Player2HealthPlus5(Command) + ChangeHealth(Player2, Health2, 5); +EndProcedure + +&AtClient +Procedure Player2HealthMinus1(Command) + ChangeHealth(Player2, Health2, -1); +EndProcedure + +&AtClient +Procedure Player2HealthMinus5(Command) + ChangeHealth(Player2, Health2, -5); +EndProcedure + +&AtServer +Procedure OnCreateAtServer(Cancel, StandardProcessing) + NewGameAtServer(True); +EndProcedure + +&AtClient +Procedure NewGame(Command) + NewGameAtServer(); +EndProcedure + +&AtServer +Procedure NewGameAtServer(FirstTime = False) + + Health1 = 20; + Health2 = 20; + + If FirstTime Then + Player1 = Catalogs.Players.Player1; + Player2 = Catalogs.Players.Player2; + + Deck1 = Catalogs.Decks.DefaultDeck; + Deck2 = Catalogs.Decks.DefaultDeck; + EndIf; + + // TODO: Move GUI from logic + ThisObject.ChildItems.PlayerWon.Visible = False; + ThisObject.ChildItems.Buttons.Enabled = True; + +EndProcedure + +&AtClient +Procedure ChangeHealth(Player, PlayersHealth, Amount) + + PlayersHealth = PlayersHealth + Amount; + + If PlayersHealth <= 0 Then + + // TODO: rewrite + PlayerWon = ?(Player = Player1, Player2, Player1); + + // TODO: Move GUI from logic + ThisObject.ChildItems.PlayerWon.Visible = True; + ThisObject.ChildItems.PlayerWon.Title = String(PlayerWon) + " won!"; + ThisObject.ChildItems.Buttons.Enabled = False; + + SaveGameStat(PlayerWon); + + EndIf; + +EndProcedure + +&AtServer +Procedure SaveGameStat(PlayerWon) + + NewRecord = InformationRegisters.GameStats.CreateRecordManager(); + NewRecord.Date = CurrentDate(); + NewRecord.Player1 = Player1; + NewRecord.Player2 = Player2; + NewRecord.Deck1 = Deck1; + NewRecord.Deck2 = Deck2; + NewRecord.Won = PlayerWon; + + NewRecord.Write(); + +EndProcedure diff --git a/src/test/resources/references/AnnotationReferenceFinder.os b/src/test/resources/references/AnnotationReferenceFinder.os new file mode 100644 index 00000000000..42d905391dc --- /dev/null +++ b/src/test/resources/references/AnnotationReferenceFinder.os @@ -0,0 +1,32 @@ +&ТестоваяАннотация(ВторойПараметр = "ТестовоеЗначение", "ТестовоеЗначение2") +Перем ТестоваяПеременная; + +&ТестоваяАннотация2 +Перем ТестоваяПеременная2; + +&ТестоваяАннотация("Строка") +&ТестоваяАннотация( + "Многострочная + |Строка" +) +&ТестоваяАннотация(32) +&ТестоваяАннотация(-32) +&ТестоваяАннотация(Истина) +&ТестоваяАннотация('20200101') +&ТестоваяАннотация(Неопределено) +&ТестоваяАннотация(NULL) +&ТестоваяАннотация( + 42, + -42, + "Строка", + "Многострочная + |Строка", + Истина, + '20200101', + Неопределено, + NULL +) +Перем ТестоваяПеременная3; + +Процедура ПриСозданииОбъекта() +КонецПроцедуры \ No newline at end of file diff --git "a/src/test/resources/references/annotations/\320\242\320\265\321\201\321\202\320\276\320\262\320\260\321\217\320\220\320\275\320\275\320\276\321\202\320\260\321\206\320\270\321\217.os" "b/src/test/resources/references/annotations/\320\242\320\265\321\201\321\202\320\276\320\262\320\260\321\217\320\220\320\275\320\275\320\276\321\202\320\260\321\206\320\270\321\217.os" new file mode 100644 index 00000000000..698dc1aa070 --- /dev/null +++ "b/src/test/resources/references/annotations/\320\242\320\265\321\201\321\202\320\276\320\262\320\260\321\217\320\220\320\275\320\275\320\276\321\202\320\260\321\206\320\270\321\217.os" @@ -0,0 +1,9 @@ +// Описание +// +// Параметры: +// Значение - Строка - Значение аннотации +// ВторойПараметр - Строка - Второе значение аннотации +// +&Аннотация("ТестоваяАннотация") +Процедура ПриСозданииОбъекта(Значение, ВторойПараметр) +КонецПроцедуры \ No newline at end of file diff --git "a/src/test/resources/references/annotations/\320\242\320\265\321\201\321\202\320\276\320\262\320\260\321\217\320\220\320\275\320\275\320\276\321\202\320\260\321\206\320\270\321\2172.os" "b/src/test/resources/references/annotations/\320\242\320\265\321\201\321\202\320\276\320\262\320\260\321\217\320\220\320\275\320\275\320\276\321\202\320\260\321\206\320\270\321\2172.os" new file mode 100644 index 00000000000..1bbb37f66e2 --- /dev/null +++ "b/src/test/resources/references/annotations/\320\242\320\265\321\201\321\202\320\276\320\262\320\260\321\217\320\220\320\275\320\275\320\276\321\202\320\260\321\206\320\270\321\2172.os" @@ -0,0 +1,3 @@ +&Аннотация("ТестоваяАннотация2") +Процедура ПриСозданииОбъекта() +КонецПроцедуры \ No newline at end of file diff --git a/src/test/resources/suppliers/extractStructureConstructor.bsl b/src/test/resources/suppliers/extractStructureConstructor.bsl new file mode 100644 index 00000000000..31ed8f64068 --- /dev/null +++ b/src/test/resources/suppliers/extractStructureConstructor.bsl @@ -0,0 +1,18 @@ + +Структура = Новый Структура("а, б, в", а, б, в); + + Структура = Новый Структура("а, б, в", а, б, в); + +СтруктураПолей = Новый Структура("Измерения, Реквизиты, Ресурсы", + Новый Структура("СтрокаПолей", ""), + Новый Структура("СтрокаПолей", ""), + Новый Структура("СтрокаПолей", "")); + +СтрокиВопроса = СтрокаДерева.СоставКомплексногоВопроса.НайтиСтроки(Новый Структура("ЭлементарныйВопрос", ВыборкаВопрос.ЭлементарныйВопрос)); + +Структура = Новый Массив(); +Структура = Новый Структура; +Структура = Новый Структура(); +Структура = Новый Структура(Идентификатор); + +Чтото.Поле = Новый Структура("а, б, в", а, б, в);