pub mod convert;
use std::collections::HashMap;
use std::error::Error;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use lsp_server::{
Connection, ErrorCode, ExtractError, Message, Notification as LspNotification,
Request as LspRequest, RequestId, Response,
};
use lsp_types::notification::{
DidChangeTextDocument, DidChangeWatchedFiles, DidCloseTextDocument, DidOpenTextDocument,
DidSaveTextDocument, Exit, Notification as _, PublishDiagnostics, ShowMessage,
};
use lsp_types::request::{RegisterCapability, Request as _, Shutdown};
use lsp_types::{
ClientCapabilities, Diagnostic, DidChangeTextDocumentParams, DidChangeWatchedFilesParams,
DidChangeWatchedFilesRegistrationOptions, DidCloseTextDocumentParams,
DidOpenTextDocumentParams, DidSaveTextDocumentParams, FileSystemWatcher, GlobPattern,
InitializeParams, InitializeResult, MessageType, PublishDiagnosticsParams, Registration,
RegistrationParams, SaveOptions, ServerCapabilities, ServerInfo, ShowMessageParams,
TextDocumentSyncCapability, TextDocumentSyncKind, TextDocumentSyncOptions,
TextDocumentSyncSaveOptions, Url,
};
use crate::output::RenderedDiagnostic;
use crate::watch::{ChangeKind, WatchSession, WatchSessionOptions};
use convert::{path_to_uri, to_lsp_diagnostic, uri_to_canonical_path};
#[derive(Debug, Clone, Copy)]
pub struct LspOptions {
pub debounce: Duration,
}
impl Default for LspOptions {
fn default() -> Self {
LspOptions {
debounce: Duration::from_millis(200),
}
}
}
pub fn run_stdio(options: LspOptions) -> Result<(), Box<dyn Error + Send + Sync>> {
let (connection, io_threads) = Connection::stdio();
run_with_connection(connection, options)?;
io_threads.join()?;
Ok(())
}
pub fn run_with_connection(
connection: Connection,
options: LspOptions,
) -> Result<(), Box<dyn Error + Send + Sync>> {
let (initialize_id, params_value) = connection.initialize_start()?;
let params: InitializeParams = serde_json::from_value(params_value)?;
let (workspace_root, multi_root_warning) = resolve_workspace_root(¶ms);
let run_mode = parse_run_mode(params.initialization_options.as_ref());
let register_watched_files = supports_watched_files_registration(¶ms.capabilities);
let initialize_result = InitializeResult {
server_info: Some(ServerInfo {
name: "import-lint".to_string(),
version: Some(env!("CARGO_PKG_VERSION").to_string()),
}),
capabilities: server_capabilities(),
};
connection.initialize_finish(initialize_id, serde_json::to_value(&initialize_result)?)?;
let mut server = Server::new(connection, options.debounce, workspace_root, run_mode);
if let Some(message) = multi_root_warning {
server.show_message(MessageType::WARNING, message);
}
server.try_build_session();
if register_watched_files {
server.register_watched_files();
}
server.run()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RunMode {
OnType,
OnSave,
}
fn parse_run_mode(initialization_options: Option<&serde_json::Value>) -> RunMode {
match initialization_options
.and_then(|options| options.get("run"))
.and_then(|value| value.as_str())
{
Some("onSave") => RunMode::OnSave,
_ => RunMode::OnType,
}
}
#[allow(deprecated)]
fn resolve_workspace_root(params: &InitializeParams) -> (PathBuf, Option<String>) {
if let Some(folders) = ¶ms.workspace_folders
&& let Some(first) = folders.first()
&& let Some(path) = uri_to_dir_path(&first.uri)
{
let warning = (folders.len() > 1).then(|| {
format!(
"import-lint: multiple workspace folders are open; using {} \
(multi-root workspaces are not supported, docs/PLAN-lsp.md E10)",
path.display()
)
});
return (path, warning);
}
if let Some(root_uri) = ¶ms.root_uri
&& let Some(path) = uri_to_dir_path(root_uri)
{
return (path, None);
}
(
std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
None,
)
}
fn uri_to_dir_path(uri: &Url) -> Option<PathBuf> {
let path = uri.to_file_path().ok()?;
Some(path.canonicalize().unwrap_or(path))
}
fn supports_watched_files_registration(capabilities: &ClientCapabilities) -> bool {
capabilities
.workspace
.as_ref()
.and_then(|workspace| workspace.did_change_watched_files.as_ref())
.and_then(|watched_files| watched_files.dynamic_registration)
.unwrap_or(false)
}
fn server_capabilities() -> ServerCapabilities {
ServerCapabilities {
text_document_sync: Some(TextDocumentSyncCapability::Options(
TextDocumentSyncOptions {
open_close: Some(true),
change: Some(TextDocumentSyncKind::FULL),
will_save: None,
will_save_wait_until: None,
save: Some(TextDocumentSyncSaveOptions::SaveOptions(SaveOptions {
include_text: Some(false),
})),
},
)),
..ServerCapabilities::default()
}
}
struct Server {
connection: Connection,
debounce: Duration,
workspace_root: PathBuf,
run_mode: RunMode,
session: Option<WatchSession>,
open_docs: HashMap<Url, OpenDocument>,
published: HashMap<PathBuf, Vec<Diagnostic>>,
pending: Vec<ChangeKind>,
deadline: Option<Instant>,
next_request_id: i32,
}
struct OpenDocument {
path: PathBuf,
text: String,
}
impl Server {
fn new(
connection: Connection,
debounce: Duration,
workspace_root: PathBuf,
run_mode: RunMode,
) -> Self {
Server {
connection,
debounce,
workspace_root,
run_mode,
session: None,
open_docs: HashMap::new(),
published: HashMap::new(),
pending: Vec::new(),
deadline: None,
next_request_id: 1,
}
}
fn next_request_id(&mut self) -> RequestId {
let id = self.next_request_id;
self.next_request_id += 1;
RequestId::from(id)
}
fn run(mut self) -> Result<(), Box<dyn Error + Send + Sync>> {
loop {
match self.recv_next() {
NextMessage::Message(Message::Request(req)) => {
if req.method == Shutdown::METHOD {
self.connection.handle_shutdown(&req)?;
return Ok(());
}
let response = Response::new_err(
req.id,
ErrorCode::MethodNotFound as i32,
format!("import-lint: unsupported request method {}", req.method),
);
if self.connection.sender.send(response.into()).is_err() {
return Ok(());
}
}
NextMessage::Message(Message::Notification(not)) => {
if not.method == Exit::METHOD {
return Ok(());
}
self.handle_notification(not);
}
NextMessage::Message(Message::Response(_)) => {}
NextMessage::Timeout => self.flush(),
NextMessage::Disconnected => return Ok(()),
}
}
}
fn recv_next(&self) -> NextMessage {
if let Some(deadline) = self.deadline {
let remaining = deadline.saturating_duration_since(Instant::now());
crossbeam_channel::select! {
recv(self.connection.receiver) -> msg => match msg {
Ok(message) => NextMessage::Message(message),
Err(_) => NextMessage::Disconnected,
},
default(remaining) => NextMessage::Timeout,
}
} else {
match self.connection.receiver.recv() {
Ok(message) => NextMessage::Message(message),
Err(_) => NextMessage::Disconnected,
}
}
}
fn handle_notification(&mut self, not: LspNotification) {
let not = match cast_notification::<DidOpenTextDocument>(not) {
Ok(params) => return self.on_did_open(params),
Err(not) => not,
};
let not = match cast_notification::<DidChangeTextDocument>(not) {
Ok(params) => return self.on_did_change(params),
Err(not) => not,
};
let not = match cast_notification::<DidSaveTextDocument>(not) {
Ok(params) => return self.on_did_save(params),
Err(not) => not,
};
let not = match cast_notification::<DidCloseTextDocument>(not) {
Ok(params) => return self.on_did_close(params),
Err(not) => not,
};
if let Ok(params) = cast_notification::<DidChangeWatchedFiles>(not) {
self.on_did_change_watched_files(params);
}
}
fn on_did_open(&mut self, params: DidOpenTextDocumentParams) {
let uri = params.text_document.uri;
let Some(path) = uri_to_canonical_path(&uri) else {
return;
};
let text = params.text_document.text;
if let Some(session) = &mut self.session {
session.set_overlay(path.clone(), text.clone());
}
self.open_docs.insert(
uri,
OpenDocument {
path: path.clone(),
text,
},
);
self.pending.push(ChangeKind::ContentEdit(path));
self.flush();
}
fn on_did_change(&mut self, params: DidChangeTextDocumentParams) {
let Some(change) = params.content_changes.into_iter().last() else {
return;
};
let Some(doc) = self.open_docs.get_mut(¶ms.text_document.uri) else {
return;
};
doc.text = change.text;
let path = doc.path.clone();
if let Some(session) = &mut self.session {
session.set_overlay(path.clone(), doc.text.clone());
}
self.pending.push(ChangeKind::ContentEdit(path));
match self.run_mode {
RunMode::OnType => self.deadline = Some(Instant::now() + self.debounce),
RunMode::OnSave => {}
}
}
fn on_did_save(&mut self, params: DidSaveTextDocumentParams) {
let Some(doc) = self.open_docs.get(¶ms.text_document.uri) else {
return;
};
self.pending.push(ChangeKind::ContentEdit(doc.path.clone()));
self.flush();
}
fn on_did_close(&mut self, params: DidCloseTextDocumentParams) {
let Some(doc) = self.open_docs.remove(¶ms.text_document.uri) else {
return;
};
if let Some(session) = &mut self.session {
session.clear_overlay(&doc.path);
}
self.pending.push(ChangeKind::ContentEdit(doc.path));
self.flush();
}
fn on_did_change_watched_files(&mut self, params: DidChangeWatchedFilesParams) {
let tsconfig_path = self
.session
.as_ref()
.and_then(|session| session.watch_targets().tsconfig_path);
for change in params.changes {
let Some(path) = change.uri.to_file_path().ok() else {
continue;
};
self.pending
.push(classify_watched_file(&path, tsconfig_path.as_deref()));
}
self.flush();
}
fn register_watched_files(&mut self) {
let mut watchers = vec![
watcher_for("**/.importlintrc.json"),
watcher_for("**/.importlintrc.jsonc"),
watcher_for("**/tsconfig.json"),
watcher_for("**/package.json"),
];
if let Some(session) = &self.session
&& let Some(tsconfig_path) = session.watch_targets().tsconfig_path
{
let default_name =
tsconfig_path.file_name().and_then(|name| name.to_str()) == Some("tsconfig.json");
if !default_name {
watchers.push(watcher_for(&tsconfig_path.to_string_lossy()));
}
}
let registration = Registration {
id: "import-lint-watched-files".to_string(),
method: DidChangeWatchedFiles::METHOD.to_string(),
register_options: Some(
serde_json::to_value(DidChangeWatchedFilesRegistrationOptions { watchers })
.expect("DidChangeWatchedFilesRegistrationOptions always serializes"),
),
};
let params = RegistrationParams {
registrations: vec![registration],
};
let id = self.next_request_id();
let request = LspRequest::new(id, RegisterCapability::METHOD.to_string(), params);
let _ = self.connection.sender.send(request.into());
}
fn try_build_session(&mut self) {
let options = WatchSessionOptions {
cli_paths: Vec::new(),
explicit_config: None,
cli_tsconfig: None,
report_unresolved: false,
quiet: false,
cwd: self.workspace_root.clone(),
};
match WatchSession::new(options) {
Ok(mut session) => {
if self.open_docs.is_empty() {
let diagnostics = session.last_diagnostics().to_vec();
self.session = Some(session);
self.publish_diagnostics(diagnostics);
} else {
let replay: Vec<ChangeKind> = self
.open_docs
.values()
.map(|doc| {
session.set_overlay(doc.path.clone(), doc.text.clone());
ChangeKind::ContentEdit(doc.path.clone())
})
.collect();
let outcome = session.run_cycle(&replay);
self.session = Some(session);
self.publish_diagnostics(outcome.diagnostics);
}
}
Err(err) => {
self.session = None;
self.show_message(MessageType::ERROR, format!("import-lint: {err}"));
}
}
}
fn flush(&mut self) {
self.deadline = None;
let pending = std::mem::take(&mut self.pending);
if pending.is_empty() {
return;
}
let Some(session) = &mut self.session else {
if pending
.iter()
.any(|change| matches!(change, ChangeKind::ConfigChanged))
{
self.try_build_session();
}
return;
};
let outcome = session.run_cycle(&pending);
if let Some(message) = outcome.config_error {
self.show_message(MessageType::WARNING, message);
}
self.publish_diagnostics(outcome.diagnostics);
}
fn publish_diagnostics(&mut self, diagnostics: Vec<RenderedDiagnostic>) {
let mut grouped: HashMap<PathBuf, Vec<Diagnostic>> = HashMap::new();
for diagnostic in &diagnostics {
grouped
.entry(diagnostic.file.clone())
.or_default()
.push(to_lsp_diagnostic(diagnostic));
}
for (path, diags) in &grouped {
if self.published.get(path) != Some(diags) {
self.publish_for_path(path, diags.clone());
}
}
let vanished: Vec<PathBuf> = self
.published
.keys()
.filter(|path| !grouped.contains_key(*path))
.cloned()
.collect();
for path in vanished {
self.publish_for_path(&path, Vec::new());
}
self.published = grouped;
}
fn publish_for_path(&self, path: &Path, diagnostics: Vec<Diagnostic>) {
let Some(uri) = path_to_uri(path) else {
return;
};
let params = PublishDiagnosticsParams {
uri,
diagnostics,
version: None,
};
let not = LspNotification::new(PublishDiagnostics::METHOD.to_string(), params);
let _ = self.connection.sender.send(not.into());
}
fn show_message(&self, typ: MessageType, message: String) {
let params = ShowMessageParams { typ, message };
let not = LspNotification::new(ShowMessage::METHOD.to_string(), params);
let _ = self.connection.sender.send(not.into());
}
}
enum NextMessage {
Message(Message),
Timeout,
Disconnected,
}
fn cast_notification<N>(not: LspNotification) -> Result<N::Params, LspNotification>
where
N: lsp_types::notification::Notification,
{
match not.extract(N::METHOD) {
Ok(params) => Ok(params),
Err(ExtractError::MethodMismatch(not)) => Err(not),
Err(ExtractError::JsonError { method, error }) => {
panic!("import-lint: malformed {method} notification: {error}")
}
}
}
fn watcher_for(glob: &str) -> FileSystemWatcher {
FileSystemWatcher {
glob_pattern: GlobPattern::String(glob.to_string()),
kind: None,
}
}
fn classify_watched_file(path: &Path, tsconfig_path: Option<&Path>) -> ChangeKind {
let filename = path.file_name().and_then(|name| name.to_str());
if matches!(
filename,
Some(".importlintrc.json") | Some(".importlintrc.jsonc")
) {
return ChangeKind::ConfigChanged;
}
if filename == Some("tsconfig.json") || tsconfig_path.is_some_and(|expected| expected == path) {
return ChangeKind::TsconfigChanged;
}
ChangeKind::Structural
}