diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 47426d04..a2751f01 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -20,7 +20,6 @@ concurrency: cancel-in-progress: true env: - RUSTFLAGS: -A dead_code RUST_LOG: info RUST_BACKTRACE: 1 RUSTUP_WINDOWS_PATH_ADD_BIN: 1 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d50ed529..f11d4318 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,9 +7,6 @@ permissions: contents: write env: - # Ultimately, we shouldn't ignore warnings. - # We need to pass it as an ENV because inlining doesn't work on Windows. - RUSTFLAGS: -A dead_code # Need these guys for cross-compilation CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER: aarch64-linux-gnu-gcc diff --git a/crates/pgt_analyse/src/rule.rs b/crates/pgt_analyse/src/rule.rs index f4936459..f135705e 100644 --- a/crates/pgt_analyse/src/rule.rs +++ b/crates/pgt_analyse/src/rule.rs @@ -260,10 +260,6 @@ impl RuleDiagnostic { self.footer(LogCategory::Warn, msg) } - pub(crate) fn span(&self) -> Option { - self.span - } - pub fn advices(&self) -> &RuleAdvice { &self.rule_advice } diff --git a/crates/pgt_cli/src/commands/check.rs b/crates/pgt_cli/src/commands/check.rs index c7cde669..46819624 100644 --- a/crates/pgt_cli/src/commands/check.rs +++ b/crates/pgt_cli/src/commands/check.rs @@ -61,10 +61,6 @@ impl CommandRunner for CheckCommandPayload { self.stdin_file_path.as_deref() } - fn should_write(&self) -> bool { - false - } - fn get_execution( &self, cli_options: &CliOptions, diff --git a/crates/pgt_cli/src/commands/daemon.rs b/crates/pgt_cli/src/commands/daemon.rs index db6c4eb1..0f6c4aac 100644 --- a/crates/pgt_cli/src/commands/daemon.rs +++ b/crates/pgt_cli/src/commands/daemon.rs @@ -5,7 +5,7 @@ use crate::{ use pgt_console::{ConsoleExt, markup}; use pgt_lsp::ServerFactory; use pgt_workspace::{TransportError, WorkspaceError, workspace::WorkspaceClient}; -use std::{env, fs, path::PathBuf}; +use std::{env, path::PathBuf}; use tokio::io; use tokio::runtime::Runtime; use tracing::subscriber::Interest; @@ -175,33 +175,6 @@ async fn start_lsp_proxy( } } -pub(crate) fn read_most_recent_log_file( - log_path: Option, - log_file_name_prefix: String, -) -> io::Result> { - let pgt_log_path = log_path.unwrap_or(default_pgt_log_path()); - - let most_recent = fs::read_dir(pgt_log_path)? - .flatten() - .filter(|file| file.file_type().is_ok_and(|ty| ty.is_file())) - .filter_map(|file| { - match file - .file_name() - .to_str()? - .split_once(log_file_name_prefix.as_str()) - { - Some((_, date_part)) if date_part.split('-').count() == 4 => Some(file.path()), - _ => None, - } - }) - .max(); - - match most_recent { - Some(file) => Ok(Some(fs::read_to_string(file)?)), - None => Ok(None), - } -} - /// Set up the [tracing]-based logging system for the server /// The events received by the subscriber are filtered at the `info` level, /// then printed using the [HierarchicalLayer] layer, and the resulting text diff --git a/crates/pgt_cli/src/commands/mod.rs b/crates/pgt_cli/src/commands/mod.rs index b475d298..49b74766 100644 --- a/crates/pgt_cli/src/commands/mod.rs +++ b/crates/pgt_cli/src/commands/mod.rs @@ -15,7 +15,6 @@ use pgt_workspace::workspace::UpdateSettingsParams; use pgt_workspace::{DynRef, Workspace, WorkspaceError}; use std::ffi::OsString; use std::path::PathBuf; - pub(crate) mod check; pub(crate) mod clean; pub(crate) mod daemon; @@ -24,6 +23,7 @@ pub(crate) mod version; #[derive(Debug, Clone, Bpaf)] #[bpaf(options, version(VERSION))] +#[allow(clippy::large_enum_variant)] /// Postgres Tools official CLI. Use it to check the health of your project or run it to check single files. pub enum PgtCommand { /// Shows the version information and quit. @@ -338,9 +338,6 @@ pub(crate) trait CommandRunner: Sized { /// It returns the file path to use in `stdin` mode. fn get_stdin_file_path(&self) -> Option<&str>; - /// Whether the command should write the files. - fn should_write(&self) -> bool; - /// Returns the [Execution] mode. fn get_execution( &self, @@ -357,11 +354,6 @@ pub(crate) trait CommandRunner: Sized { fn check_incompatible_arguments(&self) -> Result<(), CliDiagnostic> { Ok(()) } - - /// Checks whether the configuration has errors. - fn should_validate_configuration_diagnostics(&self) -> bool { - true - } } fn get_files_to_process_with_cli_options( diff --git a/crates/pgt_cli/src/diagnostics.rs b/crates/pgt_cli/src/diagnostics.rs index 0c5bd24f..d24d02e9 100644 --- a/crates/pgt_cli/src/diagnostics.rs +++ b/crates/pgt_cli/src/diagnostics.rs @@ -1,4 +1,3 @@ -use pgt_console::fmt::Display; use pgt_console::markup; use pgt_diagnostics::adapters::{BpafError, IoError, SerdeJsonError}; use pgt_diagnostics::{ @@ -231,25 +230,6 @@ pub struct IncompatibleEndConfiguration { )] pub struct NoFilesWereProcessed; -#[derive(Debug, Diagnostic)] -#[diagnostic( - category = "internalError/fs", - severity = Warning, - tags(DEPRECATED_CODE) -)] -pub struct DeprecatedArgument { - #[message] - pub message: MessageAndDescription, -} - -impl DeprecatedArgument { - pub fn new(message: impl Display) -> Self { - Self { - message: MessageAndDescription::from(markup! {{message}}.to_owned()), - } - } -} - #[derive(Debug, Diagnostic)] pub enum ReportDiagnostic { /// Emitted when trying to serialise the report diff --git a/crates/pgt_cli/src/execute/diagnostics.rs b/crates/pgt_cli/src/execute/diagnostics.rs index fff49223..a355abec 100644 --- a/crates/pgt_cli/src/execute/diagnostics.rs +++ b/crates/pgt_cli/src/execute/diagnostics.rs @@ -19,6 +19,7 @@ pub(crate) trait ResultExt { code: &'static Category, ) -> Result; + #[allow(unused)] fn with_file_path_and_code_and_tags( self, file_path: String, diff --git a/crates/pgt_cli/src/execute/mod.rs b/crates/pgt_cli/src/execute/mod.rs index 753e739d..90a5bb98 100644 --- a/crates/pgt_cli/src/execute/mod.rs +++ b/crates/pgt_cli/src/execute/mod.rs @@ -11,11 +11,10 @@ use crate::reporter::junit::{JunitReporter, JunitReporterVisitor}; use crate::reporter::terminal::{ConsoleReporter, ConsoleReporterVisitor}; use crate::{CliDiagnostic, CliSession, DiagnosticsPayload, Reporter}; use pgt_diagnostics::{Category, category}; -use pgt_fs::PgTPath; use std::borrow::Borrow; use std::ffi::OsString; use std::fmt::{Display, Formatter}; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use tracing::info; /// Useful information during the traversal of files and virtual content @@ -37,14 +36,10 @@ impl Execution { } } -#[derive(Debug, Clone, Copy)] -pub enum ExecutionEnvironment { - GitHub, -} - /// A type that holds the information to execute the CLI via `stdin #[derive(Debug, Clone)] pub struct Stdin( + #[allow(unused)] /// The virtual path to the file PathBuf, /// The content of the file @@ -52,10 +47,6 @@ pub struct Stdin( ); impl Stdin { - fn as_path(&self) -> &Path { - self.0.as_path() - } - fn as_content(&self) -> &str { self.1.as_str() } @@ -170,10 +161,6 @@ impl Execution { } } - pub(crate) const fn is_dummy(&self) -> bool { - matches!(self.traversal_mode, TraversalMode::Dummy) - } - /// Whether the traversal mode requires write access to files pub(crate) const fn requires_write_access(&self) -> bool { match self.traversal_mode { @@ -202,6 +189,7 @@ impl Execution { false } + #[allow(unused)] /// Returns [true] if the user used the `--write`/`--fix` option pub(crate) fn is_write(&self) -> bool { match self.traversal_mode { @@ -232,14 +220,7 @@ pub fn execute_mode( // don't do any traversal if there's some content coming from stdin if let Some(stdin) = execution.as_stdin_file() { - let pgt_path = PgTPath::new(stdin.as_path()); - std_in::run( - session, - &execution, - pgt_path, - stdin.as_content(), - cli_options.verbose, - ) + std_in::run(session, stdin.as_content()) } else { let TraverseResult { summary, diff --git a/crates/pgt_cli/src/execute/process_file.rs b/crates/pgt_cli/src/execute/process_file.rs index f2d4d19e..421f9bb3 100644 --- a/crates/pgt_cli/src/execute/process_file.rs +++ b/crates/pgt_cli/src/execute/process_file.rs @@ -15,29 +15,34 @@ pub(crate) enum FileStatus { Changed, /// File unchanged, and it was a success Unchanged, + /// While handling the file, something happened + #[allow(unused)] Message(Message), + /// A match was found while searching a file + #[allow(unused)] SearchResult(usize, Message), + /// File ignored, it should not be count as "handled" + #[allow(unused)] Ignored, + /// Files that belong to other tools and shouldn't be touched + #[allow(unused)] Protected(String), } -impl FileStatus { - pub const fn is_changed(&self) -> bool { - matches!(self, Self::Changed) - } -} - /// Wrapper type for messages that can be printed during the traversal process #[derive(Debug)] pub(crate) enum Message { + #[allow(unused)] SkippedFixes { /// Suggested fixes skipped during the lint traversal skipped_suggested_fixes: u32, }, + + #[allow(unused)] Failure, Error(Error), Diagnostics { @@ -48,19 +53,6 @@ pub(crate) enum Message { }, } -impl Message { - pub(crate) const fn is_failure(&self) -> bool { - matches!(self, Message::Failure) - } -} - -#[derive(Debug)] -pub(crate) enum DiffKind { - Format, - OrganizeImports, - Assists, -} - impl From for Message where Error: From, diff --git a/crates/pgt_cli/src/execute/process_file/workspace_file.rs b/crates/pgt_cli/src/execute/process_file/workspace_file.rs index 55f36aad..790176b9 100644 --- a/crates/pgt_cli/src/execute/process_file/workspace_file.rs +++ b/crates/pgt_cli/src/execute/process_file/workspace_file.rs @@ -4,7 +4,6 @@ use pgt_diagnostics::{Error, category}; use pgt_fs::{File, OpenOptions, PgTPath}; use pgt_workspace::workspace::{ChangeParams, FileGuard, OpenFileParams}; use pgt_workspace::{Workspace, WorkspaceError}; -use std::ffi::OsStr; use std::path::{Path, PathBuf}; /// Small wrapper that holds information and operations around the current processed file @@ -59,11 +58,8 @@ impl<'ctx, 'app> WorkspaceFile<'ctx, 'app> { self.guard().get_file_content() } - pub(crate) fn as_extension(&self) -> Option<&OsStr> { - self.path.extension() - } - /// It updates the workspace file with `new_content` + #[allow(dead_code)] pub(crate) fn update_file(&mut self, new_content: impl Into) -> Result<(), Error> { let new_content = new_content.into(); diff --git a/crates/pgt_cli/src/execute/std_in.rs b/crates/pgt_cli/src/execute/std_in.rs index 8fee336f..f9346f6a 100644 --- a/crates/pgt_cli/src/execute/std_in.rs +++ b/crates/pgt_cli/src/execute/std_in.rs @@ -1,20 +1,10 @@ //! In here, there are the operations that run via standard input //! -use crate::execute::Execution; use crate::{CliDiagnostic, CliSession}; use pgt_console::{ConsoleExt, markup}; -use pgt_fs::PgTPath; -pub(crate) fn run<'a>( - session: CliSession, - mode: &'a Execution, - pgt_path: PgTPath, - content: &'a str, - verbose: bool, -) -> Result<(), CliDiagnostic> { - let workspace = &*session.app.workspace; +pub(crate) fn run(session: CliSession, content: &str) -> Result<(), CliDiagnostic> { let console = &mut *session.app.console; - let version = 0; console.append(markup! {{content}}); Ok(()) diff --git a/crates/pgt_cli/src/execute/traverse.rs b/crates/pgt_cli/src/execute/traverse.rs index 700aa4c9..5673810c 100644 --- a/crates/pgt_cli/src/execute/traverse.rs +++ b/crates/pgt_cli/src/execute/traverse.rs @@ -188,6 +188,7 @@ fn traverse_inputs( struct DiagnosticsPrinter<'ctx> { /// Execution of the traversal + #[allow(dead_code)] execution: &'ctx Execution, /// The maximum number of diagnostics the console thread is allowed to print max_diagnostics: u32, @@ -435,10 +436,6 @@ impl TraversalOptions<'_, '_> { pub(crate) fn push_message(&self, msg: impl Into) { self.messages.send(msg.into()).ok(); } - - pub(crate) fn protected_file(&self, pgt_path: &PgTPath) { - self.push_diagnostic(WorkspaceError::protected_file(pgt_path.display().to_string()).into()) - } } impl TraversalContext for TraversalOptions<'_, '_> { diff --git a/crates/pgt_cli/src/reporter/terminal.rs b/crates/pgt_cli/src/reporter/terminal.rs index b3396786..6e10efc8 100644 --- a/crates/pgt_cli/src/reporter/terminal.rs +++ b/crates/pgt_cli/src/reporter/terminal.rs @@ -130,13 +130,13 @@ impl fmt::Display for Files { } } -struct SummaryDetail<'a>(pub(crate) &'a TraversalMode, usize); +struct SummaryDetail(usize); -impl fmt::Display for SummaryDetail<'_> { +impl fmt::Display for SummaryDetail { fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> { - if self.1 > 0 { + if self.0 > 0 { fmt.write_markup(markup! { - " Fixed "{Files(self.1)}"." + " Fixed "{Files(self.0)}"." }) } else { fmt.write_markup(markup! { @@ -168,7 +168,7 @@ pub(crate) struct ConsoleTraversalSummary<'a>( impl fmt::Display for ConsoleTraversalSummary<'_> { fn fmt(&self, fmt: &mut Formatter) -> io::Result<()> { let summary = SummaryTotal(self.0, self.1.changed + self.1.unchanged, &self.1.duration); - let detail = SummaryDetail(self.0, self.1.changed); + let detail = SummaryDetail(self.1.changed); fmt.write_markup(markup!({summary}{detail}))?; if self.1.errors > 0 { diff --git a/crates/pgt_cli/src/service/mod.rs b/crates/pgt_cli/src/service/mod.rs index 1be4ea5c..a09a880c 100644 --- a/crates/pgt_cli/src/service/mod.rs +++ b/crates/pgt_cli/src/service/mod.rs @@ -70,11 +70,11 @@ type JsonRpcResult = Result, TransportError>; /// This structs holds an instance of the `tokio` runtime, as well as the /// following fields: /// - `write_send` is a sender handle to the "write channel", an MPSC channel -/// that's used to queue up requests to be sent to the server (for simplicity -/// the requests are pushed to the channel as serialized byte buffers) +/// that's used to queue up requests to be sent to the server (for simplicity +/// the requests are pushed to the channel as serialized byte buffers) /// - `pending_requests` is handle to a shared hashmap where the keys are `u64` -/// corresponding to request IDs, and the values are sender handles to oneshot -/// channel instances that can be consumed to fulfill the associated request +/// corresponding to request IDs, and the values are sender handles to oneshot +/// channel instances that can be consumed to fulfill the associated request /// /// Creating a new `SocketTransport` instance requires providing a `tokio` /// runtime instance as well as the "read half" and "write half" of the socket @@ -85,7 +85,7 @@ type JsonRpcResult = Result, TransportError>; /// /// This concurrent handling of I/O is implemented using two "background tasks": /// - the `write_task` pulls outgoing messages from the "write channel" and -/// writes them to the "write half" of the socket +/// writes them to the "write half" of the socket /// - the `read_task` reads incoming messages from the "read half" of the /// socket, then looks up a request with an ID corresponding to the received /// message in the "pending requests" map. If a pending request is found, it's diff --git a/crates/pgt_cli/src/service/unix.rs b/crates/pgt_cli/src/service/unix.rs index 68322584..2ff7adb0 100644 --- a/crates/pgt_cli/src/service/unix.rs +++ b/crates/pgt_cli/src/service/unix.rs @@ -24,6 +24,7 @@ fn get_socket_name() -> PathBuf { pgt_fs::ensure_cache_dir().join(format!("pgt-socket-{}", pgt_configuration::VERSION)) } +#[allow(dead_code)] pub(crate) fn enumerate_pipes() -> io::Result> { fs::read_dir(pgt_fs::ensure_cache_dir()).map(|iter| { iter.filter_map(|entry| { diff --git a/crates/pgt_completions/src/providers/functions.rs b/crates/pgt_completions/src/providers/functions.rs index 2fbcaacf..b4a9c35a 100644 --- a/crates/pgt_completions/src/providers/functions.rs +++ b/crates/pgt_completions/src/providers/functions.rs @@ -6,11 +6,11 @@ use crate::{ pub fn complete_functions(ctx: &CompletionContext, builder: &mut CompletionBuilder) { let available_functions = &ctx.schema_cache.functions; - for foo in available_functions { + for func in available_functions { let item = CompletionItem { - label: foo.name.clone(), - score: CompletionRelevanceData::Function(foo).get_score(ctx), - description: format!("Schema: {}", foo.schema), + label: func.name.clone(), + score: CompletionRelevanceData::Function(func).get_score(ctx), + description: format!("Schema: {}", func.schema), preselected: false, kind: CompletionItemKind::Function, }; diff --git a/crates/pgt_diagnostics/src/display/diff.rs b/crates/pgt_diagnostics/src/display/diff.rs index a5021a1a..1e01044a 100644 --- a/crates/pgt_diagnostics/src/display/diff.rs +++ b/crates/pgt_diagnostics/src/display/diff.rs @@ -99,11 +99,11 @@ pub(super) fn print_diff(fmt: &mut fmt::Formatter<'_>, diff: &TextEdit) -> io::R /// This function scans the list of DiffOps that make up the `diff` and derives /// the following data structures: /// - `modified_lines` is the set of [LineKey] that contain at least one insert -/// or delete operation +/// or delete operation /// - `inserted_lines` maps a [LineKey] to the list of diff operations that -/// happen on the corresponding line +/// happen on the corresponding line /// - `before_line_to_after` maps line numbers in the old revision of the text -/// to line numbers in the new revision +/// to line numbers in the new revision /// - `after_line` counts the number of lines in the new revision of the document /// - `before_line` counts the number of lines in the old revision of the document fn process_diff_ops<'diff>( diff --git a/crates/pgt_diagnostics_macros/src/parse.rs b/crates/pgt_diagnostics_macros/src/parse.rs index 298358d0..0e6e1b91 100644 --- a/crates/pgt_diagnostics_macros/src/parse.rs +++ b/crates/pgt_diagnostics_macros/src/parse.rs @@ -9,6 +9,7 @@ use syn::{ token::Paren, }; +#[allow(clippy::large_enum_variant)] pub(crate) enum DeriveInput { DeriveStructInput(DeriveStructInput), DeriveEnumInput(DeriveEnumInput), diff --git a/crates/pgt_lsp/src/adapters/line_index.rs b/crates/pgt_lsp/src/adapters/line_index.rs index 88b1351a..79a48b10 100644 --- a/crates/pgt_lsp/src/adapters/line_index.rs +++ b/crates/pgt_lsp/src/adapters/line_index.rs @@ -67,16 +67,6 @@ impl LineIndex { } } - /// Return the number of lines in the index, clamped to [u32::MAX] - pub fn len(&self) -> u32 { - self.newlines.len().try_into().unwrap_or(u32::MAX) - } - - /// Return `true` if the index contains no lines. - pub fn is_empty(&self) -> bool { - self.newlines.is_empty() - } - pub fn line_col(&self, offset: TextSize) -> Option { let line = self.newlines.partition_point(|&it| it <= offset) - 1; let line_start_offset = self.newlines.get(line)?; diff --git a/crates/pgt_lsp/src/diagnostics.rs b/crates/pgt_lsp/src/diagnostics.rs index 9f156102..2c7acbba 100644 --- a/crates/pgt_lsp/src/diagnostics.rs +++ b/crates/pgt_lsp/src/diagnostics.rs @@ -1,9 +1,6 @@ -use crate::utils::into_lsp_error; use anyhow::Error; -use pgt_diagnostics::print_diagnostic_to_string; use pgt_workspace::WorkspaceError; use std::fmt::{Display, Formatter}; -use tower_lsp::lsp_types::MessageType; #[derive(Debug)] pub enum LspError { @@ -43,34 +40,3 @@ impl Display for LspError { } } } - -/// Receives an error coming from a LSP query, and converts it into a JSON-RPC error. -/// -/// It accepts a `Client`, so contextual messages are sent to the user. -pub(crate) async fn handle_lsp_error( - err: LspError, - client: &tower_lsp::Client, -) -> Result, tower_lsp::jsonrpc::Error> { - match err { - LspError::WorkspaceError(err) => match err { - // diagnostics that shouldn't raise an hard error, but send a message to the user - WorkspaceError::FileIgnored(_) | WorkspaceError::FileTooLarge(_) => { - let message = format!("{err}"); - client.log_message(MessageType::WARNING, message).await; - Ok(None) - } - - _ => { - let message = format!("{err}"); - client.log_message(MessageType::ERROR, message).await; - Ok(None) - } - }, - LspError::Anyhow(err) => Err(into_lsp_error(err)), - LspError::Error(err) => { - let message = print_diagnostic_to_string(&err); - client.log_message(MessageType::ERROR, message).await; - Ok(None) - } - } -} diff --git a/crates/pgt_lsp/src/handlers/code_actions.rs b/crates/pgt_lsp/src/handlers/code_actions.rs index 4e118c2b..b2616177 100644 --- a/crates/pgt_lsp/src/handlers/code_actions.rs +++ b/crates/pgt_lsp/src/handlers/code_actions.rs @@ -63,7 +63,7 @@ pub fn get_actions( Ok(actions .into_iter() - .map(|ac| CodeActionOrCommand::CodeAction(ac)) + .map(CodeActionOrCommand::CodeAction) .collect()) } @@ -93,7 +93,7 @@ pub async fn execute_command( path, })?; - /** + /* * Updating all diagnostics: the changes caused by the statement execution * might affect many files. * diff --git a/crates/pgt_lsp/src/server.rs b/crates/pgt_lsp/src/server.rs index 562a0777..d4f801f2 100644 --- a/crates/pgt_lsp/src/server.rs +++ b/crates/pgt_lsp/src/server.rs @@ -1,13 +1,9 @@ use crate::capabilities::server_capabilities; -use crate::diagnostics::{LspError, handle_lsp_error}; use crate::handlers; -use crate::session::{ - CapabilitySet, CapabilityStatus, ClientInformation, Session, SessionHandle, SessionKey, -}; +use crate::session::{CapabilitySet, CapabilityStatus, Session, SessionHandle, SessionKey}; use crate::utils::{into_lsp_error, panic_to_lsp_error}; use futures::FutureExt; use futures::future::ready; -use pgt_diagnostics::panic::PanicError; use pgt_fs::{ConfigName, FileSystem, OsFileSystem}; use pgt_workspace::{DynRef, Workspace, workspace}; use rustc_hash::FxHashMap; @@ -88,20 +84,6 @@ impl LSPServer { self.session.register_capabilities(capabilities).await; } - - async fn map_op_error( - &self, - result: Result, LspError>, PanicError>, - ) -> LspResult> { - match result { - Ok(result) => match result { - Ok(result) => Ok(result), - Err(err) => handle_lsp_error(err, &self.session.client).await, - }, - - Err(err) => Err(into_lsp_error(err)), - } - } } #[tower_lsp::async_trait] @@ -125,10 +107,6 @@ impl LanguageServer for LSPServer { self.session.initialize( params.capabilities, - params.client_info.map(|client_info| ClientInformation { - name: client_info.name, - version: client_info.version, - }), params.root_uri, params.workspace_folders, ); @@ -231,13 +209,6 @@ impl LanguageServer for LSPServer { }; } - #[tracing::instrument(level = "trace", skip(self))] - async fn did_save(&self, params: DidSaveTextDocumentParams) { - // handlers::text_document::did_save(&self.session, params) - // .await - // .ok(); - } - #[tracing::instrument(level = "trace", skip(self))] async fn did_close(&self, params: DidCloseTextDocumentParams) { handlers::text_document::did_close(&self.session, params) @@ -270,7 +241,8 @@ impl LanguageServer for LSPServer { params: ExecuteCommandParams, ) -> LspResult> { match handlers::code_actions::execute_command(&self.session, params).await { - Ok(result) => LspResult::Ok(None), + // we'll inform the client within `code_actions::execute_command` + Ok(_) => LspResult::Ok(None), Err(err) => LspResult::Err(into_lsp_error(err)), } } diff --git a/crates/pgt_lsp/src/session.rs b/crates/pgt_lsp/src/session.rs index 5c10b980..64adf16a 100644 --- a/crates/pgt_lsp/src/session.rs +++ b/crates/pgt_lsp/src/session.rs @@ -30,14 +30,6 @@ use tower_lsp::lsp_types::{MessageType, Registration}; use tower_lsp::lsp_types::{Unregistration, WorkspaceFolder}; use tracing::{error, info}; -pub(crate) struct ClientInformation { - /// The name of the client - pub(crate) name: String, - - /// The version of the client - pub(crate) version: Option, -} - /// Key, uniquely identifying a LSP session. #[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)] pub(crate) struct SessionKey(pub u64); @@ -75,7 +67,6 @@ pub(crate) struct Session { struct InitializeParams { /// The capabilities provided by the client as part of [`lsp_types::InitializeParams`] client_capabilities: lsp_types::ClientCapabilities, - client_information: Option, root_uri: Option, #[allow(unused)] workspace_folders: Option>, @@ -97,10 +88,6 @@ impl ConfigurationStatus { pub(crate) const fn is_error(&self) -> bool { matches!(self, ConfigurationStatus::Error) } - - pub(crate) const fn is_loaded(&self) -> bool { - matches!(self, ConfigurationStatus::Loaded) - } } impl TryFrom for ConfigurationStatus { @@ -176,13 +163,11 @@ impl Session { pub(crate) fn initialize( &self, client_capabilities: lsp_types::ClientCapabilities, - client_information: Option, root_uri: Option, workspace_folders: Option>, ) { let result = self.initialize_params.set(InitializeParams { client_capabilities, - client_information, root_uri, workspace_folders, }); @@ -391,11 +376,6 @@ impl Session { } } - /// Returns a reference to the client information for this session - pub(crate) fn client_information(&self) -> Option<&ClientInformation> { - self.initialize_params.get()?.client_information.as_ref() - } - /// Returns a reference to the client capabilities for this session pub(crate) fn client_capabilities(&self) -> Option<&ClientCapabilities> { self.initialize_params diff --git a/crates/pgt_lsp/src/utils.rs b/crates/pgt_lsp/src/utils.rs index a27dfecb..92059b66 100644 --- a/crates/pgt_lsp/src/utils.rs +++ b/crates/pgt_lsp/src/utils.rs @@ -6,7 +6,6 @@ use pgt_console::fmt::Termcolor; use pgt_console::fmt::{self, Formatter}; use pgt_diagnostics::termcolor::NoColor; use pgt_diagnostics::{Diagnostic, DiagnosticTags, Location, PrintDescription, Severity, Visit}; -use pgt_text_edit::{CompressedOp, DiffOp, TextEdit}; use pgt_text_size::{TextRange, TextSize}; use std::any::Any; use std::borrow::Cow; @@ -18,74 +17,6 @@ use tower_lsp::lsp_types; use tower_lsp::lsp_types::{self as lsp, CodeDescription, Url}; use tracing::error; -pub(crate) fn text_edit( - line_index: &LineIndex, - diff: TextEdit, - position_encoding: PositionEncoding, - offset: Option, -) -> Result> { - let mut result: Vec = Vec::new(); - let mut offset = if let Some(offset) = offset { - TextSize::from(offset) - } else { - TextSize::from(0) - }; - - for op in diff.iter() { - match op { - CompressedOp::DiffOp(DiffOp::Equal { range }) => { - offset += range.len(); - } - CompressedOp::DiffOp(DiffOp::Insert { range }) => { - let start = to_lsp::position(line_index, offset, position_encoding)?; - - // Merge with a previous delete operation if possible - let last_edit = result.last_mut().filter(|text_edit| { - text_edit.range.end == start && text_edit.new_text.is_empty() - }); - - if let Some(last_edit) = last_edit { - last_edit.new_text = diff.get_text(*range).to_string(); - } else { - result.push(lsp::TextEdit { - range: lsp::Range::new(start, start), - new_text: diff.get_text(*range).to_string(), - }); - } - } - CompressedOp::DiffOp(DiffOp::Delete { range }) => { - let start = to_lsp::position(line_index, offset, position_encoding)?; - offset += range.len(); - let end = to_lsp::position(line_index, offset, position_encoding)?; - - result.push(lsp::TextEdit { - range: lsp::Range::new(start, end), - new_text: String::new(), - }); - } - - CompressedOp::EqualLines { line_count } => { - let mut line_col = line_index - .line_col(offset) - .expect("diff length is overflowing the line count in the original file"); - - line_col.line += line_count.get() + 1; - line_col.col = 0; - - // SAFETY: This should only happen if `line_index` wasn't built - // from the same string as the old revision of `diff` - let new_offset = line_index - .offset(line_col) - .expect("diff length is overflowing the line count in the original file"); - - offset = new_offset; - } - } - } - - Ok(result) -} - /// Convert an [pgt_diagnostics::Diagnostic] to a [lsp::Diagnostic], using the span /// of the diagnostic's primary label as the diagnostic range. /// Requires a [LineIndex] to convert a byte offset range to the line/col range @@ -209,6 +140,7 @@ impl Visit for RelatedInformationVisitor<'_> { } /// Convert a piece of markup into a String +#[allow(unused)] fn print_markup(markup: &MarkupBuf) -> String { let mut message = Termcolor(NoColor::new(Vec::new())); fmt::Display::fmt(markup, &mut Formatter::new(&mut message)) @@ -304,11 +236,81 @@ pub(crate) fn apply_document_changes( #[cfg(test)] mod tests { - use crate::adapters::PositionEncoding; use crate::adapters::line_index::LineIndex; - use pgt_text_edit::TextEdit; + use crate::adapters::{PositionEncoding, to_lsp}; + use anyhow::Result; + use pgt_text_edit::{CompressedOp, DiffOp, TextEdit}; + use pgt_text_size::TextSize; use tower_lsp::lsp_types as lsp; + fn text_edit( + line_index: &LineIndex, + diff: TextEdit, + position_encoding: PositionEncoding, + offset: Option, + ) -> Result> { + let mut result: Vec = Vec::new(); + let mut offset = if let Some(offset) = offset { + TextSize::from(offset) + } else { + TextSize::from(0) + }; + + for op in diff.iter() { + match op { + CompressedOp::DiffOp(DiffOp::Equal { range }) => { + offset += range.len(); + } + CompressedOp::DiffOp(DiffOp::Insert { range }) => { + let start = to_lsp::position(line_index, offset, position_encoding)?; + + // Merge with a previous delete operation if possible + let last_edit = result.last_mut().filter(|text_edit| { + text_edit.range.end == start && text_edit.new_text.is_empty() + }); + + if let Some(last_edit) = last_edit { + last_edit.new_text = diff.get_text(*range).to_string(); + } else { + result.push(lsp::TextEdit { + range: lsp::Range::new(start, start), + new_text: diff.get_text(*range).to_string(), + }); + } + } + CompressedOp::DiffOp(DiffOp::Delete { range }) => { + let start = to_lsp::position(line_index, offset, position_encoding)?; + offset += range.len(); + let end = to_lsp::position(line_index, offset, position_encoding)?; + + result.push(lsp::TextEdit { + range: lsp::Range::new(start, end), + new_text: String::new(), + }); + } + + CompressedOp::EqualLines { line_count } => { + let mut line_col = line_index + .line_col(offset) + .expect("diff length is overflowing the line count in the original file"); + + line_col.line += line_count.get() + 1; + line_col.col = 0; + + // SAFETY: This should only happen if `line_index` wasn't built + // from the same string as the old revision of `diff` + let new_offset = line_index + .offset(line_col) + .expect("diff length is overflowing the line count in the original file"); + + offset = new_offset; + } + } + } + + Ok(result) + } + #[test] fn test_diff_1() { const OLD: &str = "line 1 old @@ -330,7 +332,7 @@ line 7 new"; let line_index = LineIndex::new(OLD); let diff = TextEdit::from_unicode_words(OLD, NEW); - let text_edit = super::text_edit(&line_index, diff, PositionEncoding::Utf8, None).unwrap(); + let text_edit = text_edit(&line_index, diff, PositionEncoding::Utf8, None).unwrap(); assert_eq!( text_edit.as_slice(), @@ -373,7 +375,7 @@ line 7 new"; let line_index = LineIndex::new(OLD); let diff = TextEdit::from_unicode_words(OLD, NEW); - let text_edit = super::text_edit(&line_index, diff, PositionEncoding::Utf8, None).unwrap(); + let text_edit = text_edit(&line_index, diff, PositionEncoding::Utf8, None).unwrap(); assert_eq!( text_edit.as_slice(), diff --git a/crates/pgt_test_macros/src/lib.rs b/crates/pgt_test_macros/src/lib.rs index 7c23d159..e8b954cf 100644 --- a/crates/pgt_test_macros/src/lib.rs +++ b/crates/pgt_test_macros/src/lib.rs @@ -164,7 +164,7 @@ impl Arguments { let span = self.pattern.lit.span(); let test_name = syn::Ident::new(&test_name, span); - let foo = &self.test_function; + let func = &self.test_function; modules.insert( path, @@ -174,7 +174,7 @@ impl Arguments { let test_fullpath = #test_fullpath; let test_expected_fullpath = #test_expected_fullpath; let test_dir = #test_dir; - #foo(test_fullpath, test_expected_fullpath, test_dir); + #func(test_fullpath, test_expected_fullpath, test_dir); } }, ) diff --git a/crates/pgt_text_size/src/size.rs b/crates/pgt_text_size/src/size.rs index dccb512e..e35e1c24 100644 --- a/crates/pgt_text_size/src/size.rs +++ b/crates/pgt_text_size/src/size.rs @@ -5,7 +5,6 @@ use { fmt, iter, num::TryFromIntError, ops::{Add, AddAssign, Sub, SubAssign}, - u32, }, }; diff --git a/crates/pgt_typecheck/src/diagnostics.rs b/crates/pgt_typecheck/src/diagnostics.rs index 0f373f71..b443dcc9 100644 --- a/crates/pgt_typecheck/src/diagnostics.rs +++ b/crates/pgt_typecheck/src/diagnostics.rs @@ -30,12 +30,16 @@ struct TypecheckAdvices { column: Option, data_type: Option, constraint: Option, - line: Option, - file: Option, detail: Option, - routine: Option, where_: Option, hint: Option, + + #[allow(unused)] + line: Option, + #[allow(unused)] + file: Option, + #[allow(unused)] + routine: Option, } impl Advices for TypecheckAdvices { diff --git a/crates/pgt_workspace/src/configuration.rs b/crates/pgt_workspace/src/configuration.rs index 726b23e0..536d5b9d 100644 --- a/crates/pgt_workspace/src/configuration.rs +++ b/crates/pgt_workspace/src/configuration.rs @@ -239,7 +239,7 @@ pub fn strip_jsonc_comments(jsonc_input: &str) -> String { json_output.push(last_char); } } else { - json_output.push_str(" "); + json_output.push(' '); } last_char = Some(cur_char); } diff --git a/crates/pgt_workspace/src/settings.rs b/crates/pgt_workspace/src/settings.rs index c635d167..29f05098 100644 --- a/crates/pgt_workspace/src/settings.rs +++ b/crates/pgt_workspace/src/settings.rs @@ -303,7 +303,7 @@ impl From for DatabaseSettings { .map(|stringset| { stringset.iter().any(|pattern| { let glob = Glob::new(pattern) - .expect(format!("Invalid pattern: {}", pattern).as_str()) + .unwrap_or_else(|_| panic!("Invalid pattern: {}", pattern)) .compile_matcher(); glob.is_match(format!("{}/{}", host, database)) diff --git a/crates/pgt_workspace/src/workspace/server.rs b/crates/pgt_workspace/src/workspace/server.rs index c37c5bb6..adbd72a6 100644 --- a/crates/pgt_workspace/src/workspace/server.rs +++ b/crates/pgt_workspace/src/workspace/server.rs @@ -288,7 +288,7 @@ impl Workspace for WorkspaceServer { Some("Statement execution not allowed against database.".into()) }; - for (stmt, range, txt) in eligible_statements { + for (stmt, _, txt) in eligible_statements { let title = format!( "Execute Statement: {}...", txt.chars().take(50).collect::() @@ -337,7 +337,7 @@ impl Workspace for WorkspaceServer { } }; - let conn = self.connection.write().unwrap(); + let conn = self.connection.read().unwrap(); let pool = match conn.get_pool() { Some(p) => p, None => { diff --git a/crates/pgt_workspace/src/workspace/server/migration.rs b/crates/pgt_workspace/src/workspace/server/migration.rs index baa736dd..ef4bdd25 100644 --- a/crates/pgt_workspace/src/workspace/server/migration.rs +++ b/crates/pgt_workspace/src/workspace/server/migration.rs @@ -3,6 +3,7 @@ use std::path::Path; #[derive(Debug)] pub(crate) struct Migration { pub(crate) timestamp: u64, + #[allow(unused)] pub(crate) name: String, } diff --git a/xtask/codegen/src/generate_configuration.rs b/xtask/codegen/src/generate_configuration.rs index 2c0820c4..91ae304c 100644 --- a/xtask/codegen/src/generate_configuration.rs +++ b/xtask/codegen/src/generate_configuration.rs @@ -536,13 +536,7 @@ fn generate_group_struct( let rule_option_type = quote! { pgt_analyser::options::#rule_name }; - let rule_option = if kind == RuleCategory::Action { - quote! { Option<#rule_config_type<#rule_option_type>> } - } else { - quote! { - Option<#rule_config_type<#rule_option_type>> - } - }; + let rule_option = quote! { Option<#rule_config_type<#rule_option_type>> }; schema_lines_rules.push(quote! { #[doc = #summary] #[serde(skip_serializing_if = "Option::is_none")] @@ -570,15 +564,9 @@ fn generate_group_struct( } }); - if kind == RuleCategory::Action { - get_rule_configuration_line.push(quote! { - #rule => self.#rule_identifier.as_ref().map(|conf| (conf.level(), conf.get_options())) - }); - } else { - get_rule_configuration_line.push(quote! { - #rule => self.#rule_identifier.as_ref().map(|conf| (conf.level(), conf.get_options())) - }); - } + get_rule_configuration_line.push(quote! { + #rule => self.#rule_identifier.as_ref().map(|conf| (conf.level(), conf.get_options())) + }); } let group_pascal_ident = Ident::new(&to_capitalized(group), Span::call_site());