Skip to main content

Crate perl_lsp

Crate perl_lsp 

Source
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 definitions
  • transport: Message framing and transport (stdio, TCP, WebSocket)
  • dispatch: Request routing and method dispatch logic

§State Management

  • state: Document and workspace state management
  • textdoc: Text document synchronization and version tracking
  • runtime: 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

§Request Handling

  • handlers: Request and notification handlers
  • server: Public server API and message processing loop

§Protocol Support

The server implements LSP 3.17 specification features:

§Lifecycle Methods

  • initialize - Server initialization and capability negotiation
  • initialized - Post-initialization notification
  • shutdown - Graceful server shutdown
  • exit - Server process termination

§Document Synchronization

  • textDocument/didOpen - Document opened in editor
  • textDocument/didChange - Document content changed
  • textDocument/didSave - Document saved to disk
  • textDocument/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 --stdio

Editors 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 9257

Connect 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 --log

Logs 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.

  • perl_parser: Parsing engine and analysis infrastructure
  • perl_lexer: Context-aware Perl tokenizer
  • perl_corpus: Comprehensive test corpus
  • perl_dap: Debug Adapter Protocol implementation

§Documentation

  • LSP Guide: See docs/reference/LSP_IMPLEMENTATION_GUIDE.md in 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§

pub use cli::run_cli;
pub use server::LspServer;

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§

BridgeAdapter
DAP bridge adapter re-export Bridge adapter that proxies DAP messages to Perl::LanguageServer
JsonRpcError
JSON-RPC 2.0 error object
JsonRpcRequest
JSON-RPC 2.0 request message
JsonRpcResponse
JSON-RPC 2.0 response message

Functions§

run_stdio
Run the LSP server in stdio mode.