Compare commits

..

68 Commits

Author SHA1 Message Date
Dandaedre 45aa8928b1
test: restore bridge coverage gate
Rust CI vsg-bridge-ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head This commit looks good Details
2026-10-04 01:30:54 +02:00
Dandaedre 0c296d5070
Document VSG fork installation updates
Rust CI vsg-bridge-ls failed CI.
MadGobblins/vsg-bridge-ls/pipeline/head There was a failure building this commit Details
2026-10-03 22:11:46 +02:00
Dandaedre 97d9d717a5
Streamline README advanced usage 2026-10-03 22:01:29 +02:00
Dandaedre 5eff84c575
Report unlocated VSG analysis failures
Rust CI vsg-bridge-ls failed CI.
MadGobblins/vsg-bridge-ls/pipeline/head There was a failure building this commit Details
2026-10-03 21:55:07 +02:00
Dandaedre 8222882fb1
Allow hover suppression in multi-server setups
Rust CI vsg-bridge-ls failed CI.
MadGobblins/vsg-bridge-ls/pipeline/head There was a failure building this commit Details
2026-10-03 21:45:53 +02:00
Dandaedre 60c30ff267
Generate project configuration from CLI options 2026-10-03 21:37:09 +02:00
Dandaedre d0e755cd6a
Add editor-friendly diagnostic severity mapping 2026-10-03 21:22:05 +02:00
Dandaedre 8008534dfd
Replace stale findings with syntax failures
Rust CI vsg-bridge-ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head This commit looks good Details
2026-10-03 21:16:34 +02:00
Dandaedre 2f88b3187e
Contain malformed diagnostics and verify non-destructive fixes
Rust CI vsg-bridge-ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head This commit looks good Details
2026-10-03 15:52:24 +02:00
Dandaedre 9fd8a07b2a
Prefer prebuilt bridge installation
Rust CI vsg-bridge-ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head This commit looks good Details
2026-10-03 15:07:21 +02:00
Dandaedre aa80d3fb30
Expand LLM development disclosure
Rust CI vsg-bridge-ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head This commit looks good Details
2026-10-03 14:41:22 +02:00
Dandaedre 41123f5d77
Document LLM-assisted development 2026-10-03 14:37:03 +02:00
Dandaedre da279289c9
Prepare 0.3.2 release candidate 3
Rust CI vsg-bridge-ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head This commit looks good Details
2026-10-03 04:11:37 +02:00
Dandaedre 039a7d7431
Expand protocol error coverage
Rust CI vsg-bridge-ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head This commit looks good Details
2026-10-03 04:09:59 +02:00
Dandaedre df7e8a0049
Fix Windows release builds
Rust CI vsg-bridge-ls failed CI.
MadGobblins/vsg-bridge-ls/pipeline/head There was a failure building this commit Details
2026-10-03 04:03:17 +02:00
Dandaedre c8444c5066
Prepare 0.3.2 release candidate
Rust CI vsg-bridge-ls failed CI.
MadGobblins/vsg-bridge-ls/pipeline/head There was a failure building this commit Details
2026-10-03 03:24:31 +02:00
Dandaedre 49d0eb6104
Add layered bridge configuration 2026-10-03 03:20:57 +02:00
Dandaedre 94ef396160
Clarify debug mode help 2026-10-03 03:04:57 +02:00
Dandaedre dd9aad2b36
Add hover debug mode and gate rule fixes 2026-10-03 03:04:01 +02:00
Dandaedre 1c8bd9ab09
Make correction actions lazy
Rust CI vsg-bridge-ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head This commit looks good Details
2026-10-03 02:54:00 +02:00
Dandaedre 7a63ab6a01
Add opt-in bridge debug information
Rust CI vsg-bridge-ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head This commit looks good Details
2026-10-03 02:39:36 +02:00
Dandaedre f2176b9238
Support Helix grouped actions and visible links 2026-10-03 02:33:11 +02:00
Dandaedre 473e0ae0b9
Make VSG failures editor-safe 2026-10-03 02:20:42 +02:00
Dandaedre 841695e30c
Rename the installed bridge executable 2026-10-03 02:12:19 +02:00
Dandaedre fa486c61ae
Release bridge milestone 0.2.0 2026-10-03 01:39:53 +02:00
Dandaedre 387ea86088
Verify fix-all clears showcase findings 2026-10-03 01:39:29 +02:00
Dandaedre e0f64fbb67
Clear diagnostics before opening lint results 2026-10-03 01:38:38 +02:00
Dandaedre aa2763d739
Provide LSP document formatting 2026-10-03 01:35:21 +02:00
Dandaedre 02dae2202b
Exercise shutdown cleanup over LSP
Rust CI vsg_bridge_ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head This commit looks good Details
2026-10-03 01:16:04 +02:00
Dandaedre 4e4af0540d
Clear diagnostics during shutdown 2026-10-03 01:15:14 +02:00
Dandaedre 9e1ecb29cd
Clarify formatter severity behavior 2026-10-03 01:15:03 +02:00
Dandaedre 0c25782c53
Clear stale diagnostics on save
Rust CI vsg_bridge_ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head This commit looks good Details
2026-10-03 00:50:16 +02:00
Dandaedre 4c8e8d2c09
Add experimental multi-rule line fixes 2026-10-03 00:49:20 +02:00
Dandaedre 0547f5f671
Add VSG correction actions 2026-10-03 00:44:40 +02:00
Dandaedre c8d500dc24
Present VSG rule documentation 2026-10-03 00:33:06 +02:00
Dandaedre 11588eddb7
Consume versioned VSG diagnostics 2026-10-03 00:28:46 +02:00
Dandaedre 5e5a71e39f
Center badge text vertically
Rust CI vsg_bridge_ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head This commit looks good Details
2026-10-03 00:19:08 +02:00
Dandaedre 4d78f5e6cf
Fix version badge rendering on FreeBSD
Rust CI vsg_bridge_ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head This commit looks good Details
2026-10-02 23:59:26 +02:00
Dandaedre 4010a58a73
Approve the scoped fix interface
Rust CI vsg_bridge_ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head There was a failure building this commit Details
2026-10-02 23:51:43 +02:00
Dandaedre e570db4d8e
Publish badges after failed builds 2026-10-02 23:50:08 +02:00
Dandaedre ddfb814301
Document the VSG bridge interface 2026-10-02 23:46:24 +02:00
Dandaedre 5a3e651ccb
Remove local badge snapshots 2026-10-02 23:45:15 +02:00
Dandaedre 3b5fd26027
Publish CI test status badge 2026-10-02 23:43:54 +02:00
Dandaedre 187209442a
Generate version badge in CI
Rust CI vsg_bridge_ls failed CI.
MadGobblins/vsg-bridge-ls/pipeline/head There was a failure building this commit Details
2026-10-02 23:39:46 +02:00
Dandaedre 4f2a4d7b81
Retain only the coverage badge 2026-10-02 23:28:11 +02:00
Dandaedre ee85e981aa
Publish only the current coverage badge 2026-10-02 23:26:05 +02:00
Dandaedre 971dbf31a5
Make coverage permissions portable
Rust CI vsg_bridge_ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head This commit looks good Details
2026-10-02 23:08:16 +02:00
Dandaedre fbf70bf6a5
Publish web-readable coverage reports
Rust CI vsg_bridge_ls failed CI.
MadGobblins/vsg-bridge-ls/pipeline/head There was a failure building this commit Details
2026-10-02 22:55:32 +02:00
Dandaedre 6bacbe26db
Create coverage publication root
Rust CI vsg_bridge_ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head This commit looks good Details
2026-10-02 22:45:56 +02:00
Dandaedre fad71741ec
Remove unintended hardening document 2026-10-02 22:41:21 +02:00
Dandaedre cc2d51eb02
Stabilize subprocess tests on FreeBSD
Rust CI vsg_bridge_ls failed CI.
MadGobblins/vsg-bridge-ls/pipeline/head There was a failure building this commit Details
2026-10-02 22:34:15 +02:00
Dandaedre e07be46ed3
Add repository status badges
Rust CI vsg_bridge_ls failed CI.
MadGobblins/vsg-bridge-ls/pipeline/head There was a failure building this commit Details
2026-10-02 21:49:44 +02:00
Dandaedre 67c0b86b22
Fix Jenkins coverage parsing 2026-10-02 21:46:20 +02:00
Dandaedre b220546800
Add Cargo dependency policy gates 2026-10-02 21:45:16 +02:00
Dandaedre eade00b5b1
Publish coverage through assets mount
MadGobblins/vsg-bridge-ls/pipeline/head There was a failure building this commit Details
2026-10-02 21:39:27 +02:00
Dandaedre 0b052b8561
Document and test LSP behavior
MadGobblins/vsg-bridge-ls/pipeline/head There was a failure building this commit Details
2026-10-02 21:27:44 +02:00
Dandaedre 486cbf7e44
Pin Rust compatibility and publish coverage 2026-10-02 21:08:47 +02:00
Dandaedre 5bec60dfe4
Make setup documentation self-contained 2026-10-02 20:48:32 +02:00
Dandaedre a843a94c96 Update Gitea organization URLs
Rust CI vsg_bridge_ls passed CI.
MadGobblins/vsg-bridge-ls/pipeline/head This commit looks good Details
2026-10-02 20:31:08 +02:00
Dandaedre b2c0054a20 Document installation and package publishing 2026-10-02 20:25:06 +02:00
Dandaedre 286630747b Add Jenkinsfile
Dandaedre/vsg_bridge_ls/pipeline/head This commit looks good Details
Rust CI vsg_bridge_ls passed CI.
MadGobblins/vsg_bridge_ls/pipeline/head This commit looks good Details
2026-09-13 21:48:05 +02:00
Dandaedre cce78b06a7 Update README.md 2025-01-10 12:10:38 +01:00
Dandaedre 526ca5edef Adds a line calculation and the beggining of string diff and parsing 2024-11-23 04:53:06 -06:00
Dandaedre 00ab1da717 Edits the readme to be on par with the latest changes on the fork 2024-11-23 00:06:03 -06:00
Dandaedre a85d811479 Fixes a mistake on the install command for the formatter and updates the readme 2024-11-22 04:18:10 -06:00
Dandaedre 5c70d114a2 Adds guidelines for autoformatting 2024-11-22 00:53:42 -06:00
Dandaedre a12912a8a8 Adds -ap to process all lints 2024-11-21 08:33:33 -06:00
Dandaedre 52ad5e459e Cleanups all clippy 2024-11-21 07:28:02 -06:00
46 changed files with 8762 additions and 234 deletions

2
.cargo/config.toml Normal file
View File

@ -0,0 +1,2 @@
[resolver]
incompatible-rust-versions = "fallback"

12
.gitignore vendored
View File

@ -3,10 +3,13 @@
# will have compiled files and executables
debug/
target/
coverage/
dist/
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock
# Generated locally by Cargo Tarpaulin.
/lcov.info
/tarpaulin-report.html
/tarpaulin-report.json
# These are backup files generated by rustfmt
**/*.rs.bk
@ -15,4 +18,5 @@ Cargo.lock
*.pdb
venv/
.cargo/
.cargo/*
!.cargo/config.toml

1137
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,23 +1,33 @@
[package]
name = "vsg_bridge_ls"
name = "vsg-bridge-ls"
description = "A very featureless VSG to lsp bridge"
version = "0.1.0"
version = "0.3.6-rc.1"
edition = "2021"
rust-version = "1.85.1"
categories =["developement-tools"]
license = "LGPL-2.0-only"
keywords = ["lsp", "bridge"]
repository = "https://proxy.dandaedre.com/gitea/MadGobblins/vsg-bridge-ls"
authors = ["dandaedre"]
[package.metadata.binstall]
pkg-url = "{ repo }/releases/download/v{ version }/{ name }-{ target }-v{ version }.tgz"
pkg-fmt = "tgz"
bin-dir = "{ name }-{ target }-v{ version }/{ bin }{ binary-ext }"
[dependencies]
anyhow = "1.0.93"
async-tungstenite = { version = "0.28.0", features = ["tokio", "tokio-runtime"] }
clap = { version = "4.5.21", features = ["derive"] }
once_cell = "1.20.2"
regex = "1.11.1"
serde = { version = "1.0.215", features = ["derive"] }
serde_json = "1.0.133"
tokio = { version = "1.41.1", features = ["default", "io-std", "io-util", "macros", "rt-multi-thread", "tokio-macros"] }
tokio-macros = "2.4.0"
tokio-utils = "0.1.2"
toml = "0.8.19"
tokio = { version = "1.41.1", features = ["io-std", "io-util", "macros", "process", "rt-multi-thread", "sync", "time"] }
tower-lsp = "0.20.0"
tracing-subscriber = "0.3.18"
ws_stream_tungstenite = { version = "0.14.0", features = ["tokio_io"] }
[dev-dependencies]
futures = "0.3.31"
tower = { version = "0.4.13", features = ["util"] }
[profile.dev]
debug = 0

15
Cross.toml Normal file
View File

@ -0,0 +1,15 @@
[build]
[build.env]
passthrough = ["RUSTUP_TOOLCHAIN"]
[target]
[target.x86_64-unknown-linux-musl]
image = "ghcr.io/cross-rs/x86_64-unknown-linux-musl:main"
[target.aarch64-unknown-linux-musl]
image = "ghcr.io/cross-rs/aarch64-unknown-linux-musl:main"
[target.x86_64-pc-windows-gnu]
image = "ghcr.io/cross-rs/x86_64-pc-windows-gnu:main"

96
DISCLOSURE.md Normal file
View File

@ -0,0 +1,96 @@
# Authorship, LLM Use, and Safety Disclosure
This document explains how `vsg-bridge-ls` was developed, where an LLM was
used, what the project tests, and which actions can affect source code. It is a
process and risk disclosure, not a warranty or a substitute for project review.
## Authorship
The project idea, requirements, and first working bridge were created by
Dandaedre. The human maintainer decides the project's scope, evaluates its
behavior, and accepts releases. The underlying VSG parser, rules, and formatter
come from VSG and its upstream author and contributors.
A substantial part of the bridge's later Rust implementation, LSP and JSON
protocol hardening, automated tests, CI, packaging, and documentation was
written or refined with an LLM coding assistant under maintainer direction.
Development has been iterative, so the repository does not claim reliable
line-by-line attribution between human-written and LLM-assisted code. Git
history remains the record of when each change was reviewed and accepted into
the project.
## What happens at runtime
The distributed language server contains no LLM and does not contact an LLM
service. For normal diagnostics it:
1. receives the current VHDL buffer from the editor;
2. passes that text through standard input to the locally installed VSG
executable;
3. validates VSG's diagnostic JSON; and
4. publishes LSP diagnostics, hover text, and available actions.
That path is observational. JSON contains diagnostic and rule metadata
collected from VSG's analysis; producing or reading it cannot alter the VHDL,
change its formatting, or write the source file. Source text is sent to the
local VSG process, not to an LLM or a project-operated network service. The
optional documentation action may ask the editor to open a public rule URL,
but it is disabled unless explicitly allowed.
Formatting and fixes have a different boundary. An editor formatting request,
`source.fixAll.vsg`, or an enabled per-rule action asks VSG to produce corrected
text. The bridge then returns or requests a versioned edit, which the editor may
apply to its in-memory buffer. These actions are explicit unless the user has
configured the editor to run them automatically, such as on save.
## What is tested
The automated suite covers:
- LSP initialization, shutdown, synchronization, and diagnostic clearing;
- use of unsaved in-memory text and suppression of stale results;
- JSON schema, metadata, severity, URL, and line-range validation;
- syntax-error location, stale-warning removal, and correction suppression;
- whole-document analysis errors when VSG cannot provide a safe location;
- default severity demotion and opt-in strict severity mapping;
- safe project-configuration generation without overwriting existing files;
- hover capability suppression for multi-language-server editor setups;
- ASCII, Unicode, UTF-16 positions, CRLF, empty lines, and document boundaries;
- missing, failing, stalled, or non-UTF-8 VSG subprocesses;
- formatting, whole-document fixes, scoped fixes, no-op edits, and concurrent
document changes;
- feature gating for experimental fixes, browser actions, and debug output; and
- deterministic line-edit behavior over examples and bounded generated cases.
CI checks formatting, compilation on the declared minimum Rust version and
current stable Rust, tests, Clippy warnings, dependency policy and known
advisories, and a 90% line-coverage floor. Most tests use an injected or fake
VSG runner for repeatability; an opt-in test also exercises the packaged VSG
process boundary.
These checks demonstrate the tested cases only. They are not formal
verification and do not prove that every editor, platform, VSG configuration,
or VHDL input is handled correctly. Helix is the actively maintained editor
integration; Vim and VSCodium instructions are best-effort.
## Risk by operation
| Operation | Source-change risk | Main remaining risk |
| --- | --- | --- |
| Diagnostics and hover | None by design | A bug may omit, duplicate, or misplace a finding. |
| Debug information | None by design | Metadata may reveal local paths or process details; source text and environment variables are intentionally excluded. |
| Open documentation | None to VHDL | When enabled, the editor may open an external HTTPS URL. |
| Format or fix all | Intentionally changes the editor buffer | A formatter defect or unexpected configuration may produce an unwanted edit. |
| Experimental per-rule or grouped fix | Intentionally changes the editor buffer | VSG phases can move findings between lines, so a scoped selection may not behave as expected. |
Document-version checks, protocol validation, feature gates, and conservative
whole-line or whole-document edits reduce these risks. They cannot establish
that a formatting change preserves the intended hardware behavior.
Treat the configured VSG executable, configuration files, and Python local
rules as trusted inputs. Local rules are executable code in the VSG process and
are outside the bridge's security boundary.
For important or safety-critical HDL, keep work in version control, inspect
every applied edit, and run the project's normal simulation, synthesis,
linting, and review process before accepting a change.

318
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,318 @@
// Add this webhook in Gitea:
// http://192.168.1.37:8080/gitea-webhook/post
pipeline {
agent { label 'rust_nodocker' }
environment {
CARGO_TERM_COLOR = 'never'
RUST_BACKTRACE = '1'
MSRV = '1.85.1'
CARGO_TARPAULIN_VERSION = '0.37.5'
CARGO_AUDIT_VERSION = '0.22.2'
CARGO_DENY_VERSION = '0.20.2'
BADGE_PUBLISH_ROOT = '/mnt/assets/coverage'
}
stages {
stage('Checkout') {
steps {
checkout scm
sh '''
set -eu
git submodule sync --recursive
git submodule update --init --recursive
'''
}
}
stage('Setup Rust') {
steps {
sh '''
set -eu
if ! command -v rustup >/dev/null 2>&1; then
echo "ERROR: rustup is not installed on this worker." >&2
exit 1
fi
rustup toolchain install stable \
--profile minimal \
--component rustfmt \
--component clippy \
--component llvm-tools-preview
rustup toolchain install "${MSRV}" \
--profile minimal
rustup default stable
echo
rustc --version
cargo --version
installed_tarpaulin=$(cargo tarpaulin --version 2>/dev/null || true)
if [ "${installed_tarpaulin}" != "cargo-tarpaulin-tarpaulin ${CARGO_TARPAULIN_VERSION}" ]; then
cargo install cargo-tarpaulin \
--locked \
--version "${CARGO_TARPAULIN_VERSION}"
fi
installed_audit=$(cargo audit --version 2>/dev/null || true)
if [ "${installed_audit}" != "cargo-audit-audit ${CARGO_AUDIT_VERSION}" ]; then
cargo install cargo-audit \
--locked \
--version "${CARGO_AUDIT_VERSION}"
fi
installed_deny=$(cargo deny --version 2>/dev/null || true)
if [ "${installed_deny}" != "cargo-deny ${CARGO_DENY_VERSION}" ]; then
cargo install cargo-deny \
--locked \
--version "${CARGO_DENY_VERSION}"
fi
'''
}
}
stage('Cargo audit') {
steps {
sh '''
set -eu
cargo audit --deny warnings
'''
}
}
stage('Cargo deny') {
steps {
sh '''
set -eu
cargo deny check
'''
}
}
stage('MSRV') {
steps {
sh '''
set -eu
echo "Checking all targets with Rust ${MSRV}..."
cargo "+${MSRV}" check \
--locked \
--all-targets \
--all-features
cargo "+${MSRV}" test \
--locked \
--all-targets \
--all-features
'''
}
}
stage('Format') {
steps {
sh '''
set -eu
echo "Checking formatting..."
cargo fmt \
--all \
-- \
--check
'''
}
}
stage('Check') {
steps {
sh '''
set -eu
echo "Running cargo check..."
cargo check \
--locked \
--all-targets \
--all-features
'''
}
}
stage('Tests') {
steps {
sh '''
set -eu
echo "Running tests..."
cargo test \
--locked \
--all-targets \
--all-features
mkdir -p coverage
: > "coverage/.tests-passed-${BUILD_NUMBER}"
'''
}
}
stage('Clippy') {
steps {
sh '''
set -eu
echo "Running Clippy..."
cargo clippy \
--locked \
--all-targets \
--all-features \
-- \
-D warnings
'''
}
}
stage('Coverage') {
steps {
sh '''
set -eu
cargo tarpaulin \
--config tarpaulin.toml \
--output-dir coverage
mv coverage/tarpaulin-report.json coverage/summary.json
coverage_percent=$(awk -F'"coverage":' '
NF > 1 {
split($2, value, ",")
print value[1]
exit
}
' coverage/summary.json)
scripts/render-coverage-badge.sh \
"${coverage_percent}" \
coverage/coverage.svg
rm coverage/summary.json
: > "coverage/.coverage-ready-${BUILD_NUMBER}"
'''
}
}
}
post {
success {
publishChecks(
conclusion: 'SUCCESS',
name: 'Rust CI',
summary: 'vsg-bridge-ls passed CI.',
text: 'Dependency audit/policy, MSRV/stable checks, formatting, tests, Clippy, and coverage completed successfully.',
title: 'Build Successful'
)
echo '✅ vsg-bridge-ls passed CI.'
}
failure {
publishChecks(
conclusion: 'FAILURE',
name: 'Rust CI',
summary: 'vsg-bridge-ls failed CI.',
text: 'A dependency audit/policy, MSRV/stable, formatting, test, Clippy, or coverage check failed. Check the Jenkins log.',
title: 'Build Failed'
)
echo '❌ vsg-bridge-ls CI failed.'
}
unstable {
publishChecks(
conclusion: 'ACTION_REQUIRED',
name: 'Rust CI',
summary: 'vsg-bridge-ls CI is unstable.',
text: 'The Jenkins build completed with an unstable status.',
title: 'Build Unstable'
)
echo '⚠️ vsg-bridge-ls CI is unstable.'
}
cleanup {
sh '''
set -eu
test_status=failing
if [ -f "coverage/.tests-passed-${BUILD_NUMBER}" ]; then
test_status=passing
fi
scripts/render-test-badge.sh \
"${test_status}" \
coverage/test.svg
if [ ! -f "coverage/.coverage-ready-${BUILD_NUMBER}" ]; then
scripts/render-coverage-badge.sh \
- \
coverage/coverage.svg
fi
package_version=
if command -v cargo >/dev/null 2>&1; then
package_id=$(cargo pkgid --locked 2>/dev/null || true)
case "$package_id" in
*@*) package_version=${package_id##*@} ;;
esac
fi
if [ -z "$package_version" ]; then
package_version=$(awk '
$0 == "[package]" { in_package = 1; next }
substr($0, 1, 1) == "[" { in_package = 0 }
in_package && $1 == "version" && $2 == "=" {
gsub(/^"|"$/, "", $3)
print $3
exit
}
' Cargo.toml)
fi
if [ -z "$package_version" ]; then
echo "could not determine package version" >&2
exit 2
fi
scripts/render-version-badge.sh \
"${package_version}" \
coverage/version.svg
rm -f \
"coverage/.tests-passed-${BUILD_NUMBER}" \
"coverage/.coverage-ready-${BUILD_NUMBER}"
'''
archiveArtifacts(
allowEmptyArchive: false,
artifacts: 'coverage/coverage.svg,coverage/test.svg,coverage/version.svg',
fingerprint: true
)
sh '''
set -eu
if [ "${BRANCH_NAME:-}" = "main" ]; then
scripts/publish-badges.sh \
"${BADGE_PUBLISH_ROOT}" \
coverage \
test \
version
fi
'''
}
}
}

278
README.md
View File

@ -1,47 +1,263 @@
# vsg_bridge_ls
# vsg-bridge-ls
A very featureless VSG to lsp bridge, allowing to use vsg as a linting lsp instead of an external diagnostic tool.
![version](https://assets.dandaedre.com/coverage/MadGobblins/vsg-bridge-ls/main/version.svg)
![tests](https://assets.dandaedre.com/coverage/MadGobblins/vsg-bridge-ls/main/test.svg)
![test coverage](https://assets.dandaedre.com/coverage/MadGobblins/vsg-bridge-ls/main/coverage.svg)
# Install
`vsg-bridge-ls` reports [VSG](https://github.com/jeremiah-c-leary/vhdl-style-guide)
diagnostics through the Language Server Protocol (LSP). A complete setup needs
the companion VSG fork and this bridge.
## Installing VSG
Install vsg either via pip on pip in your venv:
```bash
python -m venv venv
source venv/activate (or activate.fish if you use fish etc...)
pip install vsg
The bridge requires the companion package's version 1 diagnostic interface
(`--diagnostics_json`). An upstream VSG installation without that option is not
compatible.
Helix is the only actively maintained and tested editor integration. The Vim
and VSCodium recipes are best-effort and may need adjustment for your setup.
## Authorship and LLM disclosure
Dandaedre created the bridge and directs its development; upstream VSG remains
the work of its original authors and contributors. Later implementation,
testing, CI, and documentation were substantially developed or refined with an
LLM assistant. No LLM is used at runtime. Diagnostics cannot modify VHDL, while
explicit formatting and fix actions can. See the
[full authorship, testing, and safety disclosure](DISCLOSURE.md).
## 1. Install the VSG fork
The modified VSG packages are published in the
[MadGobblins Python package index](https://proxy.dandaedre.com/gitea/api/packages/MadGobblins/pypi/simple/vsg/).
The preferred installation uses `uv pip` and its prebuilt wheel:
```sh
uv venv .venv
uv pip install --python .venv/bin/python \
--upgrade \
--index https://proxy.dandaedre.com/gitea/api/packages/MadGobblins/pypi/simple/ \
vsg
```
Please note that if you decide to use a venv, you will need to activate your venv every time.
## Installing vsg_bridge_ls
Without `uv`, use standard `pip`:
`cargo install --git https://proxy.dandaedre.com/gitea/Dandaedre/vsg_bridge_ls.git`
```sh
python3 -m venv .venv
. .venv/bin/activate
python -m pip install \
--upgrade \
--index-url https://proxy.dandaedre.com/gitea/api/packages/MadGobblins/pypi/simple/ \
--extra-index-url https://pypi.org/simple \
vsg
```
# Adding the lsp bridge to your editor
This is a narrow integration fork, so upstream remains the owner of VSG release
numbers. Packages built between upstream tags instead use an automatic PEP 440
post version such as `3.35.0.post186+git.b7dc18c1`; this lets `--upgrade` select
newer fork commits. If an installation still remains on an equal or newer
version—for example after rewritten development history—add `--reinstall` to
the `uv` command or `--force-reinstall` to the `pip` command. As a final
fallback, uninstall `vsg` and install it again manually.
## Helix
Add the following to your `~/.config/helix/language.toml` (create this file if it doesn't exist)
## 2. Install the bridge
The preferred method uses
[`cargo-binstall`](https://github.com/cargo-bins/cargo-binstall). Releases
provide three prebuilt platform binaries; `cargo-binstall` selects and installs
the one for the current system from the latest release candidate:
```sh
cargo binstall --git \
https://proxy.dandaedre.com/gitea/MadGobblins/vsg-bridge-ls.git \
vsg-bridge-ls
```
Without `cargo-binstall`, build and install the bridge from source:
```sh
cargo install --locked \
--git https://proxy.dandaedre.com/gitea/MadGobblins/vsg-bridge-ls.git
```
Activate the environment and verify both executables:
```sh
. .venv/bin/activate
command -v vsg
command -v vsg-bridge-ls
vsg-bridge-ls --version
```
The version includes both the Cargo release and build commit, for example
`0.3.6-rc.1+git.0123abcd`, so editor logs can identify the exact binary. To
start from a generated TOML file, see
[Generate a project configuration](#generate-a-project-configuration).
## 3. Configure Helix
Add this minimal setup to `~/.config/helix/languages.toml`:
```toml
[language-server.vsg_bridge_ls]
command = "vsg_bridge_ls"
args = ["-c", "vhdl/config.yaml"] # Optionnal config, note that the path is relative to your project
command = "vsg-bridge-ls"
args = [
"--configuration", "/absolute/path/to/vsg-bridge-ls/showcase/vsg.yaml",
]
[[language]]
name = "vhdl"
scope = "source.vhdl"
file-types = ["vhd", "vhdl"]
comment-token = "--"
language-servers = [ "vhdl_ls", "vsg_bridge_ls" ]
indent = { tab-width = 2, unit = " " }
injection-regex = "vhdl"
language-servers = ["vsg_bridge_ls"]
auto-format = false
```
## Others
Check your editor documentation on how to add a lsp. Untested.
# Developper Documentation
[Tower-lsp](https://github.com/ebkalderon/tower-lsp/blob/master/examples/stdio.rs)
[VSG Github](https://github.com/jeremiah-c-leary/vhdl-style-guide)
[VSG Docs](https://vhdl-style-guide.readthedocs.io/en/latest/editor_integration/vscode.html)
[Lsp Specs](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/)
Start Helix from the activated environment:
```sh
. .venv/bin/activate
hx path/to/file.vhd
```
Diagnostics should appear as you edit. Run `:format` to ask the bridge to
format the current in-memory buffer through the same VSG fix-all path used by
`source.fixAll.vsg`. No separate editor formatter command is required.
If VSG encounters a syntax error, the bridge replaces stale style findings with
one error on the reported line and temporarily withholds formatting and
correction actions. Normal diagnostics and actions return after parsing
succeeds again. When VSG cannot determine a trustworthy location, the bridge
reports one whole-document `analysis-failed` error instead. Its wording says
that VSG could not analyze the document, because unsupported valid VHDL can also
cause a parser failure.
Style diagnostics use editor-friendly levels by default: VSG errors appear as
LSP warnings, and VSG warnings appear as information. This keeps lint findings
visually distinct from parser errors. Pass `--strict-diagnostic-severity` (or
set `strict_diagnostic_severity = true` in bridge TOML) to preserve VSG's Error
and Warning levels exactly.
Hover a diagnosed line to see the VSG rule, configured severity, correction
phase, fixability, relevant configuration, and available documentation links.
With `--allow-browser-action`, clients supporting LSP `window/showDocument` can
also ask the bridge to open a rule's documentation externally.
Less common options are collected under [Advanced usage](#advanced-usage).
## Advanced usage
This section covers [installing VSG from source](#install-vsg-from-source),
[configuration generation](#generate-a-project-configuration), [multiple
language servers](#multiple-language-servers), [experimental
fixes](#experimental-fixes), and [debug mode](#debug-mode).
### Install VSG from source
To install the current fork directly from Git instead of the package index:
```sh
uv venv .venv
uv pip install --python .venv/bin/python --upgrade \
"vsg @ git+https://proxy.dandaedre.com/gitea/MadGobblins/vhdl-style-guide.git@master"
```
This requires Git and builds VSG locally. Replace `master` with a commit hash
for a reproducible installation. Add `--reinstall` when reinstalling the same
commit after a local packaging or environment problem.
### Generate a project configuration
From the project directory, `--write-config` creates `vsg-bridge-ls.toml` from
the options supplied in the same command, then exits:
```sh
vsg-bridge-ls \
--configuration /absolute/path/to/vsg.yaml \
--experimental-rule-fix \
--write-config
```
It refuses to overwrite an existing file. The most useful settings are:
- `vsg_configuration`: VSG configuration paths, in loading order.
- `strict_diagnostic_severity`: preserve VSG's Error and Warning levels.
- `experimental_rule_fix` and `experimental_multi_rule_line_fix`: enable
correction actions.
- `allow_browser_action`: allow documentation actions to open HTTPS links.
- `debug_mode`: expose troubleshooting information.
- `disable_hover`: leave hover presentation to another language server.
Edit the generated file as needed and restart the language server. Explicit
command-line options take priority over configuration files. See the
[configuration reference](doc/configuration.md) for all settings.
### Multiple language servers
Helix can run the bridge alongside a semantic VHDL server such as `vhdl_ls`:
```toml
[language-server.vhdl_ls]
command = "vhdl_ls"
args = ["-l", "/usr/local/lib/vhdl_libraries"]
[[language]]
name = "vhdl"
file-types = ["vhd", "vhdl"]
language-servers = ["vhdl_ls", "vsg_bridge_ls"]
auto-format = false
```
Both servers may answer the same hover request. In Helix's hover popup, use
`Alt+n` for the next result and `Alt+p` for the previous result. The bridge may
appear first regardless of the order in `language-servers`; treat the popup as
a set of results rather than relying on response order.
If VSG hover is unwanted, place this in `vsg-bridge-ls.toml`:
```toml
disable_hover = true
```
The equivalent command-line option is `--disable-hover`. Diagnostics,
formatting, and code actions remain available; only hover is disabled.
### Experimental fixes
With `--experimental-rule-fix`, the code-action menu immediately offers a Quick
Fix for each fixable VSG rule on the diagnosed line. Building the menu does not
run VSG; selecting one action runs one VSG process against the current
in-memory document and asks the client to apply a versioned whole-line edit.
`Fix all VSG findings`
(`source.fixAll.vsg`) is an explicit whole-document action equivalent to VSG's
normal phase-seven formatter; it runs on save only when the editor is configured
to request that action.
For deliberately unformatted files and expected interactions, see the
[LSP showcase](showcase/README.md).
The commented argument above enables an additional multi-rule action. It is
disabled by default because VSG phases can move later findings to different
lines. See the
[experimental action safety notes](doc/experimental-multi-rule-line-fix.md)
before enabling it.
### Debug mode
The independent `--debug-mode` flag adds the same debug snapshot to normal LSP
hover (`space+k` in Helix), including on lines without diagnostics. A source
action remains available as a fallback. The snapshot includes build, process,
configuration, capability, and open-document metadata without source text or
process environment variables. See the [debug-mode reference](doc/debug-mode.md).
## More documentation
- [Installation alternatives and PATH troubleshooting](doc/installation.md)
- [Install VSG from source](#install-vsg-from-source)
- [Generate a project configuration](#generate-a-project-configuration)
- [Use multiple language servers](#multiple-language-servers)
- [Layered bridge configuration reference](doc/configuration.md)
- [Helix, Vim, and VSCodium setup](doc/editor-configuration.md)
- [VSG/bridge machine interface](doc/architecture/vsg-interface.md)
- [Experimental individual rule fixes](doc/experimental-rule-fix.md)
- [Debug-information mode](doc/debug-mode.md)
- [Development and packaging](doc/development.md)
- [Release procedure](doc/releasing.md)
The bridge is deliberately small. Contributions should preserve clean LSP
standard output and keep the VSG subprocess boundary explicit.

29
build.rs Normal file
View File

@ -0,0 +1,29 @@
use std::fs;
use std::process::Command;
fn main() {
println!("cargo:rerun-if-changed=.git/HEAD");
if let Ok(head) = fs::read_to_string(".git/HEAD") {
if let Some(reference) = head.trim().strip_prefix("ref: ") {
println!("cargo:rerun-if-changed=.git/{reference}");
}
}
let revision = if std::path::Path::new(".git").exists() {
Command::new("git")
.args(["rev-parse", "--short=8", "HEAD"])
.output()
.ok()
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok())
.map(|revision| revision.trim().to_owned())
.filter(|revision| {
!revision.is_empty() && revision.bytes().all(|byte| byte.is_ascii_hexdigit())
})
.unwrap_or_else(|| "unknown".to_owned())
} else {
"unknown".to_owned()
};
println!("cargo:rustc-env=VSG_BRIDGE_GIT_SHA={revision}");
}

33
deny.toml Normal file
View File

@ -0,0 +1,33 @@
# Build the same dependency graph checked by the rest of CI.
[graph]
all-features = true
# Advisory exceptions require an explicit, documented decision.
[advisories]
ignore = []
# This is the complete set needed by the current resolved graph.
[licenses]
allow = [
"Apache-2.0",
"LGPL-2.0-only",
"MIT",
"Unicode-3.0",
]
confidence-threshold = 0.8
exceptions = []
[bans]
multiple-versions = "warn"
wildcards = "deny"
highlight = "all"
allow = []
deny = []
skip = []
skip-tree = []
[sources]
unknown-registry = "deny"
unknown-git = "deny"
allow-registry = ["https://github.com/rust-lang/crates.io-index"]
allow-git = []

View File

@ -0,0 +1,288 @@
# VSG diagnostic stream interface
This document defines the boundary between the VSG fork and `vsg-bridge-ls`.
It is intentionally additive: existing VSG commands remain byte-for-byte and
behaviorally unchanged when the new arguments are absent.
## Commands
### Diagnostic request
```text
vsg --stdin --all_phases --diagnostics_json --no-failure [VSG configuration arguments]
```
`--diagnostics_json` is a new boolean argument. It selects the protocol below
for diagnostics written to stdout. It does not replace, alias, or change
`--json`, `--output_format`, or any existing report format.
The new mode is incompatible with options that also claim stdout, including
`--stdout` and `--debug`. Validate only combinations involving the new option;
do not tighten validation for existing invocations.
Stdout always contains exactly one UTF-8 JSON object followed by one newline,
including when argument validation, configuration, parsing, rules, or rendering
fail. Human headers, progress, debug text, and fixed VHDL must never appear on
stdout in this mode. Failure details may also go to stderr and operational
failures return nonzero. `--no-failure` continues to affect findings as it does
today; it must not hide an incomplete analysis or protocol error.
### Scoped correction request
```text
vsg --stdin --fix --stdout --fix_rule RULE:LINE --no-failure [VSG configuration arguments]
```
`--fix_rule` is a new repeatable argument and a thin in-memory translation to
the existing `--fix_only` structure:
```json
{"fix":{"rule":{"RULE":[LINE]}}}
```
Parse the selector by its final colon. The rule ID must be nonempty and `LINE`
must be a positive decimal integer. Deduplicate repeated selectors. Require
`--fix`; reject combination with `--fix_only` rather than defining precedence.
All other fixing behavior, phase ordering, stdout content, and exit semantics
remain owned by the existing VSG implementation.
`--fix_rule` is part of the approved interface. Its implementation must remain
limited to argument parsing, validation, deduplication, and construction of the
existing `--fix_only` data structure; it must not introduce another fix engine.
If that boundary cannot be maintained, stop and report the design conflict
rather than broadening the fork change or silently substituting another bridge
protocol.
## Diagnostic document version 1
The top-level JSON object is:
```json
{
"schema": "vsg.diagnostics",
"schema_version": 1,
"complete": true,
"tool": {"name": "vsg", "version": "3.35.0"},
"source": {"name": "stdin"},
"rules": {
"architecture_003": {
"severity": {"name": "Error", "type": "error"},
"fixable": true,
"phase": 3,
"subphase": 1,
"configuration": {
"disable": false,
"fixable": true,
"phase": 3,
"severity": "Error"
},
"documentation": {
"rule": "https://vhdl-style-guide.readthedocs.io/en/latest/architecture_rules.html#architecture-003",
"configuration": null
}
}
},
"diagnostics": [
{
"rule": "architecture_003",
"location": {"start_line": 4, "end_line": 4},
"message": "Insert blank line above"
}
],
"errors": []
}
```
### Required semantics
- `schema` is the stable protocol identifier.
- `schema_version` changes only for incompatible semantic or required-field
changes. New optional fields may be added without incrementing it.
- `complete` is `true` only when analysis finished and `diagnostics` is an
authoritative result. It defaults to `true` for compatibility with early
version 1 producers that omitted the field.
- `errors` is empty for a complete result. An incomplete result sets
`complete` to `false`, leaves `rules` and `diagnostics` empty, and supplies at
least one object with a broad `kind` (`analysis`, `protocol`, or `internal`)
and human-readable `message`. Consumers must allow future kinds.
- Consumers must reject unknown schema identifiers and unsupported versions.
- `tool.version` is the actual running VSG version, not a bridge constant.
- `rules` contains exactly the distinct rules referenced by `diagnostics`.
- Rule keys and diagnostic rule references are exact VSG unique IDs.
- Severity `name` is the configured display name. Severity `type` is VSG's
semantic type and is currently `error` or `warning`.
- `configuration` is the effective configuration after built-in, global, group,
file, and rule-specific settings have been applied.
- `fixable` reports the effective rule property; it does not promise that a
selected fix will change a stale or already-corrected buffer.
- Finding lines are one-based and inclusive. Version 1 style findings
deliberately have no column fields. Incomplete parser errors may carry their
best available one-based line and column.
- Documentation values are absolute HTTPS URLs or `null`. Built-in rule links
are preferred. Local rules may have no link.
- Diagnostics are sorted by start line and then rule ID. Rule object keys are
emitted in deterministic order to keep fixtures and debugging stable.
- Empty results still emit the complete envelope with empty `rules` and
`diagnostics` objects/arrays.
An analysis failure uses the same protocol identity and version:
```json
{
"schema": "vsg.diagnostics",
"schema_version": 1,
"complete": false,
"tool": {"name": "vsg", "version": "3.35.0"},
"source": {"name": "stdin"},
"rules": {},
"diagnostics": [],
"errors": [{
"kind": "syntax",
"message": "Unexpected token while parsing entity_declaration; expected `end`",
"location": {"line": 1, "column": 1}
}]
}
```
### Consumer behavior
By default the bridge maps VSG `error` to LSP Warning and VSG `warning` to LSP
Information, keeping style findings distinct from code-breaking parser errors.
Strict diagnostic severity maps them to LSP Error and Warning respectively.
Information remains LSP Information in either mode. The bridge preserves the
configured name in diagnostic data and fails visibly on an unknown type instead
of assigning a default severity.
Unknown optional JSON fields are ignored. A declared unsupported schema or
schema version is a compatibility error and is reported prominently. Malformed
JSON, incomplete analysis, missing required fields, invalid line numbers,
dangling rule references, malformed URLs, or inconsistent metadata are
recoverable tool failures: the bridge warns, clears stale style findings and
correction actions, and remains available for the next document update. A
located `syntax` error is published as a non-fixable LSP error on the reported
line. If a structured incomplete analysis has no trustworthy location, the
bridge publishes one non-fixable `analysis-failed` error covering the document.
This error reports VSG's inability to analyze the input rather than asserting
that the input is invalid VHDL. Complete analysis restores normal style
diagnostics and correction actions. One bad response must never crash the
language server or corrupt results from a newer document version.
## Correction granularity
Version 1 corrections are keyed by `(document version, rule ID, line)`. A
single action may fix multiple violations from the same rule on the same line,
because VSG's existing selector cannot distinguish them further. The bridge
must not claim a character-precise correction.
The corrected VHDL remains the complete stdout document produced by VSG. The
bridge should compute a line-block edit by removing common unchanged leading
and trailing lines. If a trustworthy line-block edit cannot be computed, it may
return a versioned full-document edit; it must never guess replacement text.
VSG documents that line numbers can move when multiple fixes are applied.
The version 1 interface therefore supports one rule-and-line correction at a
time, exposed by the bridge only with `--experimental-rule-fix` while its
editor behavior is evaluated.
### Why version 1 uses line ranges
VSG's public diagnostic result identifies a source line, not a character span.
Some internal rule indexes identify entries in a mutable token stream; they are
not byte, Unicode scalar, or UTF-16 offsets into the submitted document. Fix
phases can insert or remove tokens before later rules run. Some valid findings,
such as missing blank lines, describe a position between source characters,
while indentation and alignment rules can describe a group of tokens or lines.
The bridge would have to duplicate VSG parsing and phase behavior to guess more
precise ranges, and those guesses could highlight or replace the wrong text.
Line ranges are therefore the most precise generally valid contract. A future
schema may carry optional VSG-produced source spans with an explicit coordinate
encoding and source-version meaning; consumers must retain the line-range
fallback.
### Whole-document fix-all
The bridge offers a standard LSP source action with kind
`source.fixAll.vsg`. It sends the current in-memory document to the existing VSG
command without requiring a new VSG interface:
```text
vsg --stdin --stdout --fix -fp 7 --no-failure
```
Existing VSG configuration arguments remain separate arguments and are added in
the same way as other bridge invocations. The action is explicit editor sugar
over VSG formatting; it does not run automatically on save unless the user
configures the editor to request it. The bridge must bind the result to the
document version, reject stale results, and return a versioned workspace edit.
If VSG cannot parse or fix the submitted stdin, it returns that input unchanged
so the operation is a no-op; it must never represent failure as empty corrected
text. The bridge therefore receives no destructive edit from a handled parse
failure.
It may use a safe line-block edit or fall back to a full-document replacement.
Correction menus must be cheap: advertise actions from validated in-memory
diagnostics, then invoke VSG only after the client executes the selected
server-owned command. The command applies the resulting versioned workspace
edit through `workspace/applyEdit`.
Formatting and correction actions are withheld whenever analysis of the current
document version is incomplete.
### Experimental individual rule fix
Per-rule actions are exposed only when the bridge starts with:
```text
vsg-bridge-ls --experimental-rule-fix
```
The runtime gate controls action exposure without changing the VSG protocol or
binary. Each action must be labelled experimental, carry a document version and
one `(rule, line)` selector, and retain all normal validation and stale-edit
checks. Opening the menu must not start VSG; selecting an action starts one VSG
process.
### Experimental multi-rule line fix
An additional action may select every distinct fixable rule reported on a line
and invoke VSG once with the corresponding repeated `--fix_rule` selectors.
This action is disabled by default and is exposed only when the bridge starts
with:
```text
vsg-bridge-ls --experimental-multi-rule-line-fix
```
A runtime option is preferred to a Cargo feature: users install one binary,
editors can opt in independently, and CI tests the same artifact that is
distributed. This option gates only grouped action exposure; protocol parsing
remains identical. Single-rule correction exposure is independently gated by
`--experimental-rule-fix`. The grouped action title and command data must label
the behavior experimental.
The action must use one VSG process so that VSG retains ownership of phase and
rule ordering. It must not loop over stale original line numbers in the bridge.
Before this gate can be removed, the planned corpus, property, and integration
checks must pass and the promotion evidence must be recorded in the bridge
documentation.
## Documentation presentation
- Put the rule URL in LSP `Diagnostic.codeDescription.href`.
- Put rule metadata in `Diagnostic.data` so it survives into code-action
requests.
- Offer hover Markdown containing rule, message, configured severity, phase,
fixability, effective configuration, and available links.
- When explicitly enabled by `--allow-browser-action` or layered bridge
configuration, a `Show VSG rule documentation` action may execute a
server-owned command that requests `window/showDocument`. Do not advertise
the command without both permission and client support.
## Compatibility and ownership
VSG owns rule analysis, severity, fixability, effective configuration,
documentation identity, and corrected text. The bridge owns JSON validation,
UTF-16 LSP positions, document-version safety, user-facing actions, and edits.
No VSG submodule is needed. Runtime output from the installed VSG executable is
the authority and cannot safely be replaced by a catalog generated from some
other checkout.

49
doc/configuration.md Normal file
View File

@ -0,0 +1,49 @@
# Bridge configuration
The bridge loads optional TOML configuration in this order:
1. `$XDG_CONFIG_HOME/vsg-bridge-ls/config.toml`, or
`~/.config/vsg-bridge-ls/config.toml` when `XDG_CONFIG_HOME` is unset;
2. `vsg-bridge-ls.toml` in the process working directory;
3. explicit command-line options.
Each later layer overrides values explicitly set by an earlier layer. Missing
files are ignored. An unreadable file, invalid TOML, or unknown key stops startup
with the responsible path instead of silently using unexpected settings.
To create the project file without copying an example from the documentation,
run `vsg-bridge-ls --write-config` in the project directory. Other options on
that invocation are written into the new file. Existing files are never
overwritten.
```toml
vsg_configuration = ["/absolute/path/to/vsg.yaml"]
allow_browser_action = false
experimental_rule_fix = false
experimental_multi_rule_line_fix = false
debug_mode = false
disable_hover = false
strict_diagnostic_severity = false
```
The project file can explicitly set a Boolean to `false` to disable a setting
enabled in the user file. A command-line Boolean flag enables its setting over
both files. One or more command-line `--configuration PATH` values replace the
complete `vsg_configuration` list from TOML.
`allow_browser_action` is disabled by default because the corresponding code
action asks the LSP client to open an external HTTPS URL. It is equivalent to
the explicit `--allow-browser-action` flag. Documentation URLs remain visible
in diagnostics and hover when browser actions are disabled.
`disable_hover` is useful when another language server should own hover
presentation. Setting it to `true` stops the bridge from advertising or
returning hover text without disabling diagnostics, formatting, or actions.
It is equivalent to `--disable-hover`.
`strict_diagnostic_severity` is disabled by default. In the default
editor-friendly mode, VSG `error` findings become LSP warnings and VSG
`warning` findings become LSP information; informational findings remain
information. Syntax failures always remain LSP errors. Set this option to
`true`, or pass `--strict-diagnostic-severity`, to map VSG lint severities to
their matching LSP levels without demotion.

28
doc/debug-mode.md Normal file
View File

@ -0,0 +1,28 @@
# Debug-information mode
Start the bridge with `--debug-mode` to include debug information in every LSP
hover response. In Helix, `space+k` displays the snapshot in the same popup as
normal rule help; on a line without findings it displays a debug-only popup.
The `Show VSG bridge debug information` source action remains as a fallback.
This mode is independent of both experimental correction flags.
Invoking the action displays a pretty-printed JSON snapshot containing:
- the bridge version and embedded commit, executable path, process ID, and
working directory;
- enabled debug and experimental modes;
- whether browser actions are allowed and the client advertised
`window/showDocument`;
- the VSG runner and exact configuration arguments;
- the URI that requested the action; and
- every open document's URI, version, UTF-8 byte and line counts, and current
diagnostic codes, messages, severities, sources, and ranges.
The report deliberately excludes document source text and environment
variables. In particular, it does not dump `PATH`, credentials, tokens, or the
contents of unsaved buffers. Configuration paths, document URIs, and diagnostic
messages are present; VSG messages can contain source identifiers, so inspect a
report before sharing it publicly.
Debug mode is disabled by default and does not alter diagnostics, formatting,
or correction behavior. Restart the language server after changing the flag.

157
doc/development.md Normal file
View File

@ -0,0 +1,157 @@
# Development and packaging
## Rust compatibility
The bridge supports Rust 1.85.1 and newer. Rust does not publish long-term
support toolchains; 1.85.1 was chosen as a conservative distribution anchor
because it is shipped by Debian 13 stable. `Cargo.toml` declares the MSRV,
`Cargo.lock` pins an MSRV-compatible graph, and Jenkins checks that graph with
both Rust 1.85.1 and current stable.
Future dependency updates must preserve this check or deliberately update the
declared MSRV, documentation, and Jenkins value together. Cargo's MSRV-aware
resolver is enabled in `.cargo/config.toml` to avoid selecting newer compatible
crate releases that require a newer compiler.
## Bridge checks
Run the same core checks as Jenkins before submitting a bridge change:
```sh
cargo +1.85.1 check --locked --all-targets --all-features
cargo +1.85.1 test --locked --all-targets --all-features
cargo fmt --all -- --check
cargo check --locked --all-targets --all-features
cargo test --locked --all-targets --all-features
cargo clippy --locked --all-targets --all-features -- -D warnings
```
After installing a newly built companion VSG wheel, run the opt-in real-process
integration check as well:
```sh
VSG_EXECUTABLE=/path/to/venv/bin/vsg \
cargo test --test packaged_vsg -- --ignored
```
Normal unit tests use injected runners and do not depend on a developer's VSG
installation.
Run the two network-enabled dependency policy gates before the core checks:
```sh
cargo audit --deny warnings
cargo deny check
```
## Coverage
Jenkins uses pinned Cargo Tarpaulin 0.37.5 with its LLVM engine and the current
stable toolchain. To run the same 90% line-coverage gate locally:
```sh
rustup component add llvm-tools-preview
cargo install cargo-tarpaulin --locked --version 0.37.5
cargo tarpaulin --config tarpaulin.toml
```
CI uses a temporary JSON summary to render the coverage SVG badge. Its final
cleanup action obtains the package version from `cargo pkgid --locked`, with a
`Cargo.toml` fallback, and renders the test badge from a build-specific marker
written only after the test stage succeeds. If coverage did not complete, CI
renders a neutral `-%` badge instead of leaving a broken or stale image. Jenkins
archives only those three badges. The first behavior-test pass reached 84.38%
(81/96 lines); end-to-end byte-stream
and protocol lifecycle tests raised current coverage above 90%. The latest
coverage run measured 90.27%, allowing CI to enforce a 90% floor. Raise that
floor only after coverage remains stable under useful tests; never add brittle
tests or production branches merely to improve the number.
Standalone HTML, JSON, and LCOV files produced locally remain ignored. Badges
are generated only by Jenkins and are not tracked in the repository. Jenkins
does not retain precise reports; it keeps only `coverage/coverage.svg`,
`coverage/version.svg`, and `coverage/test.svg`.
For the public badge, the Jenkins worker exposes the shared `assets/` directory
at `/mnt/assets`, beside the existing `/mnt/books` mount. The pipeline sets
`BADGE_PUBLISH_ROOT` to `/mnt/assets/coverage`; the worker creates that
directory when needed, and its parent must be writable. The final cleanup action
atomically replaces all three badges after every `main` build, including failed
builds:
```text
MadGobblins/vsg-bridge-ls/main/coverage.svg
MadGobblins/vsg-bridge-ls/main/test.svg
MadGobblins/vsg-bridge-ls/main/version.svg
```
`main` is a real world-traversable directory, not a symlink. This avoids web
server symlink restrictions. Precise HTML, JSON, and LCOV reports are not
retained. The README uses these mutable CI badge URLs:
```text
https://assets.dandaedre.com/coverage/MadGobblins/vsg-bridge-ls/main/coverage.svg
https://assets.dandaedre.com/coverage/MadGobblins/vsg-bridge-ls/main/test.svg
https://assets.dandaedre.com/coverage/MadGobblins/vsg-bridge-ls/main/version.svg
```
The web server should receive this mount read-only, disable directory listing,
serve SVG with a restrictive content security policy, and use a short cache or
revalidation for the mutable badge URL.
## Companion VSG fork
The fork keeps its stream-support patch small and rebases it onto upstream
`master`. From the fork checkout:
```sh
./update-fork.sh
./build-package.sh
```
To build and publish with an explicit Gitea token file:
```sh
chmod 600 ../gitea_token.txt
./build-package.sh ../gitea_token.txt --publish
```
The script builds both a wheel and source distribution and uploads only the
artifacts produced by that invocation. It also accepts `GITEA_TOKEN` or
`GITEA_TOKEN_FILE` when no positional token file is supplied.
## Jenkins package publishing
The VSG Jenkins pipeline publishes successful `master` builds automatically.
It fetches repository tags before setup so `setuptools-git-versioning` can
derive the package version, then publishes the same wheel and source archive
that passed the pip and uv installation checks. Other branches never receive
the publishing credential.
Create the credential in Jenkins:
1. Create a Gitea personal access token whose `package` permission is set to
**Read and Write**. Use an account allowed to publish packages owned by the
`MadGobblins` organization.
2. Open **Manage Jenkins → Credentials**, select the narrowest folder or system
store containing the multibranch job, and choose **Add Credentials**.
3. Select **Secret text**, paste the token into **Secret**, and set **ID** to
`vsg-gitea-package-token`.
4. Save it. The Credentials Binding plugin must be installed for the
`withCredentials` pipeline step.
The token exists only as `GITEA_TOKEN` inside the publish stage. Shell tracing
is disabled before it is mapped to uv's `UV_PUBLISH_PASSWORD`; it is never put
in a command argument or written into the workspace.
Published versions come from the existing Git-versioning backend. An exact
release version requires a version tag on the commit; untagged commits receive
the backend's post-release version. Because package versions are immutable in
Gitea, the pipeline uses uv's index check to skip files already present.
## References
- [Language Server Protocol 3.17](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/)
- [tower-lsp stdio example](https://github.com/ebkalderon/tower-lsp/blob/master/examples/stdio.rs)
- [upstream VSG](https://github.com/jeremiah-c-leary/vhdl-style-guide)
- [upstream VSG documentation](https://vhdl-style-guide.readthedocs.io/en/latest/)

148
doc/editor-configuration.md Normal file
View File

@ -0,0 +1,148 @@
# Editor configuration
The bridge provides VSG diagnostics, opt-in rule-scoped Quick Fixes, an explicit
`source.fixAll.vsg` action, and whole-document formatting over LSP. Formatting
and fix-all both pipe the current in-memory buffer through the companion VSG
fork's normal phase-seven formatter.
Helix is the only actively maintained and tested integration. The Vim and
VSCodium recipes are best-effort starting points and may need adjustment.
Whichever editor you use, launch it from the activated VSG environment or set
absolute paths for both executables.
## Helix
Add this configuration to `~/.config/helix/languages.toml`:
```toml
[language-server.vsg_bridge_ls]
command = "vsg-bridge-ls"
args = [
"--configuration", "/absolute/path/to/vsg-bridge-ls/showcase/vsg.yaml",
# Uncomment to allow an action that opens rule documentation in a browser.
# "--allow-browser-action",
# Uncomment the next line to enable experimental individual rule fixes.
# "--experimental-rule-fix",
# Uncomment the next line to enable the experimental grouped line fix.
# "--experimental-multi-rule-line-fix",
# Uncomment the next line to expose debug information in hover and an action.
# "--debug-mode",
]
[[language]]
name = "vhdl"
language-servers = ["vsg_bridge_ls"]
auto-format = false
```
To use another VSG configuration, change the path in the argument list. Repeat
`-c PATH` for multiple files; relative paths are resolved from the project:
```toml
args = ["-c", "vhdl/config.yaml"]
```
The same bridge settings can live in the user or project TOML files described
in the [configuration reference](configuration.md). Explicit arguments in this
editor setup take precedence.
The experimental grouped same-line action is enabled by uncommenting its entry
in the complete example. It is deliberately off by default; read its
[safety notes](experimental-multi-rule-line-fix.md) before enabling it.
Keep every option and value as a separate quoted array item with a trailing
comma. An absolute configuration path avoids dependence on Helix's project
working directory.
Debug mode is independent of the experimental correction modes. After enabling
`--debug-mode` and restarting the server, use hover (`space`, then `k`) anywhere
in an open VHDL document. Rule help is retained when the line has diagnostics,
with the debug snapshot below it. The action-picker entry remains available as
a fallback. See the [debug-mode reference](debug-mode.md) for the reported
fields and privacy boundary.
If another VHDL server is installed, it can run alongside the bridge:
```toml
language-servers = ["vhdl_ls", "vsg_bridge_ls"]
```
Set `auto-format = true` only after testing the formatter on the project.
The bridge owns the formatter arguments so diagnostics, fix-all, and formatting
use one configured VSG executable and configuration. To check VSG independently:
```sh
vsg --stdin --stdout --fix -fp 7 --no-failure < vhdl/test.vhd
```
Use Helix's action picker (`space`, then `a` by default) on a diagnosed line to
choose `Fix all VSG findings`. Start the bridge with
`--experimental-rule-fix` to also offer one VSG rule correction. Hover (`space`,
then `k` by default) shows the effective rule configuration and documentation.
The menu is generated from current bridge state without starting VSG; only the
selected correction starts a formatter process.
## Vim (best-effort)
This example uses [vim-lsp](https://github.com/prabirshrestha/vim-lsp). With
vim-plug, add the plugin and run `:PlugInstall`:
```vim
Plug 'prabirshrestha/vim-lsp'
```
Then register the bridge in `.vimrc`:
```vim
if executable('vsg-bridge-ls')
au User lsp_setup call lsp#register_server({
\ 'name': 'vsg_bridge_ls',
\ 'cmd': {server_info->['vsg-bridge-ls']},
\ 'allowlist': ['vhdl'],
\ })
endif
```
Start Vim from the activated `.venv`. To pass a VSG configuration file, change
the command to `['vsg-bridge-ls', '-c', 'vhdl/config.yaml']`.
The bridge advertises standard LSP document formatting. Its standard code
actions and formatting should appear through vim-lsp's corresponding commands.
## VSCodium (best-effort)
VSCodium has no built-in setting for arbitrary LSP commands. One possible
adapter is
[Generic LSP Proxy](https://github.com/mjmorales/vscode-generic-lsp-proxy),
but it is not currently available from Open VSX. Build its VSIX locally:
```sh
git clone https://github.com/mjmorales/vscode-generic-lsp-proxy.git
cd vscode-generic-lsp-proxy
npm install
npm run compile
npx vsce package
codium --install-extension generic-lsp-proxy-*.vsix
cd ..
```
Create `.vscode/lsp-proxy.json` in the VHDL project:
```json
[
{
"languageId": "vhdl",
"command": "vsg-bridge-ls",
"transport": "stdio",
"fileExtensions": [".vhd", ".vhdl"]
}
]
```
Launch the project from the activated environment with `codium .`, then open a
VHDL file. If diagnostics do not appear, check **Output: Generic LSP Proxy**.
Desktop and sandboxed VSCodium installations may require an absolute `command`
path or other PATH adjustments.
The bridge advertises standard LSP document formatting. Its opt-in Quick Fixes,
source fix-all, and formatting should appear when the proxy preserves the
corresponding standard LSP requests.

View File

@ -0,0 +1,38 @@
# Experimental multi-rule line correction
Start the bridge with `--experimental-multi-rule-line-fix` to add one action
for all distinct fixable VSG rules reported on a diagnosed line. Individual
rule fixes are controlled separately by `--experimental-rule-fix`; enable both
flags to offer both kinds of correction. The bridge submits every selector to
one VSG process so VSG retains control of phase ordering; it never loops over
stale line numbers.
Opening the action menu does not invoke VSG. The grouped process starts only
after the user selects the experimental action.
This action is intentionally disabled by default. Rules from an early phase can
insert or delete lines before later rules inspect their selector. In the
`one-line-entity.vhd` showcase, the phase-one newline correction makes progress
but exposes an `entity_009` indentation finding, while the original phase-six
end-name selector moves to line 2. A second request using the old line-1
selectors is a no-op. This named regression is asserted by the packaged-VSG
integration test rather than silently treated as a complete correction.
The normal suite includes a fixed-seed (`0x5eed`) 128-case structured edit
property test covering indentation, whitespace, line insertion, casing,
Unicode, LF, and CRLF. It also verifies selector deduplication, one-process
batching, no-op behavior, stale-version rejection, cancellation, and exact LSP
edit reproduction. The opt-in packaged-VSG test diagnoses the corrected output
again and checks monotonic progress for the showcase case:
```sh
VSG_EXECUTABLE=/path/to/venv/bin/vsg \
cargo test --test packaged_vsg -- --ignored
```
The gate must remain until every fixable rule family and phase has a curated
case, known line-shift regressions are resolved or explicitly accepted, a
longer fuzz campaign has no unexplained regression, the packaged release pair
passes, and the behavior has been manually verified in Helix. Current tests are
useful safety coverage, not promotion evidence for enabling the action by
default.

View File

@ -0,0 +1,16 @@
# Experimental individual rule correction
Start the bridge with `--experimental-rule-fix` to offer one clearly labelled
Quick Fix per fixable VSG `(rule, line)` pair. The mode is disabled by default
while its editor behavior and usefulness are evaluated.
Opening the action menu uses only the bridge's validated in-memory diagnostics
and starts no VSG process. Selecting an action sends the current unsaved buffer
and one `--fix_rule RULE:LINE` selector to a single VSG process, rejects stale
document versions, computes a whole-line edit, and asks the editor to apply it.
Several findings from the same rule on the same line share one action because
VSG's public selector cannot distinguish them more precisely.
This flag is independent of `--experimental-multi-rule-line-fix`. Enable both
to compare individual and grouped corrections. Whole-document formatting and
`source.fixAll.vsg` remain available without either experimental flag.

100
doc/installation.md Normal file
View File

@ -0,0 +1,100 @@
# Installation
`vsg-bridge-ls` starts `vsg` by name, so both executables must be available in
the environment used by the editor. Formatting additionally requires the
companion fork's `--stdout` and `--no-failure` options; upstream VSG alone is
not sufficient for that workflow.
## Preferred: prebuilt VSG package with uv
The prebuilt package avoids a local source checkout and build:
```sh
uv venv .venv
uv pip install --python .venv/bin/python \
--index https://proxy.dandaedre.com/gitea/api/packages/MadGobblins/pypi/simple/ \
vsg
```
Activate the environment before launching the editor:
```sh
. .venv/bin/activate
```
## Install VSG from master with uv
```sh
uv venv .venv
uv pip install --python .venv/bin/python \
"git+https://proxy.dandaedre.com/gitea/MadGobblins/vhdl-style-guide.git@master"
```
## Install VSG with pip
Both package sources also work with standard pip. For the prebuilt package:
```sh
python3 -m venv .venv
. .venv/bin/activate
python -m pip install \
--index-url https://proxy.dandaedre.com/gitea/api/packages/MadGobblins/pypi/simple/ \
--extra-index-url https://pypi.org/simple \
vsg
```
The extra PyPI index supplies dependencies that are not stored in Gitea. To
install the current `master` branch instead:
```sh
python3 -m venv .venv
. .venv/bin/activate
python -m pip install \
"git+https://proxy.dandaedre.com/gitea/MadGobblins/vhdl-style-guide.git@master"
```
## Preferred: install the prebuilt bridge with cargo-binstall
Releases contain prebuilt archives for three supported targets. With
[`cargo-binstall`](https://github.com/cargo-bins/cargo-binstall) available, it
selects the archive for the current system and installs the latest release
candidate:
```sh
cargo binstall --git \
https://proxy.dandaedre.com/gitea/MadGobblins/vsg-bridge-ls.git \
vsg-bridge-ls
```
## Alternative: build the bridge from source
Without `cargo-binstall`, install the released branch directly from Gitea:
```sh
cargo install --locked \
--git https://proxy.dandaedre.com/gitea/MadGobblins/vsg-bridge-ls.git
```
For development, clone this repository and use `cargo build`. Cargo normally
places installed binaries in `~/.cargo/bin`; that directory must also be in the
editor's PATH.
The bridge supports Rust 1.85.1 and newer. `--locked` uses the dependency
versions tested by CI and is required to preserve that compatibility guarantee.
## PATH and virtual environments
Activating `.venv` before launching the editor is the simplest setup because
the child language server inherits the editor's PATH. If the editor is launched
by a desktop session, configure that editor to include the absolute paths to
`.venv/bin` and `~/.cargo/bin` instead.
Check the same environment the editor will inherit:
```sh
command -v vsg
command -v vsg-bridge-ls
```
Python 3.8 is the fork's minimum supported version. The complete test suite and
packaged stdin/stdout workflow are validated on Python 3.8.20.

89
doc/releasing.md Normal file
View File

@ -0,0 +1,89 @@
# Release procedure
`release.sh` is the project-local wrapper for `rust_realease`. It releases the
single Cargo package and binary named `vsg-bridge-ls` using the release profile
and both cargo-binstall `.tgz` archives and standalone binaries.
The default target matrix is owned by `rust_realease`:
- `x86_64-unknown-linux-musl`;
- `aarch64-unknown-linux-musl`; and
- `x86_64-pc-windows-gnu`.
Cross and a working Docker or Podman backend are required for those builds.
`Cross.toml` selects the current upstream Cross images because older tagged
Windows GNU images lack the import libraries required by current Rust releases.
`cargo-binstall` is required to verify the archives. Install the publisher from
its authoritative repository if `rust_realease --version` is unavailable:
```sh
cargo install --git \
https://proxy.dandaedre.com/gitea/idle-org/rust_realease.git \
--locked rust_realease
```
## Release identity
The Cargo version is authoritative and produces a `v`-prefixed tag. For
example, version `0.3.3-rc.1` requires tag `v0.3.3-rc.1`. A hyphenated Cargo
version makes the wrapper add `--prerelease` automatically.
Development uses the SSH origin
`git@git.dandaedre.com:MadGobblins/vsg-bridge-ls.git`. The exact fallback in
`rust-release.toml` directs release creation, downloads, and cargo-binstall to
the public HTTPS repository without changing the Git remote.
This repository does not currently maintain a changelog file. Release notes and
version selection must therefore be reviewed from the commits since the prior
tag before publication.
## Token handling
Pass a readable token file as the first wrapper argument. Only its first line is
exported as `GITEA_TOKEN`; the value is never placed in process arguments. Do
not commit the token or its path. The usual workspace-local invocation is:
```sh
./release.sh ../gitea_token.txt --dry-run
```
The token needs repository read and release write access. This is a public
repository, so generated downloads and cargo-binstall verification can be
performed anonymously after upload.
## Verification and publication
Run a syntax check and non-mutating publisher inspection first:
```sh
sh -n release.sh
./release.sh ../gitea_token.txt --dry-run
```
The dry run must report the expected package, version, tag, three targets,
artifact names, and HTTPS destination. It does not build, tag, push, create a
release, or upload files.
A local build and package inspection is also non-publishing:
```sh
./release.sh ../gitea_token.txt --compile-only
```
Inspect the resulting `dist/release-*` directory, `SHA256SUMS`, archives,
executables, and cargo-binstall metadata. Generated `dist/` content is ignored
by Git.
Before a live run, require a clean checkout, confirm that the expected signed
tag points to `HEAD`, push the commit and tag, and verify the same tag exists on
the remote. Recheck Gitea for an existing release and asset-name collisions.
Then publish explicitly:
```sh
./release.sh ../gitea_token.txt
```
The wrapper itself never edits Git metadata, creates or pushes a tag, or
publishes without `rust_realease`. An existing asset is a hard stop. Never pass
`--replace-assets` unless the exact existing release and assets were inspected
and replacement was separately approved.

48
release.sh Executable file
View File

@ -0,0 +1,48 @@
#!/bin/sh
set -eu
usage() {
echo "usage: $0 <gitea-token-file> [rust_realease options...]" >&2
exit 2
}
[ "$#" -ge 1 ] || usage
token_file=$1
shift
if [ ! -f "$token_file" ] || [ ! -r "$token_file" ]; then
echo "token file is not a readable regular file: $token_file" >&2
exit 2
fi
if ! command -v rust_realease >/dev/null 2>&1; then
echo "rust_realease is not installed or not available in PATH" >&2
exit 2
fi
GITEA_TOKEN=
IFS= read -r GITEA_TOKEN <"$token_file" || :
if [ -z "$GITEA_TOKEN" ]; then
echo "token file is empty: $token_file" >&2
exit 2
fi
export GITEA_TOKEN
repository_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
manifest_version=$(sed -n 's/^version = "\([^"]*\)"/\1/p' \
"$repository_dir/Cargo.toml" | head -n 1)
if [ -z "$manifest_version" ]; then
echo "could not determine the selected package version" >&2
exit 2
fi
set -- \
"$repository_dir" \
--package vsg-bridge-ls \
--artifact-format both \
"$@"
case "$manifest_version" in
*-*) set -- "$@" --prerelease ;;
esac
exec rust_realease "$@"

3
rust-release.toml Normal file
View File

@ -0,0 +1,3 @@
[[repository.fallbacks]]
origin = "git@git.dandaedre.com:MadGobblins/vsg-bridge-ls.git"
fallback-url = "https://proxy.dandaedre.com/gitea/MadGobblins/vsg-bridge-ls"

72
scripts/publish-badges.sh Executable file
View File

@ -0,0 +1,72 @@
#!/bin/sh
set -eu
usage() {
echo "usage: $0 <badge-publication-root> <badge> [badge...]" >&2
echo "badges: coverage test version" >&2
exit 2
}
[ "$#" -ge 2 ] || usage
publication_root=$1
shift
case "$publication_root" in
/*) ;;
*)
echo "badge publication root must be an absolute path: $publication_root" >&2
exit 2
;;
esac
if ! mkdir -p "$publication_root"; then
echo "could not create badge publication root: $publication_root" >&2
exit 2
fi
if [ ! -w "$publication_root" ]; then
echo "badge publication root is not a writable directory: $publication_root" >&2
exit 2
fi
chmod 0755 "$publication_root"
for badge in "$@"; do
case "$badge" in
coverage|test|version) ;;
*)
echo "unsupported badge: $badge" >&2
exit 2
;;
esac
if [ ! -f "coverage/$badge.svg" ]; then
echo "required badge is missing: coverage/$badge.svg" >&2
exit 2
fi
done
owner_root="$publication_root/MadGobblins"
project_root="$owner_root/vsg-bridge-ls"
badge_root="$project_root/main"
mkdir -p "$project_root"
chmod 0755 "$owner_root" "$project_root"
if [ -L "$badge_root" ]; then
unlink "$badge_root"
elif [ -e "$badge_root" ] && [ ! -d "$badge_root" ]; then
echo "badge destination is not a directory: $badge_root" >&2
exit 2
fi
mkdir -p "$badge_root"
chmod 0755 "$badge_root"
for badge in "$@"; do
temporary=$(mktemp "$badge_root/.$badge.svg.XXXXXX")
trap 'rm -f "$temporary"' EXIT HUP INT TERM
cp "coverage/$badge.svg" "$temporary"
chmod 0644 "$temporary"
mv -f "$temporary" "$badge_root/$badge.svg"
trap - EXIT HUP INT TERM
echo "published $badge badge to $badge_root/$badge.svg"
done

View File

@ -0,0 +1,69 @@
#!/bin/sh
set -eu
usage() {
echo "usage: $0 <line-coverage-percent> <output.svg>" >&2
exit 2
}
[ "$#" -eq 2 ] || usage
percent=$1
output=$2
if [ "$percent" = "-" ]; then
rounded=-
color='#9f9f9f'
else
if ! awk -v value="$percent" 'BEGIN {
valid = value ~ /^[0-9]+([.][0-9]+)?$/ && value >= 0 && value <= 100
exit(valid ? 0 : 1)
}'; then
echo "coverage percentage must be - or a number from 0 through 100: $percent" >&2
exit 2
fi
rounded=$(awk -v value="$percent" 'BEGIN { printf "%.0f", value }')
if [ "$rounded" -ge 90 ]; then
color='#4c1'
elif [ "$rounded" -ge 70 ]; then
color='#dfb317'
else
color='#e05d44'
fi
fi
output_dir=${output%/*}
if [ "$output_dir" != "$output" ]; then
mkdir -p -- "$output_dir"
fi
temporary="${output}.tmp.$$"
trap 'rm -f -- "$temporary"' EXIT HUP INT TERM
sed \
-e "s/@PERCENT@/${rounded}/g" \
-e "s/@COLOR@/${color}/g" \
>"$temporary" <<'EOF'
<svg xmlns="http://www.w3.org/2000/svg" width="112" height="20" role="img" aria-label="coverage: @PERCENT@%">
<title>coverage: @PERCENT@%</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#fff" stop-opacity=".7"/>
<stop offset=".1" stop-color="#aaa" stop-opacity=".1"/>
<stop offset=".9" stop-opacity=".3"/>
<stop offset="1" stop-opacity=".5"/>
</linearGradient>
<clipPath id="r"><rect width="112" height="20" rx="3"/></clipPath>
<g clip-path="url(#r)">
<rect width="75" height="20" fill="#555"/>
<rect x="75" width="37" height="20" fill="@COLOR@"/>
<rect width="112" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" dominant-baseline="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="37.5" y="10">coverage</text>
<text x="93.5" y="10">@PERCENT@%</text>
</g>
</svg>
EOF
mv -- "$temporary" "$output"
trap - EXIT HUP INT TERM

56
scripts/render-test-badge.sh Executable file
View File

@ -0,0 +1,56 @@
#!/bin/sh
set -eu
usage() {
echo "usage: $0 <passing|failing> <output.svg>" >&2
exit 2
}
[ "$#" -eq 2 ] || usage
status=$1
output=$2
case "$status" in
passing) color='#4c1' ;;
failing) color='#e05d44' ;;
*)
echo "test badge status must be passing or failing: $status" >&2
exit 2
;;
esac
output_dir=${output%/*}
if [ "$output_dir" != "$output" ]; then
mkdir -p -- "$output_dir"
fi
temporary="${output}.tmp.$$"
trap 'rm -f -- "$temporary"' EXIT HUP INT TERM
sed \
-e "s/@STATUS@/${status}/g" \
-e "s/@COLOR@/${color}/g" \
>"$temporary" <<'EOF'
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="20" role="img" aria-label="tests: @STATUS@">
<title>tests: @STATUS@</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#fff" stop-opacity=".7"/>
<stop offset=".1" stop-color="#aaa" stop-opacity=".1"/>
<stop offset=".9" stop-opacity=".3"/>
<stop offset="1" stop-opacity=".5"/>
</linearGradient>
<clipPath id="r"><rect width="100" height="20" rx="3"/></clipPath>
<g clip-path="url(#r)">
<rect width="45" height="20" fill="#555"/>
<rect x="45" width="55" height="20" fill="@COLOR@"/>
<rect width="100" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" dominant-baseline="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="22.5" y="10">tests</text>
<text x="72.5" y="10">@STATUS@</text>
</g>
</svg>
EOF
mv -- "$temporary" "$output"
trap - EXIT HUP INT TERM

65
scripts/render-version-badge.sh Executable file
View File

@ -0,0 +1,65 @@
#!/bin/sh
set -eu
usage() {
echo "usage: $0 <package-version> <output.svg>" >&2
exit 2
}
[ "$#" -eq 2 ] || usage
version=$1
output=$2
case "$version" in
''|*[!0-9A-Za-z.+-]*)
echo "package version contains unsupported badge characters: $version" >&2
exit 2
;;
esac
value_width=$(awk -v value="$version" 'BEGIN {
width = length(value) * 7 + 10
print (width < 45 ? 45 : width)
}')
badge_width=$((59 + value_width))
value_center=$(awk -v width="$value_width" 'BEGIN {
printf "%.1f", 59 + width / 2
}')
output_dir=${output%/*}
if [ "$output_dir" != "$output" ]; then
mkdir -p -- "$output_dir"
fi
temporary="${output}.tmp.$$"
trap 'rm -f -- "$temporary"' EXIT HUP INT TERM
sed \
-e "s/@VERSION@/${version}/g" \
-e "s/@BADGE_WIDTH@/${badge_width}/g" \
-e "s/@VALUE_WIDTH@/${value_width}/g" \
-e "s/@VALUE_CENTER@/${value_center}/g" \
>"$temporary" <<'EOF'
<svg xmlns="http://www.w3.org/2000/svg" width="@BADGE_WIDTH@" height="20" role="img" aria-label="version: @VERSION@">
<title>version: @VERSION@</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#fff" stop-opacity=".7"/>
<stop offset=".1" stop-color="#aaa" stop-opacity=".1"/>
<stop offset=".9" stop-opacity=".3"/>
<stop offset="1" stop-opacity=".5"/>
</linearGradient>
<clipPath id="r"><rect width="@BADGE_WIDTH@" height="20" rx="3"/></clipPath>
<g clip-path="url(#r)">
<rect width="59" height="20" fill="#555"/>
<rect x="59" width="@VALUE_WIDTH@" height="20" fill="#007ec6"/>
<rect width="@BADGE_WIDTH@" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" dominant-baseline="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="29.5" y="10">version</text>
<text x="@VALUE_CENTER@" y="10">@VERSION@</text>
</g>
</svg>
EOF
mv -- "$temporary" "$output"
trap - EXIT HUP INT TERM

60
showcase/README.md Normal file
View File

@ -0,0 +1,60 @@
# LSP showcase
These deliberately unformatted, valid VHDL files make the bridge behavior easy
to inspect in an editor. Do not format and commit them: their findings are the
showcase.
From the repository root, start your editor with the VSG environment active and
pass the showcase configuration to the bridge:
```toml
[language-server.vsg_bridge_ls]
command = "vsg-bridge-ls"
args = [
"--configuration", "/absolute/path/to/vsg-bridge-ls/showcase/vsg.yaml",
# Uncomment to allow an action that opens rule documentation in a browser.
# "--allow-browser-action",
# Uncomment the next line to enable experimental individual rule fixes.
# "--experimental-rule-fix",
# Uncomment the next line to enable the experimental grouped line fix.
# "--experimental-multi-rule-line-fix",
# Uncomment the next line to expose debug information in hover and an action.
# "--debug-mode",
]
[[language]]
name = "vhdl"
language-servers = ["vsg_bridge_ls"]
auto-format = false
```
Open `one-line-entity.vhd` first. It intentionally has multiple fixable rules
on one line and rules from different VSG phases. You should be able to:
1. See full-line diagnostics with exact VSG rule IDs.
2. Hover the line for severity, phase, fixability, effective configuration,
and documentation links.
3. with `--experimental-rule-fix`, select an individual Quick Fix for one rule
on line 1;
4. select `Fix all VSG findings` to run the normal phase-seven formatter; and
5. run Helix `:format` through the bridge's equivalent LSP formatting request.
To inspect the opt-in grouped action, add
`--experimental-multi-rule-line-fix` to the bridge arguments. The action is
clearly labelled Experimental. Enable both correction flags to display grouped
and individual actions together.
Then open `demo_design.vhd` to inspect findings and fixes across an entity,
port clause, architecture, operators, indentation, and identifier casing. The
enabled `comment_012` rule reports its TODO comment as a non-fixable Warning,
so both LSP Error and Warning presentation can be inspected. VSG deliberately
fixes only Error-severity rules; the warning remains after `Fix all VSG
findings`, while `one-line-entity.vhd` becomes clean.
Restarting the language server should replace the existing diagnostic set,
without doubling its entries. The bridge clears every open document during a
graceful LSP shutdown so Helix can discard diagnostics owned by the old server
instance.
Helix is the maintained test target. Its action picker is available through
`space` then `a`; hover is `space` then `k`. Key bindings can vary by release.

13
showcase/demo_design.vhd Normal file
View File

@ -0,0 +1,13 @@
library ieee;
use ieee.std_logic_1164.all;
entity blinker is
port(Clk:in std_logic;LED:out std_logic);
end entity blinker;
architecture RTL of blinker is
begin
LED<=Clk;
end architecture RTL;
-- TODO: inspect this non-fixable warning in the editor

View File

@ -0,0 +1 @@
entity tiny is end entity tiny;

7
showcase/vsg.yaml Normal file
View File

@ -0,0 +1,7 @@
rule:
entity_008:
case: upper
entity_012:
case: upper
comment_012:
disable: false

903
src/diagnostics.rs Normal file
View File

@ -0,0 +1,903 @@
//! Validation and LSP conversion for VSG's versioned diagnostic protocol.
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::collections::{BTreeMap, BTreeSet};
use tower_lsp::lsp_types::{
CodeDescription, Diagnostic, DiagnosticSeverity, NumberOrString, Position, Range, Url,
};
/// Stable source label attached to every diagnostic from VSG.
const DIAGNOSTIC_SOURCE: &str = "vsg";
/// Protocol identifier supported by this bridge release.
const DIAGNOSTIC_SCHEMA: &str = "vsg.diagnostics";
/// Protocol version supported by this bridge release.
const DIAGNOSTIC_SCHEMA_VERSION: u32 = 1;
/// Complete wire document produced by VSG.
#[derive(Debug, Deserialize)]
struct DiagnosticDocument {
/// Stable protocol identifier.
schema: String,
/// Version of the protocol schema.
schema_version: u32,
/// Whether analysis completed and the findings are authoritative.
#[serde(default = "complete_by_default")]
complete: bool,
/// VSG executable identity.
tool: ToolIdentity,
/// Submitted source identity.
source: SourceIdentity,
/// Metadata keyed by exact VSG rule identifier.
rules: BTreeMap<String, RuleMetadata>,
/// Findings in deterministic VSG order.
diagnostics: Vec<VsgDiagnostic>,
/// Structured failures supplied when VSG could not complete analysis.
#[serde(default)]
errors: Vec<VsgError>,
}
/// One failure reported inside an incomplete diagnostic document.
#[derive(Debug, Deserialize)]
struct VsgError {
/// Stable broad failure category.
kind: String,
/// Human-readable failure detail.
message: String,
/// Best available parser position, using VSG's one-based coordinates.
location: Option<VsgErrorLocation>,
}
/// Source position associated with an incomplete VSG analysis.
#[derive(Debug, Deserialize)]
struct VsgErrorLocation {
/// One-based source line.
line: u32,
/// One-based source column, validated while the bridge publishes a safe line range.
column: Option<u32>,
}
/// Result of parsing one VSG response without confusing failure with "clean".
#[derive(Debug)]
pub(crate) enum DiagnosticResponse {
/// Analysis completed and these diagnostics may replace the previous set.
Complete(Vec<Diagnostic>),
/// Analysis failed or the response was malformed; replace stale findings.
Incomplete {
/// Human-readable failure reported to the user.
message: String,
/// A located syntax failure, when VSG supplied a safe source position.
diagnostics: Vec<Diagnostic>,
},
}
/// Identity of the VSG executable that produced a document.
#[derive(Debug, Deserialize)]
struct ToolIdentity {
/// Expected to remain `vsg`.
name: String,
/// Actual VSG package version.
version: String,
}
/// Identity of the source submitted to VSG.
#[derive(Debug, Deserialize)]
struct SourceIdentity {
/// Expected to remain `stdin` for the bridge transport.
name: String,
}
/// Configured severity and its stable semantic class.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub(crate) struct RuleSeverity {
/// User-facing configured severity name.
pub(crate) name: String,
/// Stable VSG class: `error` or `warning`.
#[serde(rename = "type")]
pub(crate) kind: String,
}
/// Documentation links supplied by VSG.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub(crate) struct RuleDocumentation {
/// Rule-specific documentation, when stable.
pub(crate) rule: Option<String>,
/// Configuration documentation, when applicable.
pub(crate) configuration: Option<String>,
}
/// Effective metadata for one referenced VSG rule.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub(crate) struct RuleMetadata {
/// Configured display name and semantic severity type.
pub(crate) severity: RuleSeverity,
/// Whether VSG implements a correction for this rule.
pub(crate) fixable: bool,
/// VSG correction phase.
pub(crate) phase: u32,
/// Ordering within the correction phase.
pub(crate) subphase: u32,
/// Fully merged rule configuration.
pub(crate) configuration: Map<String, Value>,
/// Stable documentation destinations.
pub(crate) documentation: RuleDocumentation,
}
/// One line-oriented VSG finding.
#[derive(Debug, Deserialize)]
struct VsgDiagnostic {
/// Exact key into the document's rule table.
rule: String,
/// Inclusive, one-based source lines.
location: VsgLocation,
/// Human-readable correction guidance.
message: String,
}
/// Inclusive one-based source location.
#[derive(Debug, Deserialize)]
struct VsgLocation {
/// First affected source line.
start_line: u32,
/// Last affected source line.
end_line: u32,
}
/// Opaque bridge data retained by LSP diagnostics for later requests.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub(crate) struct DiagnosticData {
/// Protocol version from which this data was derived.
pub(crate) schema_version: u32,
/// Actual VSG package version.
pub(crate) tool_version: String,
/// Exact VSG rule identifier.
pub(crate) rule: String,
/// One-based line used by VSG correction selectors.
pub(crate) line: u32,
/// Effective metadata for the rule.
pub(crate) metadata: RuleMetadata,
}
/// UTF-16 line widths for one in-memory document.
#[derive(Clone, Debug, PartialEq, Eq)]
struct LineMetrics {
/// Number of UTF-16 code units in each line, excluding the line ending.
utf16_widths: Vec<u32>,
}
impl LineMetrics {
/// Measures all lines using the position encoding required by LSP 3.17.
fn new(text: &str) -> Self {
let utf16_widths = text
.split('\n')
.map(|line| {
let line = line.strip_suffix('\r').unwrap_or(line);
u32::try_from(line.encode_utf16().count()).unwrap_or(u32::MAX)
})
.collect();
Self { utf16_widths }
}
/// Returns a valid range spanning inclusive one-based VSG lines.
fn range_for_vsg_lines(&self, start_line: u32, end_line: u32) -> Range {
let final_index = self.utf16_widths.len().saturating_sub(1);
let start_index = (start_line.saturating_sub(1) as usize).min(final_index);
let end_index = (end_line.saturating_sub(1) as usize).min(final_index);
let start = u32::try_from(start_index).unwrap_or(u32::MAX);
let end = u32::try_from(end_index).unwrap_or(u32::MAX);
let width = self.utf16_widths.get(end_index).copied().unwrap_or(0);
Range::new(Position::new(start, 0), Position::new(end, width))
}
}
/// Parses one VSG response, reserving errors for incompatible protocol versions.
pub(crate) fn parse_diagnostics(
output: &str,
document_text: &str,
strict_diagnostic_severity: bool,
) -> Result<DiagnosticResponse> {
let value: Value = match serde_json::from_str(output) {
Ok(value) => value,
Err(_) => {
return Ok(incomplete(
"VSG returned malformed diagnostic JSON".to_owned(),
Vec::new(),
));
}
};
if let Some(reason) = validate_protocol_identity(&value)? {
return Ok(incomplete(reason, Vec::new()));
}
let document: DiagnosticDocument = match serde_json::from_value(value) {
Ok(document) => document,
Err(_) => {
return Ok(incomplete(
"VSG returned an incomplete diagnostic document".to_owned(),
Vec::new(),
));
}
};
if !document.complete {
let error = document
.errors
.iter()
.find(|error| !error.message.trim().is_empty())
.map(|error| (format!("{}: {}", error.kind, error.message), error));
let (detail, diagnostics) = match error {
Some((detail, error)) => (
detail,
vec![analysis_failure_diagnostic(error, document_text)],
),
None => (
"VSG diagnostic analysis did not complete".to_owned(),
vec![generic_analysis_failure_diagnostic(
"VSG diagnostic analysis did not complete",
document_text,
)],
),
};
return Ok(incomplete(detail, diagnostics));
}
if !document.errors.is_empty() {
return Ok(incomplete(
"VSG marked a complete diagnostic document with errors".to_owned(),
Vec::new(),
));
}
if let Err(error) = validate_document(&document) {
return Ok(incomplete(
format!("VSG returned invalid diagnostic data ({error})"),
Vec::new(),
));
}
let metrics = LineMetrics::new(document_text);
let diagnostics = document
.diagnostics
.iter()
.map(|finding| convert_diagnostic(&document, finding, &metrics, strict_diagnostic_severity))
.collect::<Result<Vec<_>>>();
match diagnostics {
Ok(diagnostics) => Ok(DiagnosticResponse::Complete(diagnostics)),
Err(error) => Ok(incomplete(
format!("VSG diagnostic conversion failed ({error})"),
Vec::new(),
)),
}
}
/// Rejects only an explicitly incompatible protocol identity or version.
fn validate_protocol_identity(value: &Value) -> Result<Option<String>> {
let Some(document) = value.as_object() else {
return Ok(Some(
"VSG diagnostic output was not a JSON object".to_owned(),
));
};
match document.get("schema").and_then(Value::as_str) {
Some(DIAGNOSTIC_SCHEMA) => {}
Some(schema) => bail!("unsupported VSG diagnostic schema: {schema}"),
None => {
return Ok(Some("VSG diagnostic output omitted its schema".to_owned()));
}
}
match document.get("schema_version").and_then(Value::as_u64) {
Some(version) if version == u64::from(DIAGNOSTIC_SCHEMA_VERSION) => Ok(None),
Some(version) => bail!("unsupported VSG diagnostic schema version: {version}"),
None => Ok(Some(
"VSG diagnostic output omitted its schema version".to_owned(),
)),
}
}
/// Constructs a recoverable response which replaces, rather than preserves, stale findings.
fn incomplete(message: String, diagnostics: Vec<Diagnostic>) -> DiagnosticResponse {
DiagnosticResponse::Incomplete {
message,
diagnostics,
}
}
/// Converts an incomplete analysis into a precise or whole-file non-fixable error.
fn analysis_failure_diagnostic(error: &VsgError, document_text: &str) -> Diagnostic {
if error.kind == "syntax" {
if let Some(location) = error
.location
.as_ref()
.filter(|location| location.line > 0 && location.column != Some(0))
{
let metrics = LineMetrics::new(document_text);
return Diagnostic {
range: metrics.range_for_vsg_lines(location.line, location.line),
severity: Some(DiagnosticSeverity::ERROR),
code: Some(NumberOrString::String("syntax".to_owned())),
source: Some(DIAGNOSTIC_SOURCE.to_owned()),
message: error.message.clone(),
..Diagnostic::default()
};
}
}
generic_analysis_failure_diagnostic(&error.message, document_text)
}
/// Covers the complete document when VSG cannot provide a trustworthy location.
fn generic_analysis_failure_diagnostic(message: &str, document_text: &str) -> Diagnostic {
let metrics = LineMetrics::new(document_text);
Diagnostic {
range: metrics.range_for_vsg_lines(1, u32::MAX),
severity: Some(DiagnosticSeverity::ERROR),
code: Some(NumberOrString::String("analysis-failed".to_owned())),
source: Some(DIAGNOSTIC_SOURCE.to_owned()),
message: format!(
"VSG could not analyze this document: {message}. This may indicate a syntax error or unsupported VHDL."
),
..Diagnostic::default()
}
}
/// Legacy version-one documents predate the explicit completion marker.
const fn complete_by_default() -> bool {
true
}
/// Validates invariants that cannot be expressed through deserialization.
fn validate_document(document: &DiagnosticDocument) -> Result<()> {
debug_assert_eq!(document.schema, DIAGNOSTIC_SCHEMA);
debug_assert_eq!(document.schema_version, DIAGNOSTIC_SCHEMA_VERSION);
if document.tool.name != "vsg" || document.tool.version.is_empty() {
bail!("invalid VSG tool identity");
}
if document.source.name != "stdin" {
bail!("unexpected VSG diagnostic source: {}", document.source.name);
}
let mut referenced_rules = BTreeSet::new();
for finding in &document.diagnostics {
if finding.rule.is_empty() || finding.message.is_empty() {
bail!("VSG diagnostic rule and message must be nonempty");
}
if finding.location.start_line == 0
|| finding.location.end_line == 0
|| finding.location.end_line < finding.location.start_line
{
bail!("VSG diagnostic lines must be positive and ordered");
}
if !document.rules.contains_key(&finding.rule) {
bail!("VSG diagnostic references unknown rule: {}", finding.rule);
}
referenced_rules.insert(finding.rule.as_str());
}
let metadata_rules: BTreeSet<_> = document.rules.keys().map(String::as_str).collect();
if metadata_rules != referenced_rules {
bail!("VSG diagnostic rule metadata does not match referenced rules");
}
for (rule, metadata) in &document.rules {
if metadata.severity.name.is_empty() {
bail!("VSG rule {rule} has an empty severity name");
}
severity_to_lsp(rule, &metadata.severity.kind, true)?;
validate_documentation_url(rule, "rule", metadata.documentation.rule.as_deref())?;
validate_documentation_url(
rule,
"configuration",
metadata.documentation.configuration.as_deref(),
)?;
}
Ok(())
}
/// Checks that an optional documentation destination is absolute HTTPS.
fn validate_documentation_url(rule: &str, kind: &str, value: Option<&str>) -> Result<()> {
let Some(value) = value else {
return Ok(());
};
let url = Url::parse(value)
.with_context(|| format!("VSG rule {rule} has an invalid {kind} documentation URL"))?;
if url.scheme() != "https" || url.host_str().is_none() {
bail!("VSG rule {rule} has a non-HTTPS {kind} documentation URL");
}
Ok(())
}
/// Converts one validated VSG finding to an LSP diagnostic.
fn convert_diagnostic(
document: &DiagnosticDocument,
finding: &VsgDiagnostic,
metrics: &LineMetrics,
strict_diagnostic_severity: bool,
) -> Result<Diagnostic> {
let metadata = document
.rules
.get(&finding.rule)
.context("validated VSG diagnostic lost its rule metadata")?;
let code_description = metadata
.documentation
.rule
.as_deref()
.map(Url::parse)
.transpose()
.context("validated VSG documentation URL became invalid")?
.map(|href| CodeDescription { href });
let data = serde_json::to_value(DiagnosticData {
schema_version: document.schema_version,
tool_version: document.tool.version.clone(),
rule: finding.rule.clone(),
line: finding.location.start_line,
metadata: metadata.clone(),
})
.context("failed to retain VSG diagnostic metadata")?;
Ok(Diagnostic {
range: metrics.range_for_vsg_lines(finding.location.start_line, finding.location.end_line),
severity: Some(severity_to_lsp(
&finding.rule,
&metadata.severity.kind,
strict_diagnostic_severity,
)?),
code: Some(NumberOrString::String(finding.rule.clone())),
code_description,
source: Some(DIAGNOSTIC_SOURCE.to_owned()),
message: finding.message.clone(),
data: Some(data),
..Diagnostic::default()
})
}
/// Maps the closed set of VSG semantic severity types to LSP.
fn severity_to_lsp(
rule: &str,
severity: &str,
strict_diagnostic_severity: bool,
) -> Result<DiagnosticSeverity> {
match (severity, strict_diagnostic_severity) {
("error", true) => Ok(DiagnosticSeverity::ERROR),
("error", false) => Ok(DiagnosticSeverity::WARNING),
("warning", true) => Ok(DiagnosticSeverity::WARNING),
("warning", false) | ("information", _) => Ok(DiagnosticSeverity::INFORMATION),
_ => bail!("VSG rule {rule} has unknown severity type: {severity}"),
}
}
#[cfg(test)]
mod tests {
//! Unit tests for the VSG protocol and LSP position conversion.
use super::{parse_diagnostics, DiagnosticData, DiagnosticResponse, LineMetrics};
use serde_json::{json, Value};
use tower_lsp::lsp_types::{DiagnosticSeverity, NumberOrString, Position, Range};
/// Builds a realistic diagnostic document with replaceable findings.
fn document(rules: Value, diagnostics: Value) -> String {
json!({
"schema": "vsg.diagnostics",
"schema_version": 1,
"tool": {"name": "vsg", "version": "3.35.0"},
"source": {"name": "stdin"},
"rules": rules,
"diagnostics": diagnostics,
})
.to_string()
}
/// Builds complete metadata for one rule.
fn metadata(severity_type: &str, rule_url: Value) -> Value {
json!({
"severity": {"name": "Style", "type": severity_type},
"fixable": true,
"phase": 3,
"subphase": 1,
"configuration": {"case": "upper", "disable": false},
"documentation": {
"rule": rule_url,
"configuration": null,
},
})
}
/// Extracts diagnostics from a response expected to be complete.
fn complete(output: &str, text: &str) -> Vec<tower_lsp::lsp_types::Diagnostic> {
complete_with_mode(output, text, false)
}
/// Extracts diagnostics using the requested severity behavior.
fn complete_with_mode(
output: &str,
text: &str,
strict_diagnostic_severity: bool,
) -> Vec<tower_lsp::lsp_types::Diagnostic> {
match parse_diagnostics(output, text, strict_diagnostic_severity)
.expect("compatible protocol")
{
DiagnosticResponse::Complete(diagnostics) => diagnostics,
DiagnosticResponse::Incomplete { message, .. } => {
panic!("unexpected incomplete response: {message}")
}
}
}
/// Extracts the reason from a response expected to be recoverably incomplete.
fn incomplete(output: &str, text: &str) -> String {
match parse_diagnostics(output, text, false).expect("compatible protocol") {
DiagnosticResponse::Complete(_) => panic!("unexpected complete response"),
DiagnosticResponse::Incomplete { message, .. } => message,
}
}
/// A representative document retains protocol metadata and UTF-16 range.
#[test]
fn parses_versioned_diagnostic_document() {
let output = document(
json!({
"entity_008": metadata(
"warning",
json!("https://example.com/entity.html#entity-008"),
),
}),
json!([{
"rule": "entity_008",
"location": {"start_line": 2, "end_line": 2},
"message": "Change é😀 to upper case",
}]),
);
let diagnostics = complete(&output, "first\né😀");
let diagnostic = &diagnostics[0];
assert_eq!(diagnostic.severity, Some(DiagnosticSeverity::INFORMATION));
assert_eq!(
diagnostic.code,
Some(NumberOrString::String("entity_008".to_owned()))
);
assert_eq!(
diagnostic.range,
Range::new(Position::new(1, 0), Position::new(1, 3))
);
assert_eq!(
diagnostic
.code_description
.as_ref()
.expect("rule link")
.href
.as_str(),
"https://example.com/entity.html#entity-008"
);
let data: DiagnosticData =
serde_json::from_value(diagnostic.data.clone().expect("diagnostic metadata"))
.expect("valid retained metadata");
assert_eq!(data.rule, "entity_008");
assert_eq!(data.line, 2);
assert_eq!(data.metadata.severity.name, "Style");
assert!(data.metadata.fixable);
}
/// A complete empty result maps to an empty diagnostic list.
#[test]
fn parses_empty_document() {
let output = document(json!({}), json!([]));
assert!(complete(&output, "").is_empty());
}
/// Malformed JSON is recoverable and cannot terminate the language server.
#[test]
fn contains_malformed_json() {
let reason = incomplete("not JSON", "");
assert!(reason.contains("malformed diagnostic JSON"));
}
/// Structurally partial responses remain recoverable and distinct from clean results.
#[test]
fn contains_structurally_incomplete_documents() {
for (value, expected) in [
(json!([]), "not a JSON object"),
(json!({}), "omitted its schema"),
(
json!({"schema": "vsg.diagnostics"}),
"omitted its schema version",
),
(
json!({"schema": "vsg.diagnostics", "schema_version": 1}),
"incomplete diagnostic document",
),
] {
assert!(incomplete(&value.to_string(), "").contains(expected));
}
let mut no_error: Value =
serde_json::from_str(&document(json!({}), json!([]))).expect("fixture document");
no_error["complete"] = json!(false);
assert!(incomplete(&no_error.to_string(), "").contains("did not complete"));
let mut contradictory: Value =
serde_json::from_str(&document(json!({}), json!([]))).expect("fixture document");
contradictory["errors"] = json!([{"kind": "analysis", "message": "unexpected error"}]);
assert!(incomplete(&contradictory.to_string(), "").contains("marked a complete"));
}
/// VSG may explicitly report a valid but incomplete analysis.
#[test]
fn accepts_incomplete_diagnostic_document() {
let output = json!({
"schema": "vsg.diagnostics",
"schema_version": 1,
"complete": false,
"tool": {"name": "vsg", "version": "3.35.0"},
"source": {"name": "stdin"},
"rules": {},
"diagnostics": [],
"errors": [{"kind": "analysis", "message": "could not parse source"}],
})
.to_string();
assert_eq!(
incomplete(&output, "source"),
"analysis: could not parse source"
);
}
/// An unlocated analysis failure remains visible as a whole-document error.
#[test]
fn converts_unlocated_analysis_failure() {
let output = json!({
"schema": "vsg.diagnostics",
"schema_version": 1,
"complete": false,
"tool": {"name": "vsg", "version": "3.35.0"},
"source": {"name": "stdin"},
"rules": {},
"diagnostics": [],
"errors": [{"kind": "analysis", "message": "parser stopped"}],
})
.to_string();
let DiagnosticResponse::Incomplete { diagnostics, .. } =
parse_diagnostics(&output, "first\nsecond", false)
.expect("compatible incomplete response")
else {
panic!("expected incomplete response")
};
assert_eq!(diagnostics.len(), 1);
assert_eq!(diagnostics[0].severity, Some(DiagnosticSeverity::ERROR));
assert_eq!(
diagnostics[0].range,
Range::new(Position::new(0, 0), Position::new(1, 6))
);
assert_eq!(
diagnostics[0].code,
Some(NumberOrString::String("analysis-failed".to_owned()))
);
assert!(diagnostics[0]
.message
.contains("may indicate a syntax error"));
assert!(diagnostics[0].data.is_none());
}
/// A located syntax failure becomes an editor diagnostic without correction data.
#[test]
fn converts_located_syntax_failure() {
let output = json!({
"schema": "vsg.diagnostics",
"schema_version": 1,
"complete": false,
"tool": {"name": "vsg", "version": "3.35.0"},
"source": {"name": "stdin"},
"rules": {},
"diagnostics": [],
"errors": [{
"kind": "syntax",
"message": "Unexpected token; expected ;",
"location": {"line": 2, "column": 3},
}],
})
.to_string();
let DiagnosticResponse::Incomplete {
message,
diagnostics,
} = parse_diagnostics(&output, "first\nabc\n", false)
.expect("compatible incomplete response")
else {
panic!("expected incomplete response")
};
assert!(message.contains("Unexpected token"));
assert_eq!(diagnostics.len(), 1);
assert_eq!(diagnostics[0].severity, Some(DiagnosticSeverity::ERROR));
assert_eq!(
diagnostics[0].range,
Range::new(Position::new(1, 0), Position::new(1, 3))
);
assert_eq!(
diagnostics[0].code,
Some(NumberOrString::String("syntax".to_owned()))
);
assert!(diagnostics[0].data.is_none());
}
/// Unknown protocol identities and versions fail visibly.
#[test]
fn rejects_unsupported_protocol() {
let mut value: Value =
serde_json::from_str(&document(json!({}), json!([]))).expect("fixture document");
value["schema_version"] = json!(2);
assert!(parse_diagnostics(&value.to_string(), "", false)
.expect_err("unsupported version")
.to_string()
.contains("schema version"));
value["schema_version"] = json!(1);
value["schema"] = json!("different.protocol");
assert!(parse_diagnostics(&value.to_string(), "", false)
.expect_err("unsupported schema")
.to_string()
.contains("schema"));
}
/// Required identity and finding fields are rejected independently.
#[test]
fn rejects_incomplete_protocol_metadata() {
let valid = || {
serde_json::from_str::<Value>(&document(
json!({"rule_001": metadata("warning", Value::Null)}),
json!([{
"rule": "rule_001",
"location": {"start_line": 1, "end_line": 1},
"message": "message",
}]),
))
.expect("fixture document")
};
let mut value = valid();
value["tool"]["name"] = json!("another-tool");
assert!(incomplete(&value.to_string(), "x").contains("tool identity"));
let mut value = valid();
value["source"]["name"] = json!("file");
assert!(incomplete(&value.to_string(), "x").contains("diagnostic source"));
let mut value = valid();
value["diagnostics"][0]["message"] = json!("");
assert!(incomplete(&value.to_string(), "x").contains("must be nonempty"));
let mut value = valid();
value["rules"]["rule_001"]["severity"]["name"] = json!("");
assert!(incomplete(&value.to_string(), "x").contains("empty severity name"));
}
/// Editor-friendly severity is the default while strict mode preserves VSG levels.
#[test]
fn maps_diagnostic_severity_modes() {
for (kind, relaxed, strict) in [
(
"error",
DiagnosticSeverity::WARNING,
DiagnosticSeverity::ERROR,
),
(
"warning",
DiagnosticSeverity::INFORMATION,
DiagnosticSeverity::WARNING,
),
(
"information",
DiagnosticSeverity::INFORMATION,
DiagnosticSeverity::INFORMATION,
),
] {
let output = document(
json!({"rule_001": metadata(kind, Value::Null)}),
json!([{
"rule": "rule_001",
"location": {"start_line": 1, "end_line": 1},
"message": "message",
}]),
);
assert_eq!(
complete_with_mode(&output, "x", false)[0].severity,
Some(relaxed)
);
assert_eq!(
complete_with_mode(&output, "x", true)[0].severity,
Some(strict)
);
}
}
/// Unknown severity types are rejected rather than guessed.
#[test]
fn rejects_unknown_severity_type() {
let output = document(
json!({"rule_001": metadata("critical", Value::Null)}),
json!([{
"rule": "rule_001",
"location": {"start_line": 1, "end_line": 1},
"message": "message",
}]),
);
assert!(incomplete(&output, "x").contains("unknown severity type"));
}
/// Rule metadata must correspond exactly to referenced findings.
#[test]
fn rejects_dangling_and_unreferenced_rules() {
let dangling = document(
json!({}),
json!([{
"rule": "missing_001",
"location": {"start_line": 1, "end_line": 1},
"message": "message",
}]),
);
assert!(incomplete(&dangling, "x").contains("unknown rule"));
let unreferenced = document(
json!({"extra_001": metadata("error", Value::Null)}),
json!([]),
);
assert!(incomplete(&unreferenced, "x").contains("does not match"));
}
/// Lines must be positive and ordered before safe LSP clamping.
#[test]
fn rejects_invalid_lines() {
for location in [
json!({"start_line": 0, "end_line": 1}),
json!({"start_line": 2, "end_line": 1}),
] {
let output = document(
json!({"rule_001": metadata("error", Value::Null)}),
json!([{"rule": "rule_001", "location": location, "message": "m"}]),
);
assert!(incomplete(&output, "x").contains("positive and ordered"));
}
}
/// Documentation links must be absolute HTTPS URLs when present.
#[test]
fn rejects_malformed_documentation_urls() {
for url in [json!("not a URL"), json!("http://example.com/rule")] {
let output = document(
json!({"rule_001": metadata("error", url)}),
json!([{
"rule": "rule_001",
"location": {"start_line": 1, "end_line": 1},
"message": "message",
}]),
);
assert!(incomplete(&output, "x").contains("documentation URL"));
}
}
/// CRLF terminators are not included in reported line widths.
#[test]
fn excludes_crlf_from_line_width() {
let metrics = LineMetrics::new("abc\r\ndef");
assert_eq!(
metrics.range_for_vsg_lines(1, 1),
Range::new(Position::new(0, 0), Position::new(0, 3))
);
}
/// Empty text, a final line, and out-of-range lines remain safe.
#[test]
fn clamps_ranges_to_document_lines() {
assert_eq!(
LineMetrics::new("").range_for_vsg_lines(1, 1),
Range::new(Position::new(0, 0), Position::new(0, 0))
);
assert_eq!(
LineMetrics::new("abc\n").range_for_vsg_lines(2, 99),
Range::new(Position::new(1, 0), Position::new(1, 0))
);
}
}

228
src/edits.rs Normal file
View File

@ -0,0 +1,228 @@
//! Safe conversion of complete VSG output into LSP edits.
use tower_lsp::lsp_types::{
DocumentChanges, OneOf, OptionalVersionedTextDocumentIdentifier, Position, Range,
TextDocumentEdit, TextEdit, Url, WorkspaceEdit,
};
/// Builds the smallest whole-line edit that reproduces VSG's complete output.
pub(crate) fn workspace_edit(
uri: Url,
version: i32,
original: &str,
corrected: &str,
) -> Option<WorkspaceEdit> {
let text_edit = text_edit(original, corrected)?;
Some(WorkspaceEdit {
document_changes: Some(DocumentChanges::Edits(vec![TextDocumentEdit {
text_document: OptionalVersionedTextDocumentIdentifier {
uri,
version: Some(version),
},
edits: vec![OneOf::Left(text_edit)],
}])),
..WorkspaceEdit::default()
})
}
/// Builds the smallest whole-line text edit that reproduces VSG's output.
pub(crate) fn text_edit(original: &str, corrected: &str) -> Option<TextEdit> {
if original == corrected {
return None;
}
let old_lines: Vec<_> = original.split_inclusive('\n').collect();
let new_lines: Vec<_> = corrected.split_inclusive('\n').collect();
let mut prefix = 0;
while prefix < old_lines.len()
&& prefix < new_lines.len()
&& old_lines[prefix] == new_lines[prefix]
{
prefix += 1;
}
let mut suffix = 0;
while suffix < old_lines.len().saturating_sub(prefix)
&& suffix < new_lines.len().saturating_sub(prefix)
&& old_lines[old_lines.len() - 1 - suffix] == new_lines[new_lines.len() - 1 - suffix]
{
suffix += 1;
}
let old_end = old_lines.len() - suffix;
let new_end = new_lines.len() - suffix;
let start = Position::new(u32::try_from(prefix).unwrap_or(u32::MAX), 0);
let end = if old_end < old_lines.len() {
Position::new(u32::try_from(old_end).unwrap_or(u32::MAX), 0)
} else {
document_end(original)
};
let new_text = new_lines[prefix..new_end].concat();
Some(TextEdit {
range: Range::new(start, end),
new_text,
})
}
/// Finds the UTF-16 end position of a complete LSP document.
fn document_end(text: &str) -> Position {
let line = text.rsplit_once('\n').map_or(text, |(_, line)| line);
let line = line.strip_suffix('\r').unwrap_or(line);
let line_count = text.bytes().filter(|byte| *byte == b'\n').count();
Position::new(
u32::try_from(line_count).unwrap_or(u32::MAX),
u32::try_from(line.encode_utf16().count()).unwrap_or(u32::MAX),
)
}
#[cfg(test)]
mod tests {
//! Edit computation and application regression tests.
use super::{text_edit, workspace_edit};
use tower_lsp::lsp_types::{DocumentChanges, OneOf, Position, Url};
/// Extracts the single plain text edit returned by the helper.
fn edit(original: &str, corrected: &str) -> tower_lsp::lsp_types::TextEdit {
let workspace = workspace_edit(
Url::parse("file:///tmp/example.vhd").expect("valid URI"),
7,
original,
corrected,
)
.expect("changed output");
let Some(DocumentChanges::Edits(documents)) = workspace.document_changes else {
panic!("expected versioned document edit")
};
assert_eq!(documents[0].text_document.version, Some(7));
let OneOf::Left(edit) = &documents[0].edits[0] else {
panic!("expected plain text edit")
};
edit.clone()
}
/// Converts a UTF-16 LSP position to a byte boundary in test text.
fn byte_offset(text: &str, position: Position) -> usize {
let mut offset = 0;
for (index, line) in text.split_inclusive('\n').enumerate() {
if index == position.line as usize {
let content = line.strip_suffix('\n').unwrap_or(line);
let content = content.strip_suffix('\r').unwrap_or(content);
let mut utf16 = 0;
for (byte, character) in content.char_indices() {
if utf16 == position.character {
return offset + byte;
}
utf16 += u32::try_from(character.len_utf16()).expect("UTF-16 width");
}
assert_eq!(utf16, position.character);
return offset + content.len();
}
offset += line.len();
}
assert_eq!(
position.line as usize,
text.bytes().filter(|byte| *byte == b'\n').count()
);
assert_eq!(position.character, 0);
text.len()
}
/// Applies one computed LSP edit and checks the complete resulting text.
fn assert_reproduces(original: &str, corrected: &str) {
let edit = edit(original, corrected);
let start = byte_offset(original, edit.range.start);
let end = byte_offset(original, edit.range.end);
let mut applied = original.to_owned();
applied.replace_range(start..end, &edit.new_text);
assert_eq!(applied, corrected);
}
/// A same-line change produces a whole-line replacement.
#[test]
fn replaces_one_complete_line() {
let edit = edit("first\nbad\nlast\n", "first\nGOOD\nlast\n");
assert_eq!(edit.range.start, Position::new(1, 0));
assert_eq!(edit.range.end, Position::new(2, 0));
assert_eq!(edit.new_text, "GOOD\n");
}
/// Insertions and deletions are anchored between unchanged lines.
#[test]
fn handles_line_insertion_and_deletion() {
let insertion = edit("first\nlast", "first\ninserted\nlast");
assert_eq!(insertion.range.start, Position::new(1, 0));
assert_eq!(insertion.range.end, Position::new(1, 0));
assert_eq!(insertion.new_text, "inserted\n");
let deletion = edit("first\nremoved\nlast", "first\nlast");
assert_eq!(deletion.range.start, Position::new(1, 0));
assert_eq!(deletion.range.end, Position::new(2, 0));
assert_eq!(deletion.new_text, "");
}
/// Unicode columns and CRLF endings are preserved at the document end.
#[test]
fn uses_utf16_at_unicode_crlf_document_end() {
let edit = edit("same\r\né😀", "same\r\nÉ😀");
assert_eq!(edit.range.start, Position::new(1, 0));
assert_eq!(edit.range.end, Position::new(1, 3));
assert_eq!(edit.new_text, "É😀");
}
/// Identical formatter output produces no action edit.
#[test]
fn ignores_unchanged_output() {
assert!(text_edit("same", "same").is_none());
assert!(workspace_edit(
Url::parse("file:///tmp/example.vhd").expect("valid URI"),
1,
"same",
"same",
)
.is_none());
}
/// A deterministic corpus covers boundaries, line shifts, Unicode, and CRLF.
#[test]
fn line_edits_reproduce_structured_corpus() {
for (original, corrected) in [
("bad", "GOOD"),
("first\nbad\nlast\n", "first\nGOOD\nlast\n"),
("first\nlast", "first\ninserted\nlast"),
("first\nremoved\nlast", "first\nlast"),
("é😀\nlast", "É😀\nlast"),
("first\r\nbad\r\nlast\r\n", "first\r\nGOOD\r\nlast\r\n"),
("first\nlast", "inserted\nfirst\nlast"),
("first\nlast", "first\nlast\ninserted\n"),
] {
assert_reproduces(original, corrected);
}
}
/// Fixed-seed structured mutations exercise many whole-line edit shapes.
#[test]
fn line_edits_reproduce_bounded_generated_cases() {
let mut state = 0x5eed_u64;
for case in 0..128 {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1);
let indent = " ".repeat((state as usize) % 9);
let ending = if state & 1 == 0 { "\n" } else { "\r\n" };
let original = format!("entity sample is{ending}{indent}é😀 <= a;{ending}end;{ending}");
let corrected = match case % 4 {
0 => format!("entity SAMPLE is{ending}{indent}é😀 <= a;{ending}end;{ending}"),
1 => {
format!("entity sample is{ending}{indent}é😀 <= a;{ending}{ending}end;{ending}")
}
2 => format!("entity sample is{ending}{indent}é😀<=a;{ending}end;{ending}"),
_ => format!("entity sample is{ending} {indent}é😀 <= a;{ending}end;{ending}"),
};
assert_reproduces(&original, &corrected);
}
}
}

636
src/lib.rs Normal file
View File

@ -0,0 +1,636 @@
//! Language Server Protocol diagnostics backed by VHDL Style Guide.
//!
//! The crate keeps protocol handling, diagnostic parsing, and subprocess
//! execution separate so each boundary can be tested independently.
#![warn(clippy::missing_docs_in_private_items)]
mod diagnostics;
mod edits;
mod presentation;
mod runner;
mod server;
use anyhow::{Context, Result};
use clap::Parser;
use serde::{Deserialize, Serialize};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::io::{AsyncRead, AsyncWrite};
use tower_lsp::{LspService, Server};
pub use runner::{ProcessVsgRunner, VsgRunner};
pub use server::Backend;
/// Package version paired with the source revision used for this build.
pub const VERSION: &str = concat!(
env!("CARGO_PKG_VERSION"),
"+git.",
env!("VSG_BRIDGE_GIT_SHA")
);
/// Project-local bridge configuration filename.
const PROJECT_CONFIG: &str = "vsg-bridge-ls.toml";
/// Path below the user's XDG configuration directory.
const USER_CONFIG: &str = "vsg-bridge-ls/config.toml";
/// Command-line configuration for the language server.
#[derive(Clone, Debug, Parser, PartialEq, Eq)]
#[command(version = VERSION, about, long_about = None)]
pub struct Options {
/// VSG configuration files, in the order in which VSG should load them.
#[arg(short, long)]
pub configuration: Vec<String>,
/// Allows a code action that opens rule documentation in a browser.
#[arg(long)]
pub allow_browser_action: bool,
/// Offers opt-in per-rule corrections for one diagnosed line.
#[arg(long)]
pub experimental_rule_fix: bool,
/// Offers an opt-in action that fixes all reported rules on one line.
#[arg(long)]
pub experimental_multi_rule_line_fix: bool,
/// Adds runtime state to hover and offers a fallback action.
#[arg(long)]
pub debug_mode: bool,
/// Disables VSG hover responses for multi-server editor setups.
#[arg(long)]
pub disable_hover: bool,
/// Preserves VSG lint severities instead of using editor-friendly levels.
#[arg(long)]
pub strict_diagnostic_severity: bool,
/// Writes vsg-bridge-ls.toml in the current directory, then exits.
#[arg(long)]
pub write_config: bool,
}
/// Serializable project configuration generated from command-line options.
#[derive(Debug, Serialize)]
struct GeneratedFileOptions<'a> {
/// VSG configuration paths forwarded in their declared order.
vsg_configuration: &'a [String],
/// Whether browser-opening documentation actions are offered.
allow_browser_action: bool,
/// Whether individual rule corrections are offered.
experimental_rule_fix: bool,
/// Whether grouped same-line corrections are offered.
experimental_multi_rule_line_fix: bool,
/// Whether runtime debug information is exposed.
debug_mode: bool,
/// Whether VSG hover responses are disabled.
disable_hover: bool,
/// Whether VSG lint severities map directly to LSP severities.
strict_diagnostic_severity: bool,
}
/// Optional settings read from one TOML configuration layer.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
struct FileOptions {
/// VSG configuration paths forwarded in their declared order.
vsg_configuration: Option<Vec<String>>,
/// Whether browser-opening documentation actions are offered.
allow_browser_action: Option<bool>,
/// Whether individual rule corrections are offered.
experimental_rule_fix: Option<bool>,
/// Whether grouped same-line corrections are offered.
experimental_multi_rule_line_fix: Option<bool>,
/// Whether runtime debug information is exposed.
debug_mode: Option<bool>,
/// Whether VSG hover responses are disabled.
disable_hover: Option<bool>,
/// Whether VSG lint severities map directly to LSP severities.
strict_diagnostic_severity: Option<bool>,
}
impl FileOptions {
/// Applies every explicitly configured value from a higher-priority layer.
fn overlay(&mut self, higher: Self) {
if higher.vsg_configuration.is_some() {
self.vsg_configuration = higher.vsg_configuration;
}
if higher.allow_browser_action.is_some() {
self.allow_browser_action = higher.allow_browser_action;
}
if higher.experimental_rule_fix.is_some() {
self.experimental_rule_fix = higher.experimental_rule_fix;
}
if higher.experimental_multi_rule_line_fix.is_some() {
self.experimental_multi_rule_line_fix = higher.experimental_multi_rule_line_fix;
}
if higher.debug_mode.is_some() {
self.debug_mode = higher.debug_mode;
}
if higher.disable_hover.is_some() {
self.disable_hover = higher.disable_hover;
}
if higher.strict_diagnostic_severity.is_some() {
self.strict_diagnostic_severity = higher.strict_diagnostic_severity;
}
}
}
impl Options {
/// Loads user and project configuration, then applies explicit CLI values.
pub fn resolve(self) -> Result<Self> {
let user = user_config_path();
let project = std::env::current_dir()
.context("failed to determine the working directory")?
.join(PROJECT_CONFIG);
self.resolve_from_paths(user.as_deref(), &project)
}
/// Resolves configuration using injectable paths for deterministic tests.
fn resolve_from_paths(self, user: Option<&Path>, project: &Path) -> Result<Self> {
let mut file = FileOptions::default();
if let Some(user) = user {
if let Some(user) = read_file_options(user)? {
file.overlay(user);
}
}
if let Some(project) = read_file_options(project)? {
file.overlay(project);
}
Ok(Self {
configuration: if self.configuration.is_empty() {
file.vsg_configuration.unwrap_or_default()
} else {
self.configuration
},
allow_browser_action: self.allow_browser_action
|| file.allow_browser_action.unwrap_or(false),
experimental_rule_fix: self.experimental_rule_fix
|| file.experimental_rule_fix.unwrap_or(false),
experimental_multi_rule_line_fix: self.experimental_multi_rule_line_fix
|| file.experimental_multi_rule_line_fix.unwrap_or(false),
debug_mode: self.debug_mode || file.debug_mode.unwrap_or(false),
disable_hover: self.disable_hover || file.disable_hover.unwrap_or(false),
strict_diagnostic_severity: self.strict_diagnostic_severity
|| file.strict_diagnostic_severity.unwrap_or(false),
write_config: self.write_config,
})
}
/// Writes a new project configuration in the current working directory.
pub fn write_project_configuration(&self) -> Result<PathBuf> {
let path = std::env::current_dir()
.context("failed to determine the working directory")?
.join(PROJECT_CONFIG);
self.write_configuration(&path)?;
Ok(path)
}
/// Serializes supplied runtime options without overwriting an existing file.
fn write_configuration(&self, path: &Path) -> Result<()> {
let configuration = GeneratedFileOptions {
vsg_configuration: &self.configuration,
allow_browser_action: self.allow_browser_action,
experimental_rule_fix: self.experimental_rule_fix,
experimental_multi_rule_line_fix: self.experimental_multi_rule_line_fix,
debug_mode: self.debug_mode,
disable_hover: self.disable_hover,
strict_diagnostic_severity: self.strict_diagnostic_severity,
};
let body = toml::to_string_pretty(&configuration)
.context("failed to serialize bridge configuration")?;
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.with_context(|| format!("failed to create {}", path.display()))?;
file.write_all(
format!(
"# Generated by vsg-bridge-ls --write-config.\n# Edit these values, then restart the editor language server.\n\n{body}"
)
.as_bytes(),
)
.with_context(|| format!("failed to write {}", path.display()))
}
/// Converts configuration paths into the argument vector expected by VSG.
#[must_use]
pub fn vsg_arguments(&self) -> Vec<String> {
self.configuration
.iter()
.flat_map(|path| ["-c".to_owned(), path.clone()])
.collect()
}
}
/// Reads one optional TOML layer while distinguishing absence from failure.
fn read_file_options(path: &Path) -> Result<Option<FileOptions>> {
let source = match std::fs::read_to_string(path) {
Ok(source) => source,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => {
return Err(error).with_context(|| format!("failed to read {}", path.display()))
}
};
toml::from_str(&source)
.with_context(|| format!("invalid bridge configuration {}", path.display()))
.map(Some)
}
/// Finds the conventional user configuration without requiring it to exist.
fn user_config_path() -> Option<PathBuf> {
std::env::var_os("XDG_CONFIG_HOME")
.filter(|path| !path.is_empty())
.map(PathBuf::from)
.or_else(|| {
std::env::var_os("HOME")
.filter(|path| !path.is_empty())
.map(|home| PathBuf::from(home).join(".config"))
})
.map(|root| root.join(USER_CONFIG))
}
/// Runs the language server over standard input and standard output.
pub async fn run_stdio(options: Options) {
let runner: Arc<dyn VsgRunner> = Arc::new(ProcessVsgRunner::default());
run(tokio::io::stdin(), tokio::io::stdout(), options, runner).await;
}
/// Runs one language-server connection over the supplied byte streams.
///
/// This is useful for embedding the bridge and keeps the protocol transport
/// independently testable. Normal command-line users should call
/// [`run_stdio`] instead.
pub async fn run<I, O>(input: I, output: O, options: Options, runner: Arc<dyn VsgRunner>)
where
I: AsyncRead + Unpin,
O: AsyncWrite,
{
let vsg_arguments = options.vsg_arguments();
let (service, socket) = LspService::new(move |client| {
Backend::new(client, Arc::clone(&runner), vsg_arguments.clone())
.with_browser_action(options.allow_browser_action)
.with_experimental_rule_fix(options.experimental_rule_fix)
.with_experimental_multi_rule_line_fix(options.experimental_multi_rule_line_fix)
.with_debug_mode(options.debug_mode)
.with_hover_disabled(options.disable_hover)
.with_strict_diagnostic_severity(options.strict_diagnostic_severity)
});
Server::new(input, output, socket).serve(service).await;
}
#[cfg(test)]
mod tests {
//! Unit tests for command-line option translation.
use super::{run, FileOptions, Options, VERSION};
use crate::VsgRunner;
use anyhow::Result;
use clap::{CommandFactory, Parser};
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
/// Runner used when exercising requests that do not invoke VSG.
#[derive(Debug)]
struct UnusedRunner;
/// Process-local suffix for collision-free temporary test directories.
static NEXT_TEMP_DIRECTORY: AtomicU64 = AtomicU64::new(0);
/// Removes a test directory and its configuration files on drop.
struct TestDirectory(PathBuf);
impl TestDirectory {
/// Creates an isolated directory below the system temporary directory.
fn new() -> Self {
let suffix = NEXT_TEMP_DIRECTORY.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"vsg-bridge-ls-config-{}-{suffix}",
std::process::id()
));
std::fs::create_dir(&path).expect("create temporary configuration directory");
Self(path)
}
/// Returns the temporary directory path.
fn path(&self) -> &std::path::Path {
&self.0
}
}
impl Drop for TestDirectory {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[tower_lsp::async_trait]
impl VsgRunner for UnusedRunner {
async fn lint(&self, _: &str, _: &[String]) -> Result<String> {
panic!("lifecycle-only transport test must not invoke VSG");
}
}
/// Frames a JSON-RPC payload according to the LSP base protocol.
fn frame(payload: &str) -> String {
format!("Content-Length: {}\r\n\r\n{payload}", payload.len())
}
/// Reads one LSP frame and returns its JSON-RPC payload.
async fn read_frame(reader: &mut (impl tokio::io::AsyncRead + Unpin)) -> String {
let mut header = Vec::new();
while !header.ends_with(b"\r\n\r\n") {
let mut byte = [0];
reader.read_exact(&mut byte).await.expect("read LSP header");
header.push(byte[0]);
}
let header = String::from_utf8(header).expect("ASCII LSP header");
let content_length = header
.lines()
.find_map(|line| line.strip_prefix("Content-Length: "))
.expect("content-length header")
.parse::<usize>()
.expect("numeric content length");
let mut payload = vec![0; content_length];
reader
.read_exact(&mut payload)
.await
.expect("read LSP payload");
String::from_utf8(payload).expect("UTF-8 JSON-RPC payload")
}
/// Configuration paths retain their input order and each receive `-c`.
#[test]
fn builds_vsg_configuration_arguments() {
let options = Options::try_parse_from([
"vsg-bridge-ls",
"-c",
"first.yaml",
"--configuration",
"second.yaml",
])
.expect("valid command-line options");
assert_eq!(
options.vsg_arguments(),
["-c", "first.yaml", "-c", "second.yaml"]
);
}
/// No configuration option produces an empty VSG argument vector.
#[test]
fn accepts_no_configuration_files() {
let options = Options::try_parse_from(["vsg-bridge-ls"])
.expect("options without configuration files are valid");
assert!(options.vsg_arguments().is_empty());
assert!(!options.allow_browser_action);
assert!(!options.experimental_rule_fix);
assert!(!options.experimental_multi_rule_line_fix);
assert!(!options.debug_mode);
assert!(!options.disable_hover);
assert!(!options.strict_diagnostic_severity);
assert!(!options.write_config);
}
/// CLI version output identifies both the release and source revision.
#[test]
fn version_includes_source_revision() {
assert_eq!(Options::command().get_version(), Some(VERSION));
assert!(VERSION.starts_with("0.3.6-rc.1+git."));
assert!(VERSION
.strip_prefix("0.3.6-rc.1+git.")
.is_some_and(|revision| revision == "unknown"
|| (revision.len() == 8 && revision.bytes().all(|byte| byte.is_ascii_hexdigit()))));
}
/// Browser-opening actions require an explicit runtime opt-in.
#[test]
fn parses_allow_browser_action_flag() {
let options = Options::try_parse_from(["vsg-bridge-ls", "--allow-browser-action"])
.expect("browser flag is valid");
assert!(options.allow_browser_action);
}
/// User settings are overlaid by project settings and explicit CLI values.
#[test]
fn resolves_layered_toml_configuration() {
let directory = TestDirectory::new();
let user = directory.path().join("user.toml");
let project = directory.path().join("project.toml");
std::fs::write(
&user,
r#"
vsg_configuration = ["user.yaml"]
allow_browser_action = true
experimental_rule_fix = true
debug_mode = true
disable_hover = true
strict_diagnostic_severity = true
"#,
)
.expect("write user configuration");
std::fs::write(
&project,
r#"
allow_browser_action = false
experimental_rule_fix = false
experimental_multi_rule_line_fix = true
debug_mode = false
disable_hover = false
strict_diagnostic_severity = false
"#,
)
.expect("write project configuration");
let from_files = Options::try_parse_from(["vsg-bridge-ls"])
.expect("default CLI")
.resolve_from_paths(Some(&user), &project)
.expect("layered configuration");
assert_eq!(from_files.configuration, ["user.yaml"]);
assert!(!from_files.allow_browser_action);
assert!(!from_files.experimental_rule_fix);
assert!(from_files.experimental_multi_rule_line_fix);
assert!(!from_files.debug_mode);
assert!(!from_files.disable_hover);
assert!(!from_files.strict_diagnostic_severity);
let from_cli = Options::try_parse_from([
"vsg-bridge-ls",
"--configuration",
"cli.yaml",
"--allow-browser-action",
"--experimental-rule-fix",
"--debug-mode",
"--disable-hover",
"--strict-diagnostic-severity",
])
.expect("explicit CLI")
.resolve_from_paths(Some(&user), &project)
.expect("CLI overrides");
assert_eq!(from_cli.configuration, ["cli.yaml"]);
assert!(from_cli.allow_browser_action);
assert!(from_cli.experimental_rule_fix);
assert!(from_cli.experimental_multi_rule_line_fix);
assert!(from_cli.debug_mode);
assert!(from_cli.disable_hover);
assert!(from_cli.strict_diagnostic_severity);
}
/// Invalid configuration fails with the responsible path.
#[test]
fn rejects_invalid_toml_configuration() {
let directory = TestDirectory::new();
let project = directory.path().join("project.toml");
std::fs::write(&project, "debug_mode = maybe").expect("write invalid configuration");
let error = Options::try_parse_from(["vsg-bridge-ls"])
.expect("default CLI")
.resolve_from_paths(None, &project)
.expect_err("invalid TOML must fail");
assert!(error.to_string().contains("invalid bridge configuration"));
assert!(error.to_string().contains("project.toml"));
}
/// Per-rule corrections require an explicit runtime opt-in.
#[test]
fn parses_experimental_rule_fix_flag() {
let options = Options::try_parse_from(["vsg-bridge-ls", "--experimental-rule-fix"])
.expect("experimental flag is valid");
assert!(options.experimental_rule_fix);
}
/// The multi-rule line action requires an explicit runtime opt-in.
#[test]
fn parses_experimental_multi_rule_line_flag() {
let options =
Options::try_parse_from(["vsg-bridge-ls", "--experimental-multi-rule-line-fix"])
.expect("experimental flag is valid");
assert!(options.experimental_multi_rule_line_fix);
}
/// Debug information requires an explicit runtime opt-in.
#[test]
fn parses_debug_mode_flag() {
let options = Options::try_parse_from(["vsg-bridge-ls", "--debug-mode"])
.expect("debug flag is valid");
assert!(options.debug_mode);
}
/// Hover suppression requires an explicit runtime opt-in.
#[test]
fn parses_disable_hover_flag() {
let options = Options::try_parse_from(["vsg-bridge-ls", "--disable-hover"])
.expect("hover flag is valid");
assert!(options.disable_hover);
}
/// Exact VSG severity mapping requires an explicit runtime opt-in.
#[test]
fn parses_strict_diagnostic_severity_flag() {
let options = Options::try_parse_from(["vsg-bridge-ls", "--strict-diagnostic-severity"])
.expect("severity flag is valid");
assert!(options.strict_diagnostic_severity);
}
/// Config generation records supplied options and refuses to overwrite files.
#[test]
fn writes_new_project_configuration() {
let directory = TestDirectory::new();
let path = directory.path().join("vsg-bridge-ls.toml");
let options = Options::try_parse_from([
"vsg-bridge-ls",
"--write-config",
"--configuration",
"rules one.yaml",
"--allow-browser-action",
"--experimental-rule-fix",
"--disable-hover",
"--strict-diagnostic-severity",
])
.expect("configuration generation arguments are valid");
assert!(options.write_config);
options
.write_configuration(&path)
.expect("write new configuration");
let source = std::fs::read_to_string(&path).expect("read generated configuration");
assert!(source.starts_with("# Generated by vsg-bridge-ls --write-config."));
let generated: FileOptions = toml::from_str(&source).expect("valid generated TOML");
assert_eq!(
generated.vsg_configuration,
Some(vec!["rules one.yaml".to_owned()])
);
assert_eq!(generated.allow_browser_action, Some(true));
assert_eq!(generated.experimental_rule_fix, Some(true));
assert_eq!(generated.experimental_multi_rule_line_fix, Some(false));
assert_eq!(generated.debug_mode, Some(false));
assert_eq!(generated.disable_hover, Some(true));
assert_eq!(generated.strict_diagnostic_severity, Some(true));
let error = options
.write_configuration(&path)
.expect_err("existing configuration must not be overwritten");
assert!(error.to_string().contains("failed to create"));
}
/// The byte-stream transport processes a complete LSP lifecycle.
#[tokio::test]
async fn serves_lsp_over_supplied_streams() {
let (mut request_writer, request_reader) = tokio::io::duplex(4096);
let (response_writer, mut response_reader) = tokio::io::duplex(4096);
let server = tokio::spawn(run(
request_reader,
response_writer,
Options {
configuration: Vec::new(),
allow_browser_action: false,
experimental_rule_fix: false,
experimental_multi_rule_line_fix: false,
debug_mode: false,
disable_hover: false,
strict_diagnostic_severity: false,
write_config: false,
},
Arc::new(UnusedRunner),
));
request_writer
.write_all(
frame(
r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"capabilities":{}}}"#,
)
.as_bytes(),
)
.await
.expect("write initialize request");
let initialize_response = read_frame(&mut response_reader).await;
request_writer
.write_all(frame(r#"{"jsonrpc":"2.0","id":2,"method":"shutdown"}"#).as_bytes())
.await
.expect("write shutdown request");
let shutdown_response = read_frame(&mut response_reader).await;
request_writer
.write_all(frame(r#"{"jsonrpc":"2.0","method":"exit"}"#).as_bytes())
.await
.expect("write exit notification");
request_writer
.shutdown()
.await
.expect("close request stream");
server.await.expect("server task");
assert!(initialize_response.contains(r#""id":1"#));
assert!(initialize_response.contains(r#""textDocumentSync""#));
assert!(shutdown_response.contains(r#""id":2"#));
assert!(shutdown_response.contains(r#""result":null"#));
}
}

View File

@ -1,195 +1,28 @@
//! Hello
//!
#![warn(clippy::missing_docs_in_private_items)]
//! Command-line entry point for the VSG language-server bridge.
use anyhow::Context;
use clap::Parser;
use serde_json::Value;
use std::io::Write;
use std::process::{Command, Stdio};
use tower_lsp::lsp_types::*;
use tower_lsp::{Client, LanguageServer, LspService, Server};
macro_rules! regex {
($re:literal $(,)?) => {{
static RE: once_cell::sync::OnceCell<regex::Regex> = once_cell::sync::OnceCell::new();
RE.get_or_init(|| regex::Regex::new($re).unwrap())
}};
}
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
/// List of configuration files to load for vsg
#[arg(short, long)]
configuration: Vec<String>,
}
#[derive(Debug)]
struct Backend {
client: Client,
config: Args,
vsg_args: Vec<String>,
}
#[tower_lsp::async_trait]
impl LanguageServer for Backend {
async fn initialize(
&self,
_: InitializeParams,
) -> Result<InitializeResult, tower_lsp::jsonrpc::Error> {
Ok(InitializeResult {
capabilities: ServerCapabilities {
text_document_sync: Some(TextDocumentSyncCapability::Kind(
TextDocumentSyncKind::FULL,
)),
..ServerCapabilities::default()
},
..Default::default()
})
}
async fn initialized(&self, _: InitializedParams) {
self.client
.log_message(MessageType::INFO, "initialized!")
.await;
}
async fn shutdown(&self) -> Result<(), tower_lsp::jsonrpc::Error> {
Ok(())
}
async fn execute_command(
&self,
_: ExecuteCommandParams,
) -> Result<Option<Value>, tower_lsp::jsonrpc::Error> {
// self.client
// .log_message(MessageType::INFO, "command executed!")
// .await;
// match self.client.apply_edit(WorkspaceEdit::default()).await {
// Ok(res) if res.applied => self.client.log_message(MessageType::INFO, "applied").await,
// Ok(_) => self.client.log_message(MessageType::INFO, "rejected").await,
// Err(err) => self.client.log_message(MessageType::ERROR, err).await,
// }
Ok(None)
}
async fn did_open(&self, p: DidOpenTextDocumentParams) {
// match find_diagnostics_for_file(p.text_document.uri.clone(), &self.vsg_args).await {
// Ok(diags) => {
// self.client
// .publish_diagnostics(p.text_document.uri, diags, None)
// .await;
// }
// Err(e) => {
// self.client
// .show_message(MessageType::ERROR, e.to_string())
// .await;
// }
// };
}
async fn did_save(&self, p: DidSaveTextDocumentParams) {
self.client
.show_message(MessageType::ERROR, format!("{:?}", self.vsg_args))
.await;
match find_diagnostics_for_text(p.text.unwrap(), &self.vsg_args).await {
Ok(diags) => {
self.client
.publish_diagnostics(p.text_document.uri, diags, None)
.await;
}
Err(e) => {
self.client
.show_message(MessageType::ERROR, e.to_string())
.await;
}
};
}
}
async fn find_diagnostics_for_text(
// uri: Url,
data: String,
config: &Vec<String>,
) -> Result<Vec<Diagnostic>, anyhow::Error> {
let mut vec_diag = Vec::new();
let reg = regex!(
r" (?<rule>[^\s]*_\d*)\s*\| (?<severity>[^\s]*)\s*\|\s*(?<line>[^\s]*) \| (?<solution>.*)"
);
let mut child = Command::new("vsg")
.stdin(Stdio::piped())
.arg("-f")
// .arg(
// uri.to_file_path()
// .map_err(|_| anyhow!("converting uri to file path"))?,
// )
.args(config)
.spawn()
.context("failed to run vsg linter")?;
// .stdout;
let mut stdin = child.stdin.take().context("adding stdin pipe")?;
std::thread::spawn(move || {
stdin
.write_all(data.as_bytes())
.expect("Failed to write to stdin");
});
let output = child
.wait_with_output()
.context("Failed to read stdout")?
.stdout;
let output = String::from_utf8_lossy(&output);
let matches = reg.captures_iter(&output);
for m in matches {
if let (Some(rule), Some(line), Some(solution)) =
(m.name("rule"), m.name("line"), m.name("solution"))
{
let range = match line.as_str().parse() {
Ok(pos) => make_range(pos),
Err(_) => continue,
};
let d = Diagnostic {
range,
severity: Some(DiagnosticSeverity::WARNING), // Everything is a warning
code: Some(NumberOrString::String(rule.as_str().to_owned())), // The important second part
message: solution.as_str().to_owned(),
..Default::default()
};
vec_diag.push(d);
};
}
Ok(vec_diag)
}
fn make_range(pos: u32) -> Range {
Range::new(
Position::new(pos.saturating_sub(1), 0),
Position::new(pos.saturating_sub(1), 1),
)
}
use vsg_bridge_ls::{run_stdio, Options};
/// Parses command-line options and serves LSP messages over standard streams.
#[tokio::main]
async fn main() {
tracing_subscriber::fmt().init();
let config = Args::parse();
let vsg_args = config
.configuration
.iter()
.flat_map(|v| ["-c".to_string(), v.clone()])
.collect();
let (stdin, stdout) = (tokio::io::stdin(), tokio::io::stdout());
let (service, socket) = LspService::new(|client| Backend {
client,
config,
vsg_args,
let options = Options::parse();
if options.write_config {
let path = options
.write_project_configuration()
.unwrap_or_else(|error| {
eprintln!("vsg-bridge-ls: {error:#}");
std::process::exit(2);
});
println!("Wrote {}", path.display());
return;
}
tracing_subscriber::fmt()
.with_writer(std::io::stderr)
.init();
let options = options.resolve().unwrap_or_else(|error| {
eprintln!("vsg-bridge-ls: {error:#}");
std::process::exit(2);
});
Server::new(stdin, stdout, socket).serve(service).await;
run_stdio(options).await;
}

246
src/presentation.rs Normal file
View File

@ -0,0 +1,246 @@
//! User-facing hover content derived from validated VSG diagnostics.
use crate::diagnostics::DiagnosticData;
use serde_json::Value;
use tower_lsp::lsp_types::{Diagnostic, Hover, HoverContents, MarkupContent, MarkupKind};
/// Builds Markdown for every current diagnostic covering an LSP line.
pub(crate) fn hover_for_line(diagnostics: &[Diagnostic], line: u32) -> Option<Hover> {
let sections: Vec<_> = diagnostics
.iter()
.filter(|diagnostic| {
diagnostic.range.start.line <= line && line <= diagnostic.range.end.line
})
.filter_map(render_diagnostic)
.collect();
if sections.is_empty() {
return None;
}
Some(Hover {
contents: HoverContents::Markup(MarkupContent {
kind: MarkupKind::Markdown,
value: sections.join("\n\n---\n\n"),
}),
range: None,
})
}
/// Adds a debug snapshot to a normal hover, or creates a debug-only hover.
pub(crate) fn append_debug_hover(hover: Option<Hover>, report: &str) -> Hover {
let report = report.replace('`', "\\u0060");
let section = format!("## VSG bridge debug information\n\n```json\n{report}\n```");
match hover {
Some(mut hover) => {
if let HoverContents::Markup(markup) = &mut hover.contents {
markup.value.push_str("\n\n---\n\n");
markup.value.push_str(&section);
hover
} else {
debug_hover(section)
}
}
None => debug_hover(section),
}
}
/// Wraps rendered debug Markdown in an LSP hover result.
fn debug_hover(value: String) -> Hover {
Hover {
contents: HoverContents::Markup(MarkupContent {
kind: MarkupKind::Markdown,
value,
}),
range: None,
}
}
/// Renders one diagnostic while ignoring malformed opaque client data.
fn render_diagnostic(diagnostic: &Diagnostic) -> Option<String> {
let data: DiagnosticData = serde_json::from_value(diagnostic.data.clone()?).ok()?;
let metadata = data.metadata;
let mut lines = vec![
format!(
"**VSG `{}`** — {}",
escape_code(&data.rule),
diagnostic.message
),
format!(
"- Severity: {} (`{}`)",
metadata.severity.name,
escape_code(&metadata.severity.kind)
),
format!("- Phase: `{}.{}`", metadata.phase, metadata.subphase),
format!("- Fixable: {}", if metadata.fixable { "yes" } else { "no" }),
];
if let Some(url) = metadata.documentation.rule {
lines.push(format!("- Rule documentation: <{url}>"));
}
if let Some(url) = metadata.documentation.configuration {
lines.push(format!("- Configuration documentation: <{url}>"));
}
let configuration: Vec<_> = metadata
.configuration
.iter()
.filter(|(key, value)| is_nontrivial_configuration(key, value))
.map(|(key, value)| {
format!(
"`{}` = `{}`",
escape_code(key),
escape_code(&compact(value))
)
})
.collect();
if !configuration.is_empty() {
lines.push(format!("- Configuration: {}", configuration.join(", ")));
}
Some(lines.join("\n"))
}
/// Omits generic metadata that is already presented explicitly.
fn is_nontrivial_configuration(key: &str, value: &Value) -> bool {
match key {
"disable" | "fixable" | "phase" | "severity" => false,
"user_error_message" => !value.as_str().is_some_and(str::is_empty),
_ => true,
}
}
/// Produces compact JSON suitable for an inline code span.
fn compact(value: &Value) -> String {
match value {
Value::String(value) => value.clone(),
_ => value.to_string(),
}
}
/// Prevents values from ending an inline code span.
fn escape_code(value: &str) -> String {
value.replace('`', "\\`")
}
#[cfg(test)]
mod tests {
//! Hover rendering tests use realistic diagnostic data.
use super::{append_debug_hover, hover_for_line};
use serde_json::json;
use tower_lsp::lsp_types::{Diagnostic, Hover, HoverContents, MarkedString, Position, Range};
/// Builds one LSP diagnostic containing validated VSG metadata.
fn diagnostic(rule_url: Option<&str>, configuration_url: Option<&str>) -> Diagnostic {
Diagnostic {
range: Range::new(Position::new(2, 0), Position::new(2, 8)),
message: "Change name to upper case".to_owned(),
data: Some(json!({
"schema_version": 1,
"tool_version": "3.35.0",
"rule": "entity_008",
"line": 3,
"metadata": {
"severity": {"name": "Style", "type": "warning"},
"fixable": true,
"phase": 6,
"subphase": 1,
"configuration": {
"case": "upper",
"indent": 4,
"disable": false,
"phase": 6,
"severity": "Style",
"user_error_message": ""
},
"documentation": {
"rule": rule_url,
"configuration": configuration_url
}
}
})),
..Diagnostic::default()
}
}
/// Hover presents useful metadata without repeating generic configuration.
#[test]
fn renders_concise_rule_metadata() {
let hover = hover_for_line(
&[diagnostic(
Some("https://example.com/rule"),
Some("https://example.com/configuration"),
)],
2,
)
.expect("hover on diagnostic line");
let HoverContents::Markup(markup) = hover.contents else {
panic!("expected Markdown hover")
};
assert!(markup.value.contains("VSG `entity_008`"));
assert!(markup.value.contains("Severity: Style (`warning`)"));
assert!(markup.value.contains("Phase: `6.1`"));
assert!(markup.value.contains("`case` = `upper`"));
assert!(markup.value.contains("`indent` = `4`"));
assert!(!markup.value.contains("`disable`"));
assert!(markup
.value
.contains("Rule documentation: <https://example.com/rule>"));
assert!(markup
.value
.contains("Configuration documentation: <https://example.com/configuration>"));
}
/// Local rules without stable links still provide useful hover detail.
#[test]
fn renders_local_rule_without_links() {
let hover =
hover_for_line(&[diagnostic(None, None)], 2).expect("local rule hover without links");
let HoverContents::Markup(markup) = hover.contents else {
panic!("expected Markdown hover")
};
assert!(!markup.value.contains("documentation]("));
assert!(markup.value.contains("Fixable: yes"));
}
/// Positions without a current diagnostic have no hover.
#[test]
fn ignores_other_lines_and_malformed_data() {
assert!(hover_for_line(&[diagnostic(None, None)], 1).is_none());
let malformed = Diagnostic {
range: Range::new(Position::new(1, 0), Position::new(1, 1)),
data: Some(json!({"unexpected": true})),
..Diagnostic::default()
};
assert!(hover_for_line(&[malformed], 1).is_none());
}
/// Debug Markdown augments rule help and remains available away from findings.
#[test]
fn appends_debug_information_to_hover() {
let hover = hover_for_line(&[diagnostic(None, None)], 2);
let hover = append_debug_hover(hover, r#"{"version":"0.3.2-rc.3","note":"```"}"#);
let HoverContents::Markup(markup) = hover.contents else {
panic!("expected Markdown hover")
};
assert!(markup.value.contains("VSG `entity_008`"));
assert!(markup.value.contains("VSG bridge debug information"));
assert!(markup.value.contains(r#""note":"\u0060\u0060\u0060""#));
let debug_only = append_debug_hover(None, "{}");
let HoverContents::Markup(markup) = debug_only.contents else {
panic!("expected Markdown hover")
};
assert!(markup.value.contains("```json\n{}\n```"));
let legacy = Hover {
contents: HoverContents::Scalar(MarkedString::String("legacy".to_owned())),
range: None,
};
let replaced = append_debug_hover(Some(legacy), "{}");
assert!(matches!(replaced.contents, HoverContents::Markup(_)));
}
}

432
src/runner.rs Normal file
View File

@ -0,0 +1,432 @@
//! Asynchronous execution of the VSG subprocess.
use anyhow::{bail, Context, Result};
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::io::AsyncWriteExt;
use tokio::process::Command;
use tokio::time::timeout;
/// Default maximum duration of one VSG invocation.
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
/// Maximum number of characters copied from VSG stderr into an LSP message.
const MAX_ERROR_DETAIL_CHARS: usize = 800;
/// Produces a concise, single-line error suitable for an editor notification.
fn summarize_stderr(stderr: &[u8]) -> String {
let stderr = String::from_utf8_lossy(stderr);
let trimmed = stderr.trim();
if trimmed.is_empty() {
return "no error output".to_owned();
}
let detail = trimmed
.lines()
.rev()
.find(|line| line.contains(": error:"))
.unwrap_or(trimmed);
let normalized = detail.split_whitespace().collect::<Vec<_>>().join(" ");
let mut characters = normalized.chars();
let summary: String = characters.by_ref().take(MAX_ERROR_DETAIL_CHARS).collect();
if characters.next().is_some() {
format!("{summary}…")
} else {
summary
}
}
/// Abstraction over VSG execution used by the server and protocol tests.
#[tower_lsp::async_trait]
pub trait VsgRunner: Send + Sync + std::fmt::Debug {
/// Returns a non-sensitive description for opt-in debug reports.
fn debug_description(&self) -> String {
"injected VSG runner".to_owned()
}
/// Lints one complete in-memory VHDL document and returns VSG's stdout.
async fn lint(&self, source: &str, arguments: &[String]) -> Result<String>;
/// Applies selected rule-and-line corrections to one complete document.
async fn fix_rules(
&self,
_source: &str,
_arguments: &[String],
_selectors: &[(String, u32)],
) -> Result<String> {
bail!("the configured VSG runner does not support rule-scoped fixes")
}
/// Applies VSG's normal phase-seven whole-document correction.
async fn fix_all(&self, _source: &str, _arguments: &[String]) -> Result<String> {
bail!("the configured VSG runner does not support whole-document fixes")
}
}
/// Runs a local VSG executable with bounded asynchronous I/O.
#[derive(Clone, Debug)]
pub struct ProcessVsgRunner {
/// Executable path or name passed directly to the operating system.
executable: PathBuf,
/// Maximum duration allowed for a single child process.
timeout: Duration,
}
impl ProcessVsgRunner {
/// Creates a runner for a particular executable and timeout.
#[must_use]
pub fn new(executable: impl Into<PathBuf>, timeout: Duration) -> Self {
Self {
executable: executable.into(),
timeout,
}
}
/// Returns the configured VSG executable.
#[must_use]
pub fn executable(&self) -> &Path {
&self.executable
}
/// Returns the configured invocation timeout.
#[must_use]
pub fn timeout(&self) -> Duration {
self.timeout
}
/// Executes one argument vector with bounded asynchronous standard streams.
async fn execute(
&self,
source: &str,
arguments: &[String],
accept_failure_output: bool,
) -> Result<String> {
let mut child = Command::new(&self.executable)
.args(arguments)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true)
.spawn()
.with_context(|| format!("failed to start {}", self.executable.display()))?;
let mut stdin = child
.stdin
.take()
.context("failed to open the VSG standard input pipe")?;
let write_result = stdin.write_all(source.as_bytes()).await;
drop(stdin);
let output = timeout(self.timeout, child.wait_with_output())
.await
.with_context(|| format!("VSG exceeded its {} ms timeout", self.timeout.as_millis()))?
.context("failed while waiting for VSG")?;
let stdout = String::from_utf8(output.stdout).context("VSG produced non-UTF-8 output")?;
if !output.status.success() {
if accept_failure_output && !stdout.trim().is_empty() {
return Ok(stdout);
}
bail!(
"VSG exited with status {}: {}",
output.status,
summarize_stderr(&output.stderr)
);
}
write_result.context("failed to write the VHDL document to VSG")?;
Ok(stdout)
}
}
impl Default for ProcessVsgRunner {
fn default() -> Self {
Self::new("vsg", DEFAULT_TIMEOUT)
}
}
#[tower_lsp::async_trait]
impl VsgRunner for ProcessVsgRunner {
fn debug_description(&self) -> String {
self.executable.display().to_string()
}
async fn lint(&self, source: &str, arguments: &[String]) -> Result<String> {
let mut invocation = vec![
"--stdin".to_owned(),
"--all_phases".to_owned(),
"--diagnostics_json".to_owned(),
"--no-failure".to_owned(),
];
invocation.extend_from_slice(arguments);
self.execute(source, &invocation, true).await
}
async fn fix_rules(
&self,
source: &str,
arguments: &[String],
selectors: &[(String, u32)],
) -> Result<String> {
let mut invocation = vec![
"--stdin".to_owned(),
"--fix".to_owned(),
"--stdout".to_owned(),
"--no-failure".to_owned(),
];
for (rule, line) in selectors {
invocation.push("--fix_rule".to_owned());
invocation.push(format!("{rule}:{line}"));
}
invocation.extend_from_slice(arguments);
self.execute(source, &invocation, false).await
}
async fn fix_all(&self, source: &str, arguments: &[String]) -> Result<String> {
let mut invocation = vec![
"--stdin".to_owned(),
"--stdout".to_owned(),
"--fix".to_owned(),
"-fp".to_owned(),
"7".to_owned(),
"--no-failure".to_owned(),
];
invocation.extend_from_slice(arguments);
self.execute(source, &invocation, false).await
}
}
#[cfg(all(test, unix))]
mod tests {
//! Unix subprocess boundary tests using versioned fake executables.
use super::{summarize_stderr, ProcessVsgRunner, VsgRunner, MAX_ERROR_DETAIL_CHARS};
use anyhow::Result;
use std::path::PathBuf;
use std::time::Duration;
/// Minimal runner used to exercise the trait's unsupported-operation errors.
#[derive(Debug)]
struct LintOnlyRunner;
#[tower_lsp::async_trait]
impl VsgRunner for LintOnlyRunner {
async fn lint(&self, _: &str, _: &[String]) -> Result<String> {
Ok(String::new())
}
}
/// Returns a runner backed by a read-only fixture from the repository.
fn fake_vsg(name: &str, timeout: Duration) -> ProcessVsgRunner {
let executable = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fixtures")
.join(name);
assert!(
executable.is_file(),
"missing fixture: {}",
executable.display()
);
ProcessVsgRunner::new(executable, timeout)
}
/// The default runner targets `vsg` and uses a bounded timeout.
#[test]
fn default_configuration_is_explicit() {
let runner = ProcessVsgRunner::default();
assert_eq!(runner.executable(), std::path::Path::new("vsg"));
assert_eq!(runner.timeout(), Duration::from_secs(30));
assert_eq!(runner.debug_description(), "vsg");
}
/// Injected lint-only runners reject correction operations explicitly.
#[tokio::test]
async fn default_correction_methods_report_unsupported_operations() {
let runner = LintOnlyRunner;
assert!(runner.fix_rules("text", &[], &[]).await.is_err());
assert!(runner.fix_all("text", &[]).await.is_err());
}
/// Argparse usage is reduced to its actionable final error line.
#[test]
fn summarizes_argument_errors_without_usage_text() {
let stderr = b"usage: VSG [-h] [--stdin]\nVSG: error: unknown option: --bad\n";
assert_eq!(
summarize_stderr(stderr),
"VSG: error: unknown option: --bad"
);
}
/// Multiline parser failures are bounded and safe to display in an editor.
#[test]
fn bounds_and_flattens_configuration_errors() {
let stderr = format!("ERROR: Invalid configuration file:\n{}", "bad ".repeat(300));
let summary = summarize_stderr(stderr.as_bytes());
assert!(!summary.contains('\n'));
assert!(summary.chars().count() <= MAX_ERROR_DETAIL_CHARS + 1);
assert!(summary.ends_with('…'));
}
/// Source text reaches stdin and arguments are passed without a shell.
#[tokio::test]
async fn sends_source_and_arguments_to_vsg() {
let runner = fake_vsg("success-vsg.sh", Duration::from_secs(2));
let output = runner
.lint(
"entity demo is",
&["-c".to_owned(), "config with spaces.yaml".to_owned()],
)
.await
.expect("fake VSG succeeds");
assert!(output.contains("vsg.diagnostics"));
}
/// Scoped fixes use repeated selectors without a temporary control file.
#[tokio::test]
async fn sends_rule_scoped_fix_arguments() {
let runner = fake_vsg("fix-rule-vsg.sh", Duration::from_secs(2));
let output = runner
.fix_rules(
"entity bad is",
&["-c".to_owned(), "config.yaml".to_owned()],
&[("entity_008".to_owned(), 1)],
)
.await
.expect("fake scoped fix succeeds");
assert_eq!(output, "entity BAD is\n");
}
/// Fix-all remains the existing phase-seven formatter invocation.
#[tokio::test]
async fn sends_whole_document_fix_arguments() {
let runner = fake_vsg("fix-all-vsg.sh", Duration::from_secs(2));
let output = runner
.fix_all(
"entity bad is",
&["-c".to_owned(), "config.yaml".to_owned()],
)
.await
.expect("fake fix-all succeeds");
assert_eq!(output, "entity BAD is\n");
}
/// A nonzero exit includes both status and stderr in the error.
#[tokio::test]
async fn reports_unsuccessful_exit() {
let runner = fake_vsg("failure-vsg.sh", Duration::from_secs(2));
let error = runner
.lint("text", &[])
.await
.expect_err("nonzero VSG status must fail");
let message = error.to_string();
assert!(message.contains('7'), "{message}");
assert!(message.contains("broken config"), "{message}");
}
/// Lint preserves a structured incomplete document even with failure status.
#[tokio::test]
async fn preserves_incomplete_diagnostics_from_unsuccessful_exit() {
let runner = fake_vsg("incomplete-vsg.sh", Duration::from_secs(2));
let output = runner
.lint("invalid source", &[])
.await
.expect("structured diagnostic failure reaches the parser");
assert!(output.contains("\"complete\":false"));
assert!(output.contains("could not parse source"));
}
/// Invalid stdout bytes are rejected instead of being silently replaced.
#[tokio::test]
async fn rejects_non_utf8_output() {
let runner = fake_vsg("invalid-utf8-vsg.sh", Duration::from_secs(2));
let error = runner
.lint("text", &[])
.await
.expect_err("invalid UTF-8 must fail");
assert!(error.to_string().contains("non-UTF-8"));
}
/// A missing executable yields an actionable start error.
#[tokio::test]
async fn reports_missing_executable() {
let runner = ProcessVsgRunner::new(
"/definitely/not/a/vsg/executable",
Duration::from_millis(20),
);
let error = runner
.lint("text", &[])
.await
.expect_err("missing executable must fail");
assert!(error.to_string().contains("failed to start"));
}
/// A stuck process is bounded by the configured timeout.
#[tokio::test]
async fn times_out_stuck_processes() {
let runner = fake_vsg("timeout-vsg.sh", Duration::from_millis(20));
let error = runner
.lint("text", &[])
.await
.expect_err("slow VSG must time out");
assert!(error.to_string().contains("exceeded"));
}
/// Correction output uses the same strict UTF-8 boundary as diagnostics.
#[tokio::test]
async fn rejects_non_utf8_fix_output() {
let runner = fake_vsg("invalid-utf8-vsg.sh", Duration::from_secs(2));
let error = runner
.fix_all("text", &[])
.await
.expect_err("invalid UTF-8 correction must fail");
assert!(error.to_string().contains("non-UTF-8"));
}
/// Correction subprocess failures preserve actionable stderr.
#[tokio::test]
async fn reports_unsuccessful_fix() {
let runner = fake_vsg("failure-vsg.sh", Duration::from_secs(2));
let error = runner
.fix_rules("text", &[], &[("rule_001".to_owned(), 1)])
.await
.expect_err("nonzero correction status must fail");
assert!(error.to_string().contains("broken config"));
}
/// Correction subprocesses share the normal timeout and reap policy.
#[tokio::test]
async fn times_out_stuck_fix() {
let runner = fake_vsg("timeout-vsg.sh", Duration::from_millis(20));
let error = runner
.fix_all("text", &[])
.await
.expect_err("slow correction must time out");
assert!(error.to_string().contains("exceeded"));
}
}

2888
src/server.rs Normal file

File diff suppressed because it is too large Load Diff

9
tarpaulin.toml Normal file
View File

@ -0,0 +1,9 @@
[coverage]
all-features = true
engine = "Llvm"
fail-under = 90.0
locked = true
run-types = ["Tests"]
[report]
out = ["Stdout", "Json"]

5
tests/fixtures/failure-vsg.sh vendored Executable file
View File

@ -0,0 +1,5 @@
#!/bin/sh
set -eu
echo 'broken config' >&2
exit 7

14
tests/fixtures/fix-all-vsg.sh vendored Executable file
View File

@ -0,0 +1,14 @@
#!/bin/sh
set -eu
test "$1" = "--stdin"
test "$2" = "--stdout"
test "$3" = "--fix"
test "$4" = "-fp"
test "$5" = "7"
test "$6" = "--no-failure"
test "$7" = "-c"
test "$8" = "config.yaml"
input=$(cat)
test "$input" = "entity bad is"
printf '%s\n' 'entity BAD is'

14
tests/fixtures/fix-rule-vsg.sh vendored Executable file
View File

@ -0,0 +1,14 @@
#!/bin/sh
set -eu
test "$1" = "--stdin"
test "$2" = "--fix"
test "$3" = "--stdout"
test "$4" = "--no-failure"
test "$5" = "--fix_rule"
test "$6" = "entity_008:1"
test "$7" = "-c"
test "$8" = "config.yaml"
input=$(cat)
test "$input" = "entity bad is"
printf '%s\n' 'entity BAD is'

6
tests/fixtures/incomplete-vsg.sh vendored Executable file
View File

@ -0,0 +1,6 @@
#!/bin/sh
set -eu
cat >/dev/null
printf '%s\n' '{"schema":"vsg.diagnostics","schema_version":1,"complete":false,"tool":{"name":"vsg","version":"3.35.0"},"source":{"name":"stdin"},"rules":{},"diagnostics":[],"errors":[{"kind":"analysis","message":"could not parse source"}]}'
exit 1

5
tests/fixtures/invalid-utf8-vsg.sh vendored Executable file
View File

@ -0,0 +1,5 @@
#!/bin/sh
set -eu
cat >/dev/null
printf '\377'

12
tests/fixtures/success-vsg.sh vendored Executable file
View File

@ -0,0 +1,12 @@
#!/bin/sh
set -eu
test "$1" = "--stdin"
test "$2" = "--all_phases"
test "$3" = "--diagnostics_json"
test "$4" = "--no-failure"
test "$5" = "-c"
test "$6" = "config with spaces.yaml"
input=$(cat)
test "$input" = "entity demo is"
printf '%s\n' '{"schema":"vsg.diagnostics","schema_version":1,"tool":{"name":"vsg","version":"3.35.0"},"source":{"name":"stdin"},"rules":{},"diagnostics":[]}'

4
tests/fixtures/timeout-vsg.sh vendored Executable file
View File

@ -0,0 +1,4 @@
#!/bin/sh
set -eu
sleep 2

126
tests/packaged_vsg.rs Normal file
View File

@ -0,0 +1,126 @@
//! Opt-in integration check against an installed companion VSG package.
use serde_json::Value;
use std::path::PathBuf;
use std::time::Duration;
use vsg_bridge_ls::{ProcessVsgRunner, VsgRunner};
/// Exercises diagnostics, one scoped fix, and fix-all against a real wheel.
#[tokio::test]
#[ignore = "set VSG_EXECUTABLE to an installed companion VSG executable"]
async fn packaged_vsg_supports_bridge_protocol() {
let executable = std::env::var_os("VSG_EXECUTABLE")
.map(PathBuf::from)
.expect("VSG_EXECUTABLE must identify the packaged VSG executable");
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let source = std::fs::read_to_string(root.join("showcase/one-line-entity.vhd"))
.expect("read showcase VHDL");
let configuration = root.join("showcase/vsg.yaml");
let arguments = vec![
"-c".to_owned(),
configuration.to_string_lossy().into_owned(),
];
let runner = ProcessVsgRunner::new(executable, Duration::from_secs(30));
let diagnostic_output = runner
.lint(&source, &arguments)
.await
.expect("packaged VSG diagnostic request");
let document: Value =
serde_json::from_str(&diagnostic_output).expect("versioned diagnostic JSON");
assert_eq!(document["schema"], "vsg.diagnostics");
assert_eq!(document["schema_version"], 1);
assert_eq!(document["complete"], true);
assert_eq!(document["errors"], serde_json::json!([]));
assert!(document["diagnostics"]
.as_array()
.is_some_and(|diagnostics| diagnostics.len() >= 4));
let incomplete_output = runner
.lint("entity incomplete is\n", &arguments)
.await
.expect("packaged VSG preserves its structured failure response");
let incomplete: Value =
serde_json::from_str(&incomplete_output).expect("valid incomplete diagnostic JSON");
assert_eq!(incomplete["schema_version"], 1);
assert_eq!(incomplete["complete"], false);
assert_eq!(incomplete["diagnostics"], serde_json::json!([]));
assert!(incomplete["errors"]
.as_array()
.is_some_and(|errors| !errors.is_empty()));
assert_eq!(incomplete["errors"][0]["kind"], "syntax");
assert_eq!(incomplete["errors"][0]["location"]["line"], 1);
assert_eq!(incomplete["errors"][0]["location"]["column"], 1);
let invalid_source = "entity incomplete is\n";
let unchanged = runner
.fix_all(invalid_source, &arguments)
.await
.expect("packaged VSG returns a safe no-op for invalid source");
assert_eq!(unchanged, invalid_source);
let scoped = runner
.fix_rules(&source, &arguments, &[("entity_012".to_owned(), 1)])
.await
.expect("packaged VSG scoped fix");
assert_ne!(scoped, source);
assert!(scoped.contains("entity TINY"));
let fixed = runner
.fix_all(&source, &arguments)
.await
.expect("packaged VSG fix-all");
assert_ne!(fixed, source);
assert!(fixed.lines().count() > source.lines().count());
let diagnosed_fixed: Value = serde_json::from_str(
&runner
.lint(&fixed, &arguments)
.await
.expect("diagnose fix-all result"),
)
.expect("valid diagnostics after fix-all");
assert_eq!(diagnosed_fixed["diagnostics"], serde_json::json!([]));
let multi_selectors = vec![
("entity_008".to_owned(), 1),
("entity_012".to_owned(), 1),
("entity_021".to_owned(), 1),
("entity_026".to_owned(), 1),
];
let multi = runner
.fix_rules(&source, &arguments, &multi_selectors)
.await
.expect("packaged VSG multi-rule line fix");
let diagnosed_multi: Value = serde_json::from_str(
&runner
.lint(&multi, &arguments)
.await
.expect("diagnose multi-rule result"),
)
.expect("valid diagnostics after multi-rule fix");
assert_eq!(diagnosed_multi["schema_version"], 1);
let after = diagnosed_multi["diagnostics"]
.as_array()
.expect("diagnostic array after multi-rule fix");
let selected_remaining = after
.iter()
.filter(|diagnostic| {
diagnostic["rule"]
.as_str()
.is_some_and(|rule| multi_selectors.iter().any(|(selected, _)| selected == rule))
})
.count();
assert!(selected_remaining < multi_selectors.len());
assert!(
after
.iter()
.any(|diagnostic| diagnostic["rule"] == "entity_009"),
"the known phase-one newline currently exposes an indentation finding"
);
let repeated = runner
.fix_rules(&multi, &arguments, &multi_selectors)
.await
.expect("repeat packaged VSG multi-rule line fix");
assert_eq!(repeated, multi, "second identical request must be a no-op");
}

View File

@ -5,9 +5,9 @@ architecture sim of test_tb is
signal fork : boolean;
signal join_1, join_2, join_3 : boolean;
begin
CONTROLLER_PROC : process
begin
report "Forking";