Expand description
Perl Language Server Protocol Runtime
This crate provides the production-ready LSP server runtime for Perl, implementing the Language Server Protocol specification for seamless integration with editors like VSCode, Neovim, Emacs, and any LSP-compatible client.
The runtime handles all protocol communication, message framing, state management, and
feature dispatching, while delegating parsing and analysis to the perl_parser engine.
§Quick Start
§Running the Server
The simplest way to start the server is via the binary:
# Install from source
cargo install --path crates/perllsp
# Run in stdio mode (default)
perllsp --stdio
# Check health status
perllsp --health
# Show version information
perllsp --version§Programmatic Usage
Use the runtime as a library to embed LSP support:
perl_lsp::run_stdio()?;§Custom Server Configuration
For advanced use cases, create a server instance directly:
use perl_lsp::LspServer;
let mut server = LspServer::new();
server.run()?;§Architecture
The runtime is organized into distinct layers for maintainability and extensibility:
§Protocol Layer
protocol: JSON-RPC message types and LSP protocol definitionstransport: Message framing and transport (stdio, TCP, WebSocket)dispatch: Request routing and method dispatch logic
§State Management
state: Document and workspace state managementtextdoc: Text document synchronization and version trackingruntime: Server lifecycle and initialization management
§Feature Providers
The features module contains all LSP capability implementations:
- Completion: Context-aware code completion with type inference
- Hover: Symbol information and documentation on hover
- Definition: Go-to-definition with cross-file support
- References: Find all references across workspace
- Rename: Symbol renaming with conflict detection
- Diagnostics: Real-time syntax and semantic validation
- Formatting: Code formatting via perltidy integration
- Semantic Tokens: Fine-grained syntax highlighting
- Code Actions: Quick fixes and refactoring suggestions
- Code Lens: Inline actionable metadata
- Inlay Hints: Parameter names and type information
- Call Hierarchy: Function call navigation
- Type Hierarchy: Class inheritance navigation
- Document Links: File and URL navigation
- Folding: Code folding for blocks and regions
- Selection Range: Smart text selection expansion
- Signature Help: Function signature assistance
§Utilities
convert: Conversions betweenperl_parsertypes andlsp_typesutil: URI handling, UTF-16 conversion, and position mappingfallback: Text-based fallback when parsing failscancellation: Request cancellation infrastructurediagnostics_catalog: Stable diagnostic codes
§Request Handling
§Protocol Support
The server implements LSP 3.17 specification features:
§Lifecycle Methods
initialize- Server initialization and capability negotiationinitialized- Post-initialization notificationshutdown- Graceful server shutdownexit- Server process termination
§Document Synchronization
textDocument/didOpen- Document opened in editortextDocument/didChange- Document content changedtextDocument/didSave- Document saved to disktextDocument/didClose- Document closed in editor
§Language Features
See features module documentation for complete feature list and capabilities.
§Communication Modes
§Stdio Mode (Default)
Standard input/output transport for editor integration:
perllsp --stdioEditors configure this mode in their LSP client settings:
§VSCode Configuration
{
"perl.lsp.command": "perllsp",
"perl.lsp.args": ["--stdio"]
}§Neovim Configuration
require'lspconfig'.perl.setup{
cmd = { "perllsp", "--stdio" }
}§Socket Mode
TCP socket transport for remote or debugging scenarios:
perllsp --socket --port 9257Connect via TCP socket from any LSP client supporting network transport.
§Features Module
All LSP capabilities are implemented in the features module, organized by category:
features/
├── completion.rs # Code completion
├── diagnostics.rs # Real-time validation
├── formatting.rs # Code formatting
├── hover.rs # Hover information
├── references.rs # Find references
├── rename.rs # Symbol renaming
├── semantic_tokens.rs # Syntax highlighting
├── code_actions.rs # Quick fixes
├── code_lens_provider.rs # Code lens
├── inlay_hints.rs # Inline hints
└── ...§State Management
The server maintains state across requests:
- Document State: Parsed ASTs, symbol tables, and version tracking
- Workspace Index: Cross-file symbol resolution and references
- Configuration: Client-provided settings and capabilities
- Diagnostics: Cached validation results for incremental updates
§Error Handling
The runtime implements comprehensive error recovery:
- Parse Errors: Graceful degradation to text-based features
- Protocol Errors: JSON-RPC error responses with diagnostic codes
- Cancellation: Request cancellation for long-running operations
- Fallback: Text-based completion/hover when parsing fails
§Performance Optimizations
- Incremental Parsing: Reuse unchanged AST nodes on edits
- Lazy Indexing: Index files on-demand rather than at startup
- Caching: Cache parse results and symbol tables
- Cancellation: Cancel stale requests when new ones arrive
- Streaming: Stream large responses to avoid blocking
§Integration with perl-parser
The runtime delegates all parsing and analysis to perl_parser:
use perl_parser::Parser;
use perl_lsp::convert::to_lsp_diagnostic;
let code = "my $x = 1;";
let mut parser = Parser::new(code);
let ast = parser.parse()?;
// Convert parser errors to LSP diagnostics
let diagnostics: Vec<_> = parser.errors()
.iter()
.map(|e| to_lsp_diagnostic(e, &ast))
.collect();§Testing
The runtime includes comprehensive test coverage:
# Run all LSP runtime tests
cargo test -p perl-lsp-rs
# Run with adaptive threading for resource-constrained environments
RUST_TEST_THREADS=2 cargo test -p perl-lsp-rs
# Test specific feature
cargo test -p perl-lsp-rs completion§Logging and Diagnostics
Enable logging for debugging:
perllsp --stdio --logLogs are written to stderr, separate from LSP protocol communication on stdout/stdin.
§Client Capabilities
The server adapts to client capabilities negotiated during initialization:
- Dynamic Registration: Supports dynamic capability registration
- Workspace Folders: Multi-root workspace support
- Configuration: Client-side configuration changes
- Pull Diagnostics: Diagnostic pull model (LSP 3.17+)
§Security Considerations
- Sandboxed Execution: No arbitrary code execution
- Path Validation: URI validation and path sanitization
- Resource Limits: Memory and time budgets for operations
- Input Validation: Strict protocol message validation
§Migration from perl-parser
This crate was extracted from perl_parser to separate LSP runtime concerns
from parsing engine logic. The migration maintains API compatibility while
improving modularity.
Legacy code can continue using perl_parser::lsp_server::LspServer with
deprecation warnings pointing to this crate.
§Related Crates
perl_parser: Parsing engine and analysis infrastructureperl_lexer: Context-aware Perl tokenizerperl_corpus: Comprehensive test corpusperl_dap: Debug Adapter Protocol implementation
§Documentation
- LSP Guide: See
docs/reference/LSP_IMPLEMENTATION_GUIDE.mdin the repository - Capability Policy: See
docs/reference/LSP_CAPABILITY_POLICY.md - Commands Reference: See
docs/reference/COMMANDS_REFERENCE.md
§Usage Example
Complete example of running the LSP server:
use perl_lsp::LspServer;
let mut server = LspServer::new();
match server.run() {
Ok(()) => println!("Server exited cleanly"),
Err(e) => eprintln!("Server error: {}", e),
}Re-exports§
Modules§
- cancellation
- Re-exported cancellation microcrate API.
- cli
- Shared CLI entrypoint for the perl-lsp binaries.
- convert
- Type conversions between parser engine types and LSP protocol types.
- diagnostics_
catalog - Backward-compatible re-export of the diagnostic catalog microcrate.
- dispatch
- Request dispatch placeholder
- execute_
command - Execute command support for running tests and debugging.
- fallback
- Fallback implementations
- features
- LSP feature providers and legacy compatibility modules.
- handlers
- LSP method handlers
- protocol
- JSON-RPC protocol types, error handling, and capabilities.
- runtime
- Full JSON-RPC LSP Server implementation
- security
- Security module for production hardening
- server
- LSP Server core
- state
- Server and document state management
- textdoc
- Rope-based text document handling for LSP with UTF-16 aware position mapping
- transport
- LSP transport layer
- util
- Text processing utilities for LSP
Structs§
- Bridge
Adapter - DAP bridge adapter re-export Bridge adapter that proxies DAP messages to Perl::LanguageServer
- Json
RpcError - JSON-RPC 2.0 error object
- Json
RpcRequest - JSON-RPC 2.0 request message
- Json
RpcResponse - JSON-RPC 2.0 response message
Functions§
- run_
stdio - Run the LSP server in stdio mode.