1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-21 15:04:11 -05:00

refactor(lsp): changes for lsp_types 0.97.0 (#25169)

This commit is contained in:
Nayeem Rahman 2024-08-24 01:21:21 +01:00 committed by GitHub
parent bbd3a7e637
commit 2ab4afc6b8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
30 changed files with 633 additions and 548 deletions

87
Cargo.lock generated
View file

@ -752,6 +752,7 @@ dependencies = [
"deno_lockfile", "deno_lockfile",
"deno_terminal 0.2.0", "deno_terminal 0.2.0",
"deno_tls", "deno_tls",
"deno_tower_lsp",
"fastwebsockets", "fastwebsockets",
"file_test_runner", "file_test_runner",
"flaky_test", "flaky_test",
@ -768,7 +769,6 @@ dependencies = [
"serde", "serde",
"test_server", "test_server",
"tokio", "tokio",
"tower-lsp",
"trust-dns-client", "trust-dns-client",
"trust-dns-server", "trust-dns-server",
"url", "url",
@ -1178,6 +1178,7 @@ dependencies = [
"deno_semver", "deno_semver",
"deno_task_shell", "deno_task_shell",
"deno_terminal 0.2.0", "deno_terminal 0.2.0",
"deno_tower_lsp",
"dissimilar", "dissimilar",
"dotenvy", "dotenvy",
"dprint-plugin-json", "dprint-plugin-json",
@ -1244,7 +1245,6 @@ dependencies = [
"thiserror", "thiserror",
"tokio", "tokio",
"tokio-util", "tokio-util",
"tower-lsp",
"tracing", "tracing",
"twox-hash", "twox-hash",
"typed-arena", "typed-arena",
@ -1258,6 +1258,17 @@ dependencies = [
"zstd", "zstd",
] ]
[[package]]
name = "deno-tower-lsp-macros"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05d59a1cfd445fd86f63616127a434aabca000e03d963b01b03ce813520565b9"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.72",
]
[[package]] [[package]]
name = "deno_ast" name = "deno_ast"
version = "0.41.2" version = "0.41.2"
@ -2060,6 +2071,29 @@ dependencies = [
"webpki-roots", "webpki-roots",
] ]
[[package]]
name = "deno_tower_lsp"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7afb4d257c084fd889e8cf1ba3ad58db0002428c819cc7717815f996f97777a"
dependencies = [
"async-trait",
"auto_impl",
"bytes",
"dashmap",
"deno-tower-lsp-macros",
"futures",
"httparse",
"lsp-types",
"memchr",
"serde",
"serde_json",
"tokio",
"tokio-util",
"tower",
"tracing",
]
[[package]] [[package]]
name = "deno_unsync" name = "deno_unsync"
version = "0.4.1" version = "0.4.1"
@ -2981,6 +3015,15 @@ dependencies = [
"num-traits", "num-traits",
] ]
[[package]]
name = "fluent-uri"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17c704e9dbe1ddd863da1e6ff3567795087b1eb201ce80d8fa81162e1516500d"
dependencies = [
"bitflags 1.3.2",
]
[[package]] [[package]]
name = "fnv" name = "fnv"
version = "1.0.7" version = "1.0.7"
@ -4254,15 +4297,15 @@ dependencies = [
[[package]] [[package]]
name = "lsp-types" name = "lsp-types"
version = "0.94.1" version = "0.97.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c66bfd44a06ae10647fe3f8214762e9369fd4248df1350924b4ef9e770a85ea1" checksum = "53353550a17c04ac46c585feb189c2db82154fc84b79c7a66c96c2c644f66071"
dependencies = [ dependencies = [
"bitflags 1.3.2", "bitflags 1.3.2",
"fluent-uri",
"serde", "serde",
"serde_json", "serde_json",
"serde_repr", "serde_repr",
"url",
] ]
[[package]] [[package]]
@ -7535,40 +7578,6 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c20c8dbed6283a09604c3e69b4b7eeb54e298b8a600d4d5ecb5ad39de609f1d0" checksum = "c20c8dbed6283a09604c3e69b4b7eeb54e298b8a600d4d5ecb5ad39de609f1d0"
[[package]]
name = "tower-lsp"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4ba052b54a6627628d9b3c34c176e7eda8359b7da9acd497b9f20998d118508"
dependencies = [
"async-trait",
"auto_impl",
"bytes",
"dashmap",
"futures",
"httparse",
"lsp-types",
"memchr",
"serde",
"serde_json",
"tokio",
"tokio-util",
"tower",
"tower-lsp-macros",
"tracing",
]
[[package]]
name = "tower-lsp-macros"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84fd902d4e0b9a4b27f2f440108dc034e1758628a9b702f8ec61ad66355422fa"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.72",
]
[[package]] [[package]]
name = "tower-service" name = "tower-service"
version = "0.3.2" version = "0.3.2"

View file

@ -133,7 +133,7 @@ lazy-regex = "3"
libc = "0.2.126" libc = "0.2.126"
libz-sys = { version = "1.1", default-features = false } libz-sys = { version = "1.1", default-features = false }
log = "0.4.20" log = "0.4.20"
lsp-types = "=0.94.1" # used by tower-lsp and "proposed" feature is unstable in patch releases lsp-types = "=0.97.0" # used by tower-lsp and "proposed" feature is unstable in patch releases
memmem = "0.1.1" memmem = "0.1.1"
monch = "=0.5.0" monch = "=0.5.0"
notify = "=6.1.1" notify = "=6.1.1"
@ -184,7 +184,7 @@ tokio-socks = "0.5.1"
tokio-util = "0.7.4" tokio-util = "0.7.4"
tower = { version = "0.4.13", default-features = false, features = ["util"] } tower = { version = "0.4.13", default-features = false, features = ["util"] }
tower-http = { version = "0.5.2", features = ["decompression-br", "decompression-gzip"] } tower-http = { version = "0.5.2", features = ["decompression-br", "decompression-gzip"] }
tower-lsp = { version = "=0.20.0", features = ["proposed"] } tower-lsp = { package = "deno_tower_lsp", version = "0.1.0", features = ["proposed"] }
tower-service = "0.3.2" tower-service = "0.3.2"
twox-hash = "=1.6.3" twox-hash = "=1.6.3"
# Upgrading past 2.4.1 may cause WPT failures # Upgrading past 2.4.1 may cause WPT failures

View file

@ -4,9 +4,10 @@ use deno_core::serde::Deserialize;
use deno_core::serde_json; use deno_core::serde_json;
use deno_core::serde_json::json; use deno_core::serde_json::json;
use deno_core::serde_json::Value; use deno_core::serde_json::Value;
use deno_core::url::Url; use lsp_types::Uri;
use std::collections::HashMap; use std::collections::HashMap;
use std::path::Path; use std::path::Path;
use std::str::FromStr;
use std::time::Duration; use std::time::Duration;
use test_util::lsp::LspClientBuilder; use test_util::lsp::LspClientBuilder;
use test_util::PathRef; use test_util::PathRef;
@ -91,7 +92,7 @@ fn bench_deco_apps_edits(deno_exe: &Path) -> Duration {
.build(); .build();
client.initialize(|c| { client.initialize(|c| {
c.set_workspace_folders(vec![lsp_types::WorkspaceFolder { c.set_workspace_folders(vec![lsp_types::WorkspaceFolder {
uri: Url::from_file_path(&apps).unwrap(), uri: apps.uri_dir(),
name: "apps".to_string(), name: "apps".to_string(),
}]); }]);
c.set_deno_enable(true); c.set_deno_enable(true);
@ -283,7 +284,7 @@ fn bench_find_replace(deno_exe: &Path) -> Duration {
"textDocument/didChange", "textDocument/didChange",
lsp::DidChangeTextDocumentParams { lsp::DidChangeTextDocumentParams {
text_document: lsp::VersionedTextDocumentIdentifier { text_document: lsp::VersionedTextDocumentIdentifier {
uri: Url::parse(&file_name).unwrap(), uri: Uri::from_str(&file_name).unwrap(),
version: 2, version: 2,
}, },
content_changes: vec![lsp::TextDocumentContentChangeEvent { content_changes: vec![lsp::TextDocumentContentChangeEvent {
@ -310,7 +311,7 @@ fn bench_find_replace(deno_exe: &Path) -> Duration {
"textDocument/formatting", "textDocument/formatting",
lsp::DocumentFormattingParams { lsp::DocumentFormattingParams {
text_document: lsp::TextDocumentIdentifier { text_document: lsp::TextDocumentIdentifier {
uri: Url::parse(&file_name).unwrap(), uri: Uri::from_str(&file_name).unwrap(),
}, },
options: lsp::FormattingOptions { options: lsp::FormattingOptions {
tab_size: 2, tab_size: 2,

View file

@ -4,3 +4,6 @@ disallowed-methods = [
disallowed-types = [ disallowed-types = [
{ path = "reqwest::Client", reason = "use crate::http_util::HttpClient instead" }, { path = "reqwest::Client", reason = "use crate::http_util::HttpClient instead" },
] ]
ignore-interior-mutability = [
"lsp_types::Uri",
]

View file

@ -6,6 +6,7 @@ use super::documents::Documents;
use super::language_server; use super::language_server;
use super::resolver::LspResolver; use super::resolver::LspResolver;
use super::tsc; use super::tsc;
use super::urls::url_to_uri;
use crate::args::jsr_url; use crate::args::jsr_url;
use crate::tools::lint::CliLinter; use crate::tools::lint::CliLinter;
@ -750,10 +751,11 @@ impl CodeActionCollection {
.as_ref() .as_ref()
.and_then(|d| serde_json::from_value::<Vec<DataQuickFix>>(d.clone()).ok()) .and_then(|d| serde_json::from_value::<Vec<DataQuickFix>>(d.clone()).ok())
{ {
let uri = url_to_uri(specifier);
for quick_fix in data_quick_fixes { for quick_fix in data_quick_fixes {
let mut changes = HashMap::new(); let mut changes = HashMap::new();
changes.insert( changes.insert(
specifier.clone(), uri.clone(),
quick_fix quick_fix
.changes .changes
.into_iter() .into_iter()
@ -795,6 +797,7 @@ impl CodeActionCollection {
maybe_text_info: Option<&SourceTextInfo>, maybe_text_info: Option<&SourceTextInfo>,
maybe_parsed_source: Option<&deno_ast::ParsedSource>, maybe_parsed_source: Option<&deno_ast::ParsedSource>,
) -> Result<(), AnyError> { ) -> Result<(), AnyError> {
let uri = url_to_uri(specifier);
let code = diagnostic let code = diagnostic
.code .code
.as_ref() .as_ref()
@ -811,7 +814,7 @@ impl CodeActionCollection {
let mut changes = HashMap::new(); let mut changes = HashMap::new();
changes.insert( changes.insert(
specifier.clone(), uri.clone(),
vec![lsp::TextEdit { vec![lsp::TextEdit {
new_text: prepend_whitespace( new_text: prepend_whitespace(
format!("// deno-lint-ignore {code}\n"), format!("// deno-lint-ignore {code}\n"),
@ -892,7 +895,7 @@ impl CodeActionCollection {
} }
let mut changes = HashMap::new(); let mut changes = HashMap::new();
changes.insert(specifier.clone(), vec![lsp::TextEdit { new_text, range }]); changes.insert(uri.clone(), vec![lsp::TextEdit { new_text, range }]);
let ignore_file_action = lsp::CodeAction { let ignore_file_action = lsp::CodeAction {
title: format!("Disable {code} for the entire file"), title: format!("Disable {code} for the entire file"),
kind: Some(lsp::CodeActionKind::QUICKFIX), kind: Some(lsp::CodeActionKind::QUICKFIX),
@ -913,7 +916,7 @@ impl CodeActionCollection {
let mut changes = HashMap::new(); let mut changes = HashMap::new();
changes.insert( changes.insert(
specifier.clone(), uri,
vec![lsp::TextEdit { vec![lsp::TextEdit {
new_text: "// deno-lint-ignore-file\n".to_string(), new_text: "// deno-lint-ignore-file\n".to_string(),
range: lsp::Range { range: lsp::Range {

View file

@ -154,5 +154,7 @@ pub fn server_capabilities(
// TODO(nayeemrmn): Support pull-based diagnostics. // TODO(nayeemrmn): Support pull-based diagnostics.
diagnostic_provider: None, diagnostic_provider: None,
inline_value_provider: None, inline_value_provider: None,
inline_completion_provider: None,
notebook_document_sync: None,
} }
} }

View file

@ -58,7 +58,7 @@ impl Client {
) { ) {
self self
.0 .0
.publish_diagnostics(uri.into_url(), diags, version) .publish_diagnostics(uri.to_uri(), diags, version)
.await; .await;
} }
@ -149,7 +149,7 @@ impl OutsideLockClient {
pub async fn workspace_configuration( pub async fn workspace_configuration(
&self, &self,
scopes: Vec<Option<lsp::Url>>, scopes: Vec<Option<lsp::Uri>>,
) -> Result<Vec<WorkspaceSettings>, AnyError> { ) -> Result<Vec<WorkspaceSettings>, AnyError> {
self.0.workspace_configuration(scopes).await self.0.workspace_configuration(scopes).await
} }
@ -159,7 +159,7 @@ impl OutsideLockClient {
trait ClientTrait: Send + Sync { trait ClientTrait: Send + Sync {
async fn publish_diagnostics( async fn publish_diagnostics(
&self, &self,
uri: lsp::Url, uri: lsp::Uri,
diagnostics: Vec<lsp::Diagnostic>, diagnostics: Vec<lsp::Diagnostic>,
version: Option<i32>, version: Option<i32>,
); );
@ -182,7 +182,7 @@ trait ClientTrait: Send + Sync {
); );
async fn workspace_configuration( async fn workspace_configuration(
&self, &self,
scopes: Vec<Option<lsp::Url>>, scopes: Vec<Option<lsp::Uri>>,
) -> Result<Vec<WorkspaceSettings>, AnyError>; ) -> Result<Vec<WorkspaceSettings>, AnyError>;
async fn show_message(&self, message_type: lsp::MessageType, text: String); async fn show_message(&self, message_type: lsp::MessageType, text: String);
async fn register_capability( async fn register_capability(
@ -198,7 +198,7 @@ struct TowerClient(tower_lsp::Client);
impl ClientTrait for TowerClient { impl ClientTrait for TowerClient {
async fn publish_diagnostics( async fn publish_diagnostics(
&self, &self,
uri: lsp::Url, uri: lsp::Uri,
diagnostics: Vec<lsp::Diagnostic>, diagnostics: Vec<lsp::Diagnostic>,
version: Option<i32>, version: Option<i32>,
) { ) {
@ -276,7 +276,7 @@ impl ClientTrait for TowerClient {
async fn workspace_configuration( async fn workspace_configuration(
&self, &self,
scopes: Vec<Option<lsp::Url>>, scopes: Vec<Option<lsp::Uri>>,
) -> Result<Vec<WorkspaceSettings>, AnyError> { ) -> Result<Vec<WorkspaceSettings>, AnyError> {
let config_response = self let config_response = self
.0 .0
@ -349,7 +349,7 @@ struct ReplClient;
impl ClientTrait for ReplClient { impl ClientTrait for ReplClient {
async fn publish_diagnostics( async fn publish_diagnostics(
&self, &self,
_uri: lsp::Url, _uri: lsp::Uri,
_diagnostics: Vec<lsp::Diagnostic>, _diagnostics: Vec<lsp::Diagnostic>,
_version: Option<i32>, _version: Option<i32>,
) { ) {
@ -383,7 +383,7 @@ impl ClientTrait for ReplClient {
async fn workspace_configuration( async fn workspace_configuration(
&self, &self,
scopes: Vec<Option<lsp::Url>>, scopes: Vec<Option<lsp::Uri>>,
) -> Result<Vec<WorkspaceSettings>, AnyError> { ) -> Result<Vec<WorkspaceSettings>, AnyError> {
Ok(vec![get_repl_workspace_settings(); scopes.len()]) Ok(vec![get_repl_workspace_settings(); scopes.len()])
} }

View file

@ -838,7 +838,7 @@ mod tests {
fs_sources: &[(&str, &str)], fs_sources: &[(&str, &str)],
) -> Documents { ) -> Documents {
let temp_dir = TempDir::new(); let temp_dir = TempDir::new();
let cache = LspCache::new(Some(temp_dir.uri().join(".deno_dir").unwrap())); let cache = LspCache::new(Some(temp_dir.url().join(".deno_dir").unwrap()));
let mut documents = Documents::default(); let mut documents = Documents::default();
documents.update_config( documents.update_config(
&Default::default(), &Default::default(),
@ -859,7 +859,7 @@ mod tests {
.set(&specifier, HashMap::default(), source.as_bytes()) .set(&specifier, HashMap::default(), source.as_bytes())
.expect("could not cache file"); .expect("could not cache file");
let document = documents let document = documents
.get_or_load(&specifier, Some(&temp_dir.uri().join("$").unwrap())); .get_or_load(&specifier, Some(&temp_dir.url().join("$").unwrap()));
assert!(document.is_some(), "source could not be setup"); assert!(document.is_some(), "source could not be setup");
} }
documents documents

View file

@ -30,6 +30,7 @@ use deno_core::serde::Serialize;
use deno_core::serde_json; use deno_core::serde_json;
use deno_core::serde_json::json; use deno_core::serde_json::json;
use deno_core::serde_json::Value; use deno_core::serde_json::Value;
use deno_core::url::Url;
use deno_core::ModuleSpecifier; use deno_core::ModuleSpecifier;
use deno_lint::linter::LintConfig as DenoLintConfig; use deno_lint::linter::LintConfig as DenoLintConfig;
use deno_npm::npm_rc::ResolvedNpmRc; use deno_npm::npm_rc::ResolvedNpmRc;
@ -38,7 +39,6 @@ use deno_runtime::deno_node::PackageJson;
use deno_runtime::deno_permissions::PermissionsContainer; use deno_runtime::deno_permissions::PermissionsContainer;
use deno_runtime::fs_util::specifier_to_file_path; use deno_runtime::fs_util::specifier_to_file_path;
use indexmap::IndexSet; use indexmap::IndexSet;
use lsp::Url;
use lsp_types::ClientCapabilities; use lsp_types::ClientCapabilities;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::collections::HashMap; use std::collections::HashMap;
@ -844,14 +844,17 @@ pub struct Config {
impl Config { impl Config {
#[cfg(test)] #[cfg(test)]
pub fn new_with_roots(root_uris: impl IntoIterator<Item = Url>) -> Self { pub fn new_with_roots(root_urls: impl IntoIterator<Item = Url>) -> Self {
use super::urls::url_to_uri;
let mut config = Self::default(); let mut config = Self::default();
let mut folders = vec![]; let mut folders = vec![];
for root_uri in root_uris { for root_url in root_urls {
let name = root_uri.path_segments().and_then(|s| s.last()); let root_uri = url_to_uri(&root_url);
let name = root_url.path_segments().and_then(|s| s.last());
let name = name.unwrap_or_default().to_string(); let name = name.unwrap_or_default().to_string();
folders.push(( folders.push((
root_uri.clone(), root_url,
lsp::WorkspaceFolder { lsp::WorkspaceFolder {
uri: root_uri, uri: root_uri,
name, name,

View file

@ -12,6 +12,7 @@ use super::language_server::StateSnapshot;
use super::performance::Performance; use super::performance::Performance;
use super::tsc; use super::tsc;
use super::tsc::TsServer; use super::tsc::TsServer;
use super::urls::url_to_uri;
use super::urls::LspClientUrl; use super::urls::LspClientUrl;
use super::urls::LspUrlMap; use super::urls::LspUrlMap;
@ -37,6 +38,7 @@ use deno_core::serde_json::json;
use deno_core::unsync::spawn; use deno_core::unsync::spawn;
use deno_core::unsync::spawn_blocking; use deno_core::unsync::spawn_blocking;
use deno_core::unsync::JoinHandle; use deno_core::unsync::JoinHandle;
use deno_core::url::Url;
use deno_core::ModuleSpecifier; use deno_core::ModuleSpecifier;
use deno_graph::source::ResolutionMode; use deno_graph::source::ResolutionMode;
use deno_graph::source::ResolveError; use deno_graph::source::ResolveError;
@ -52,9 +54,11 @@ use deno_semver::package::PackageReq;
use import_map::ImportMap; use import_map::ImportMap;
use import_map::ImportMapError; use import_map::ImportMapError;
use log::error; use log::error;
use lsp_types::Uri;
use std::collections::HashMap; use std::collections::HashMap;
use std::collections::HashSet; use std::collections::HashSet;
use std::path::PathBuf; use std::path::PathBuf;
use std::str::FromStr;
use std::sync::atomic::AtomicUsize; use std::sync::atomic::AtomicUsize;
use std::sync::Arc; use std::sync::Arc;
use std::thread; use std::thread;
@ -737,7 +741,7 @@ fn to_lsp_related_information(
if let (Some(file_name), Some(start), Some(end)) = if let (Some(file_name), Some(start), Some(end)) =
(&ri.file_name, &ri.start, &ri.end) (&ri.file_name, &ri.start, &ri.end)
{ {
let uri = lsp::Url::parse(file_name).unwrap(); let uri = Uri::from_str(file_name).unwrap();
Some(lsp::DiagnosticRelatedInformation { Some(lsp::DiagnosticRelatedInformation {
location: lsp::Location { location: lsp::Location {
uri, uri,
@ -1070,7 +1074,7 @@ impl DenoDiagnostic {
diagnostics: Some(vec![diagnostic.clone()]), diagnostics: Some(vec![diagnostic.clone()]),
edit: Some(lsp::WorkspaceEdit { edit: Some(lsp::WorkspaceEdit {
changes: Some(HashMap::from([( changes: Some(HashMap::from([(
specifier.clone(), url_to_uri(specifier),
vec![lsp::TextEdit { vec![lsp::TextEdit {
new_text: format!("\"{to}\""), new_text: format!("\"{to}\""),
range: diagnostic.range, range: diagnostic.range,
@ -1087,7 +1091,7 @@ impl DenoDiagnostic {
diagnostics: Some(vec![diagnostic.clone()]), diagnostics: Some(vec![diagnostic.clone()]),
edit: Some(lsp::WorkspaceEdit { edit: Some(lsp::WorkspaceEdit {
changes: Some(HashMap::from([( changes: Some(HashMap::from([(
specifier.clone(), url_to_uri(specifier),
vec![lsp::TextEdit { vec![lsp::TextEdit {
new_text: " with { type: \"json\" }".to_string(), new_text: " with { type: \"json\" }".to_string(),
range: lsp::Range { range: lsp::Range {
@ -1138,7 +1142,7 @@ impl DenoDiagnostic {
diagnostics: Some(vec![diagnostic.clone()]), diagnostics: Some(vec![diagnostic.clone()]),
edit: Some(lsp::WorkspaceEdit { edit: Some(lsp::WorkspaceEdit {
changes: Some(HashMap::from([( changes: Some(HashMap::from([(
specifier.clone(), url_to_uri(specifier),
vec![lsp::TextEdit { vec![lsp::TextEdit {
new_text: format!( new_text: format!(
"\"{}\"", "\"{}\"",
@ -1164,7 +1168,7 @@ impl DenoDiagnostic {
diagnostics: Some(vec![diagnostic.clone()]), diagnostics: Some(vec![diagnostic.clone()]),
edit: Some(lsp::WorkspaceEdit { edit: Some(lsp::WorkspaceEdit {
changes: Some(HashMap::from([( changes: Some(HashMap::from([(
specifier.clone(), url_to_uri(specifier),
vec![lsp::TextEdit { vec![lsp::TextEdit {
new_text: format!( new_text: format!(
"\"{}\"", "\"{}\"",
@ -1190,7 +1194,7 @@ impl DenoDiagnostic {
diagnostics: Some(vec![diagnostic.clone()]), diagnostics: Some(vec![diagnostic.clone()]),
edit: Some(lsp::WorkspaceEdit { edit: Some(lsp::WorkspaceEdit {
changes: Some(HashMap::from([( changes: Some(HashMap::from([(
specifier.clone(), url_to_uri(specifier),
vec![lsp::TextEdit { vec![lsp::TextEdit {
new_text: format!("\"node:{}\"", data.specifier), new_text: format!("\"node:{}\"", data.specifier),
range: diagnostic.range, range: diagnostic.range,
@ -1308,10 +1312,7 @@ impl DenoDiagnostic {
} }
} }
fn specifier_text_for_redirected( fn specifier_text_for_redirected(redirect: &Url, referrer: &Url) -> String {
redirect: &lsp::Url,
referrer: &lsp::Url,
) -> String {
if redirect.scheme() == "file" && referrer.scheme() == "file" { if redirect.scheme() == "file" && referrer.scheme() == "file" {
// use a relative specifier when it's going to a file url // use a relative specifier when it's going to a file url
relative_specifier(redirect, referrer) relative_specifier(redirect, referrer)
@ -1320,7 +1321,7 @@ fn specifier_text_for_redirected(
} }
} }
fn relative_specifier(specifier: &lsp::Url, referrer: &lsp::Url) -> String { fn relative_specifier(specifier: &Url, referrer: &Url) -> String {
match referrer.make_relative(specifier) { match referrer.make_relative(specifier) {
Some(relative) => { Some(relative) => {
if relative.starts_with('.') { if relative.starts_with('.') {
@ -1640,7 +1641,8 @@ mod tests {
use test_util::TempDir; use test_util::TempDir;
fn mock_config() -> Config { fn mock_config() -> Config {
let root_uri = resolve_url("file:///").unwrap(); let root_url = resolve_url("file:///").unwrap();
let root_uri = url_to_uri(&root_url);
Config { Config {
settings: Arc::new(Settings { settings: Arc::new(Settings {
unscoped: Arc::new(WorkspaceSettings { unscoped: Arc::new(WorkspaceSettings {
@ -1651,7 +1653,7 @@ mod tests {
..Default::default() ..Default::default()
}), }),
workspace_folders: Arc::new(vec![( workspace_folders: Arc::new(vec![(
root_uri.clone(), root_url,
lsp::WorkspaceFolder { lsp::WorkspaceFolder {
uri: root_uri, uri: root_uri,
name: "".to_string(), name: "".to_string(),
@ -1666,7 +1668,7 @@ mod tests {
maybe_import_map: Option<(&str, &str)>, maybe_import_map: Option<(&str, &str)>,
) -> (TempDir, StateSnapshot) { ) -> (TempDir, StateSnapshot) {
let temp_dir = TempDir::new(); let temp_dir = TempDir::new();
let root_uri = temp_dir.uri(); let root_uri = temp_dir.url();
let cache = LspCache::new(Some(root_uri.join(".deno_dir").unwrap())); let cache = LspCache::new(Some(root_uri.join(".deno_dir").unwrap()));
let mut config = Config::new_with_roots([root_uri.clone()]); let mut config = Config::new_with_roots([root_uri.clone()]);
if let Some((relative_path, json_string)) = maybe_import_map { if let Some((relative_path, json_string)) = maybe_import_map {
@ -1833,7 +1835,7 @@ let c: number = "a";
assert_eq!(actual.len(), 2); assert_eq!(actual.len(), 2);
for record in actual { for record in actual {
let relative_specifier = let relative_specifier =
temp_dir.uri().make_relative(&record.specifier).unwrap(); temp_dir.url().make_relative(&record.specifier).unwrap();
match relative_specifier.as_str() { match relative_specifier.as_str() {
"std/assert/mod.ts" => { "std/assert/mod.ts" => {
assert_eq!(json!(record.versioned.diagnostics), json!([])) assert_eq!(json!(record.versioned.diagnostics), json!([]))
@ -2052,7 +2054,7 @@ let c: number = "a";
"source": "deno", "source": "deno",
"message": format!( "message": format!(
"Unable to load a local module: {}🦕.ts\nPlease check the file path.", "Unable to load a local module: {}🦕.ts\nPlease check the file path.",
temp_dir.uri(), temp_dir.url(),
), ),
} }
]) ])

View file

@ -1607,7 +1607,7 @@ mod tests {
async fn setup() -> (Documents, LspCache, TempDir) { async fn setup() -> (Documents, LspCache, TempDir) {
let temp_dir = TempDir::new(); let temp_dir = TempDir::new();
temp_dir.create_dir_all(".deno_dir"); temp_dir.create_dir_all(".deno_dir");
let cache = LspCache::new(Some(temp_dir.uri().join(".deno_dir").unwrap())); let cache = LspCache::new(Some(temp_dir.url().join(".deno_dir").unwrap()));
let config = Config::default(); let config = Config::default();
let resolver = let resolver =
Arc::new(LspResolver::from_config(&config, &cache, None).await); Arc::new(LspResolver::from_config(&config, &cache, None).await);
@ -1690,7 +1690,7 @@ console.log(b, "hello deno");
// but we'll guard against it anyway // but we'll guard against it anyway
let (mut documents, _, temp_dir) = setup().await; let (mut documents, _, temp_dir) = setup().await;
let file_path = temp_dir.path().join("file.ts"); let file_path = temp_dir.path().join("file.ts");
let file_specifier = temp_dir.uri().join("file.ts").unwrap(); let file_specifier = temp_dir.url().join("file.ts").unwrap();
file_path.write(""); file_path.write("");
// open the document // open the document
@ -1718,18 +1718,18 @@ console.log(b, "hello deno");
let (mut documents, cache, temp_dir) = setup().await; let (mut documents, cache, temp_dir) = setup().await;
let file1_path = temp_dir.path().join("file1.ts"); let file1_path = temp_dir.path().join("file1.ts");
let file1_specifier = temp_dir.uri().join("file1.ts").unwrap(); let file1_specifier = temp_dir.url().join("file1.ts").unwrap();
fs::write(&file1_path, "").unwrap(); fs::write(&file1_path, "").unwrap();
let file2_path = temp_dir.path().join("file2.ts"); let file2_path = temp_dir.path().join("file2.ts");
let file2_specifier = temp_dir.uri().join("file2.ts").unwrap(); let file2_specifier = temp_dir.url().join("file2.ts").unwrap();
fs::write(&file2_path, "").unwrap(); fs::write(&file2_path, "").unwrap();
let file3_path = temp_dir.path().join("file3.ts"); let file3_path = temp_dir.path().join("file3.ts");
let file3_specifier = temp_dir.uri().join("file3.ts").unwrap(); let file3_specifier = temp_dir.url().join("file3.ts").unwrap();
fs::write(&file3_path, "").unwrap(); fs::write(&file3_path, "").unwrap();
let mut config = Config::new_with_roots([temp_dir.uri()]); let mut config = Config::new_with_roots([temp_dir.url()]);
let workspace_settings = let workspace_settings =
serde_json::from_str(r#"{ "enable": true }"#).unwrap(); serde_json::from_str(r#"{ "enable": true }"#).unwrap();
config.set_workspace_settings(workspace_settings, vec![]); config.set_workspace_settings(workspace_settings, vec![]);

View file

@ -12,6 +12,7 @@ use deno_core::serde_json::json;
use deno_core::serde_json::Value; use deno_core::serde_json::Value;
use deno_core::unsync::spawn; use deno_core::unsync::spawn;
use deno_core::url; use deno_core::url;
use deno_core::url::Url;
use deno_core::ModuleSpecifier; use deno_core::ModuleSpecifier;
use deno_graph::GraphKind; use deno_graph::GraphKind;
use deno_graph::Resolution; use deno_graph::Resolution;
@ -85,6 +86,8 @@ use super::tsc::ChangeKind;
use super::tsc::GetCompletionDetailsArgs; use super::tsc::GetCompletionDetailsArgs;
use super::tsc::TsServer; use super::tsc::TsServer;
use super::urls; use super::urls;
use super::urls::uri_to_url;
use super::urls::url_to_uri;
use crate::args::create_default_npmrc; use crate::args::create_default_npmrc;
use crate::args::get_root_cert_store; use crate::args::get_root_cert_store;
use crate::args::has_flag_env_var; use crate::args::has_flag_env_var;
@ -728,14 +731,17 @@ impl Inner {
} }
// rootUri is deprecated by the LSP spec. If it's specified, merge it into // rootUri is deprecated by the LSP spec. If it's specified, merge it into
// workspace_folders. // workspace_folders.
#[allow(deprecated)]
if let Some(root_uri) = params.root_uri { if let Some(root_uri) = params.root_uri {
if !workspace_folders.iter().any(|(_, f)| f.uri == root_uri) { if !workspace_folders.iter().any(|(_, f)| f.uri == root_uri) {
let name = root_uri.path_segments().and_then(|s| s.last()); let root_url =
self.url_map.normalize_url(&root_uri, LspUrlKind::Folder);
let name = root_url.path_segments().and_then(|s| s.last());
let name = name.unwrap_or_default().to_string(); let name = name.unwrap_or_default().to_string();
workspace_folders.insert( workspace_folders.insert(
0, 0,
( (
self.url_map.normalize_url(&root_uri, LspUrlKind::Folder), root_url,
WorkspaceFolder { WorkspaceFolder {
uri: root_uri, uri: root_uri,
name, name,
@ -1008,7 +1014,10 @@ impl Inner {
async fn did_open(&mut self, params: DidOpenTextDocumentParams) { async fn did_open(&mut self, params: DidOpenTextDocumentParams) {
let mark = self.performance.mark_with_args("lsp.did_open", &params); let mark = self.performance.mark_with_args("lsp.did_open", &params);
if params.text_document.uri.scheme() == "deno" { let Some(scheme) = params.text_document.uri.scheme() else {
return;
};
if scheme.as_str() == "deno" {
// we can ignore virtual text documents opening, as they don't need to // we can ignore virtual text documents opening, as they don't need to
// be tracked in memory, as they are static assets that won't change // be tracked in memory, as they are static assets that won't change
// already managed by the language service // already managed by the language service
@ -1027,13 +1036,11 @@ impl Inner {
lsp_warn!( lsp_warn!(
"Unsupported language id \"{}\" received for document \"{}\".", "Unsupported language id \"{}\" received for document \"{}\".",
params.text_document.language_id, params.text_document.language_id,
params.text_document.uri params.text_document.uri.as_str()
); );
} }
let file_referrer = (self let file_referrer = Some(uri_to_url(&params.text_document.uri))
.documents .filter(|s| self.documents.is_valid_file_referrer(s));
.is_valid_file_referrer(&params.text_document.uri))
.then(|| params.text_document.uri.clone());
let specifier = self let specifier = self
.url_map .url_map
.normalize_url(&params.text_document.uri, LspUrlKind::File); .normalize_url(&params.text_document.uri, LspUrlKind::File);
@ -1130,8 +1137,10 @@ impl Inner {
async fn did_close(&mut self, params: DidCloseTextDocumentParams) { async fn did_close(&mut self, params: DidCloseTextDocumentParams) {
let mark = self.performance.mark_with_args("lsp.did_close", &params); let mark = self.performance.mark_with_args("lsp.did_close", &params);
self.diagnostics_state.clear(&params.text_document.uri); let Some(scheme) = params.text_document.uri.scheme() else {
if params.text_document.uri.scheme() == "deno" { return;
};
if scheme.as_str() == "deno" {
// we can ignore virtual text documents closing, as they don't need to // we can ignore virtual text documents closing, as they don't need to
// be tracked in memory, as they are static assets that won't change // be tracked in memory, as they are static assets that won't change
// already managed by the language service // already managed by the language service
@ -1140,6 +1149,7 @@ impl Inner {
let specifier = self let specifier = self
.url_map .url_map
.normalize_url(&params.text_document.uri, LspUrlKind::File); .normalize_url(&params.text_document.uri, LspUrlKind::File);
self.diagnostics_state.clear(&specifier);
if self.is_diagnosable(&specifier) { if self.is_diagnosable(&specifier) {
self.refresh_npm_specifiers().await; self.refresh_npm_specifiers().await;
self.diagnostics_server.invalidate(&[specifier.clone()]); self.diagnostics_server.invalidate(&[specifier.clone()]);
@ -1211,7 +1221,7 @@ impl Inner {
_ => return None, _ => return None,
}; };
Some(lsp_custom::DenoConfigurationChangeEvent { Some(lsp_custom::DenoConfigurationChangeEvent {
scope_uri: t.0.clone(), scope_uri: url_to_uri(t.0),
file_uri: e.uri.clone(), file_uri: e.uri.clone(),
typ: lsp_custom::DenoConfigurationChangeType::from_file_change_type( typ: lsp_custom::DenoConfigurationChangeType::from_file_change_type(
e.typ, e.typ,
@ -1246,7 +1256,7 @@ impl Inner {
_ => return None, _ => return None,
}; };
Some(lsp_custom::DenoConfigurationChangeEvent { Some(lsp_custom::DenoConfigurationChangeEvent {
scope_uri: t.0.clone(), scope_uri: url_to_uri(t.0),
file_uri: e.uri.clone(), file_uri: e.uri.clone(),
typ: lsp_custom::DenoConfigurationChangeType::from_file_change_type( typ: lsp_custom::DenoConfigurationChangeType::from_file_change_type(
e.typ, e.typ,
@ -1312,10 +1322,8 @@ impl Inner {
&self, &self,
params: DocumentFormattingParams, params: DocumentFormattingParams,
) -> LspResult<Option<Vec<TextEdit>>> { ) -> LspResult<Option<Vec<TextEdit>>> {
let file_referrer = (self let file_referrer = Some(uri_to_url(&params.text_document.uri))
.documents .filter(|s| self.documents.is_valid_file_referrer(s));
.is_valid_file_referrer(&params.text_document.uri))
.then(|| params.text_document.uri.clone());
let mut specifier = self let mut specifier = self
.url_map .url_map
.normalize_url(&params.text_document.uri, LspUrlKind::File); .normalize_url(&params.text_document.uri, LspUrlKind::File);
@ -1339,9 +1347,9 @@ impl Inner {
// counterparts, but for formatting we want to favour the file URL. // counterparts, but for formatting we want to favour the file URL.
// TODO(nayeemrmn): Implement `Document::file_resource_path()` or similar. // TODO(nayeemrmn): Implement `Document::file_resource_path()` or similar.
if specifier.scheme() != "file" if specifier.scheme() != "file"
&& params.text_document.uri.scheme() == "file" && params.text_document.uri.scheme().map(|s| s.as_str()) == Some("file")
{ {
specifier = params.text_document.uri.clone(); specifier = uri_to_url(&params.text_document.uri);
} }
let file_path = specifier_to_file_path(&specifier).map_err(|err| { let file_path = specifier_to_file_path(&specifier).map_err(|err| {
error!("{:#}", err); error!("{:#}", err);
@ -2870,7 +2878,7 @@ impl Inner {
let mut changes = vec![]; let mut changes = vec![];
for rename in params.files { for rename in params.files {
let old_specifier = self.url_map.normalize_url( let old_specifier = self.url_map.normalize_url(
&resolve_url(&rename.old_uri).unwrap(), &url_to_uri(&resolve_url(&rename.old_uri).unwrap()),
LspUrlKind::File, LspUrlKind::File,
); );
let options = self let options = self
@ -2896,7 +2904,7 @@ impl Inner {
self.snapshot(), self.snapshot(),
old_specifier, old_specifier,
self.url_map.normalize_url( self.url_map.normalize_url(
&resolve_url(&rename.new_uri).unwrap(), &url_to_uri(&resolve_url(&rename.new_uri).unwrap()),
LspUrlKind::File, LspUrlKind::File,
), ),
format_code_settings, format_code_settings,
@ -3494,19 +3502,20 @@ impl Inner {
} }
let mut config_events = vec![]; let mut config_events = vec![];
for (scope_uri, config_data) in self.config.tree.data_by_scope().iter() { for (scope_url, config_data) in self.config.tree.data_by_scope().iter() {
let scope_uri = url_to_uri(scope_url);
if let Some(config_file) = config_data.maybe_deno_json() { if let Some(config_file) = config_data.maybe_deno_json() {
config_events.push(lsp_custom::DenoConfigurationChangeEvent { config_events.push(lsp_custom::DenoConfigurationChangeEvent {
scope_uri: scope_uri.clone(), scope_uri: scope_uri.clone(),
file_uri: config_file.specifier.clone(), file_uri: url_to_uri(&config_file.specifier),
typ: lsp_custom::DenoConfigurationChangeType::Added, typ: lsp_custom::DenoConfigurationChangeType::Added,
configuration_type: lsp_custom::DenoConfigurationType::DenoJson, configuration_type: lsp_custom::DenoConfigurationType::DenoJson,
}); });
} }
if let Some(package_json) = config_data.maybe_pkg_json() { if let Some(package_json) = config_data.maybe_pkg_json() {
config_events.push(lsp_custom::DenoConfigurationChangeEvent { config_events.push(lsp_custom::DenoConfigurationChangeEvent {
scope_uri: scope_uri.clone(), scope_uri,
file_uri: package_json.specifier(), file_uri: url_to_uri(&package_json.specifier()),
typ: lsp_custom::DenoConfigurationChangeType::Added, typ: lsp_custom::DenoConfigurationChangeType::Added,
configuration_type: lsp_custom::DenoConfigurationType::PackageJson, configuration_type: lsp_custom::DenoConfigurationType::PackageJson,
}); });
@ -3715,7 +3724,7 @@ impl Inner {
result.push(TaskDefinition { result.push(TaskDefinition {
name: name.clone(), name: name.clone(),
command: command.to_string(), command: command.to_string(),
source_uri: config_file.specifier.clone(), source_uri: url_to_uri(&config_file.specifier),
}); });
} }
}; };
@ -3726,7 +3735,7 @@ impl Inner {
result.push(TaskDefinition { result.push(TaskDefinition {
name: name.clone(), name: name.clone(),
command: command.clone(), command: command.clone(),
source_uri: package_json.specifier(), source_uri: url_to_uri(&package_json.specifier()),
}); });
} }
} }
@ -3956,11 +3965,11 @@ mod tests {
temp_dir.write("root4_parent/root4/main.ts", ""); // yes, enabled temp_dir.write("root4_parent/root4/main.ts", ""); // yes, enabled
let mut config = Config::new_with_roots(vec![ let mut config = Config::new_with_roots(vec![
temp_dir.uri().join("root1/").unwrap(), temp_dir.url().join("root1/").unwrap(),
temp_dir.uri().join("root2/").unwrap(), temp_dir.url().join("root2/").unwrap(),
temp_dir.uri().join("root2/root2.1/").unwrap(), temp_dir.url().join("root2/root2.1/").unwrap(),
temp_dir.uri().join("root3/").unwrap(), temp_dir.url().join("root3/").unwrap(),
temp_dir.uri().join("root4_parent/root4/").unwrap(), temp_dir.url().join("root4_parent/root4/").unwrap(),
]); ]);
config.set_client_capabilities(ClientCapabilities { config.set_client_capabilities(ClientCapabilities {
workspace: Some(Default::default()), workspace: Some(Default::default()),
@ -3970,14 +3979,14 @@ mod tests {
Default::default(), Default::default(),
vec![ vec![
( (
temp_dir.uri().join("root1/").unwrap(), temp_dir.url().join("root1/").unwrap(),
WorkspaceSettings { WorkspaceSettings {
enable: Some(true), enable: Some(true),
..Default::default() ..Default::default()
}, },
), ),
( (
temp_dir.uri().join("root2/").unwrap(), temp_dir.url().join("root2/").unwrap(),
WorkspaceSettings { WorkspaceSettings {
enable: Some(true), enable: Some(true),
enable_paths: Some(vec![ enable_paths: Some(vec![
@ -3989,21 +3998,21 @@ mod tests {
}, },
), ),
( (
temp_dir.uri().join("root2/root2.1/").unwrap(), temp_dir.url().join("root2/root2.1/").unwrap(),
WorkspaceSettings { WorkspaceSettings {
enable: Some(true), enable: Some(true),
..Default::default() ..Default::default()
}, },
), ),
( (
temp_dir.uri().join("root3/").unwrap(), temp_dir.url().join("root3/").unwrap(),
WorkspaceSettings { WorkspaceSettings {
enable: Some(false), enable: Some(false),
..Default::default() ..Default::default()
}, },
), ),
( (
temp_dir.uri().join("root4_parent/root4/").unwrap(), temp_dir.url().join("root4_parent/root4/").unwrap(),
WorkspaceSettings { WorkspaceSettings {
enable: Some(true), enable: Some(true),
..Default::default() ..Default::default()
@ -4017,22 +4026,22 @@ mod tests {
assert_eq!( assert_eq!(
json!(workspace_files), json!(workspace_files),
json!([ json!([
temp_dir.uri().join("root4_parent/deno.json").unwrap(), temp_dir.url().join("root4_parent/deno.json").unwrap(),
temp_dir.uri().join("root1/mod0.ts").unwrap(), temp_dir.url().join("root1/mod0.ts").unwrap(),
temp_dir.uri().join("root1/mod1.js").unwrap(), temp_dir.url().join("root1/mod1.js").unwrap(),
temp_dir.uri().join("root1/mod2.tsx").unwrap(), temp_dir.url().join("root1/mod2.tsx").unwrap(),
temp_dir.uri().join("root1/mod3.d.ts").unwrap(), temp_dir.url().join("root1/mod3.d.ts").unwrap(),
temp_dir.uri().join("root1/mod4.jsx").unwrap(), temp_dir.url().join("root1/mod4.jsx").unwrap(),
temp_dir.uri().join("root1/mod5.mjs").unwrap(), temp_dir.url().join("root1/mod5.mjs").unwrap(),
temp_dir.uri().join("root1/mod6.mts").unwrap(), temp_dir.url().join("root1/mod6.mts").unwrap(),
temp_dir.uri().join("root1/mod7.d.mts").unwrap(), temp_dir.url().join("root1/mod7.d.mts").unwrap(),
temp_dir.uri().join("root1/mod8.json").unwrap(), temp_dir.url().join("root1/mod8.json").unwrap(),
temp_dir.uri().join("root1/mod9.jsonc").unwrap(), temp_dir.url().join("root1/mod9.jsonc").unwrap(),
temp_dir.uri().join("root2/file1.ts").unwrap(), temp_dir.url().join("root2/file1.ts").unwrap(),
temp_dir.uri().join("root4_parent/root4/main.ts").unwrap(), temp_dir.url().join("root4_parent/root4/main.ts").unwrap(),
temp_dir.uri().join("root1/folder/mod.ts").unwrap(), temp_dir.url().join("root1/folder/mod.ts").unwrap(),
temp_dir.uri().join("root2/folder/main.ts").unwrap(), temp_dir.url().join("root2/folder/main.ts").unwrap(),
temp_dir.uri().join("root2/root2.1/main.ts").unwrap(), temp_dir.url().join("root2/root2.1/main.ts").unwrap(),
]) ])
); );
} }

View file

@ -17,7 +17,7 @@ pub struct TaskDefinition {
// TODO(nayeemrmn): Rename this to `command` in vscode_deno. // TODO(nayeemrmn): Rename this to `command` in vscode_deno.
#[serde(rename = "detail")] #[serde(rename = "detail")]
pub command: String, pub command: String,
pub source_uri: lsp::Url, pub source_uri: lsp::Uri,
} }
#[derive(Debug, Deserialize, Serialize)] #[derive(Debug, Deserialize, Serialize)]
@ -75,8 +75,8 @@ pub enum DenoConfigurationType {
#[derive(Debug, Eq, Hash, PartialEq, Clone, Deserialize, Serialize)] #[derive(Debug, Eq, Hash, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct DenoConfigurationChangeEvent { pub struct DenoConfigurationChangeEvent {
pub scope_uri: lsp::Url, pub scope_uri: lsp::Uri,
pub file_uri: lsp::Url, pub file_uri: lsp::Uri,
#[serde(rename = "type")] #[serde(rename = "type")]
pub typ: DenoConfigurationChangeType, pub typ: DenoConfigurationChangeType,
pub configuration_type: DenoConfigurationType, pub configuration_type: DenoConfigurationType,

View file

@ -1,6 +1,7 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
use std::collections::HashMap; use std::collections::HashMap;
use std::str::FromStr;
use deno_ast::LineAndColumnIndex; use deno_ast::LineAndColumnIndex;
use deno_ast::ModuleSpecifier; use deno_ast::ModuleSpecifier;
@ -8,6 +9,7 @@ use deno_ast::SourceTextInfo;
use deno_core::anyhow::anyhow; use deno_core::anyhow::anyhow;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json; use deno_core::serde_json;
use lsp_types::Uri;
use tower_lsp::lsp_types::ClientCapabilities; use tower_lsp::lsp_types::ClientCapabilities;
use tower_lsp::lsp_types::ClientInfo; use tower_lsp::lsp_types::ClientInfo;
use tower_lsp::lsp_types::CompletionContext; use tower_lsp::lsp_types::CompletionContext;
@ -40,6 +42,7 @@ use super::config::LanguageWorkspaceSettings;
use super::config::ObjectLiteralMethodSnippets; use super::config::ObjectLiteralMethodSnippets;
use super::config::TestingSettings; use super::config::TestingSettings;
use super::config::WorkspaceSettings; use super::config::WorkspaceSettings;
use super::urls::url_to_uri;
#[derive(Debug)] #[derive(Debug)]
pub struct ReplCompletionItem { pub struct ReplCompletionItem {
@ -73,7 +76,7 @@ impl ReplLanguageServer {
.initialize(InitializeParams { .initialize(InitializeParams {
process_id: None, process_id: None,
root_path: None, root_path: None,
root_uri: Some(cwd_uri.clone()), root_uri: Some(url_to_uri(&cwd_uri)),
initialization_options: Some( initialization_options: Some(
serde_json::to_value(get_repl_workspace_settings()).unwrap(), serde_json::to_value(get_repl_workspace_settings()).unwrap(),
), ),
@ -84,6 +87,7 @@ impl ReplLanguageServer {
general: None, general: None,
experimental: None, experimental: None,
offset_encoding: None, offset_encoding: None,
notebook_document: None,
}, },
trace: None, trace: None,
workspace_folders: None, workspace_folders: None,
@ -92,6 +96,7 @@ impl ReplLanguageServer {
version: None, version: None,
}), }),
locale: None, locale: None,
work_done_progress_params: Default::default(),
}) })
.await?; .await?;
@ -133,7 +138,7 @@ impl ReplLanguageServer {
.completion(CompletionParams { .completion(CompletionParams {
text_document_position: TextDocumentPositionParams { text_document_position: TextDocumentPositionParams {
text_document: TextDocumentIdentifier { text_document: TextDocumentIdentifier {
uri: self.get_document_specifier(), uri: self.get_document_uri(),
}, },
position: Position { position: Position {
line: line_and_column.line_index as u32, line: line_and_column.line_index as u32,
@ -208,7 +213,7 @@ impl ReplLanguageServer {
.language_server .language_server
.did_change(DidChangeTextDocumentParams { .did_change(DidChangeTextDocumentParams {
text_document: VersionedTextDocumentIdentifier { text_document: VersionedTextDocumentIdentifier {
uri: self.get_document_specifier(), uri: self.get_document_uri(),
version: self.document_version, version: self.document_version,
}, },
content_changes: vec![TextDocumentContentChangeEvent { content_changes: vec![TextDocumentContentChangeEvent {
@ -233,7 +238,7 @@ impl ReplLanguageServer {
.language_server .language_server
.did_close(DidCloseTextDocumentParams { .did_close(DidCloseTextDocumentParams {
text_document: TextDocumentIdentifier { text_document: TextDocumentIdentifier {
uri: self.get_document_specifier(), uri: self.get_document_uri(),
}, },
}) })
.await; .await;
@ -248,7 +253,7 @@ impl ReplLanguageServer {
.language_server .language_server
.did_open(DidOpenTextDocumentParams { .did_open(DidOpenTextDocumentParams {
text_document: TextDocumentItem { text_document: TextDocumentItem {
uri: self.get_document_specifier(), uri: self.get_document_uri(),
language_id: "typescript".to_string(), language_id: "typescript".to_string(),
version: self.document_version, version: self.document_version,
text: format!("{}{}", self.document_text, self.pending_text), text: format!("{}{}", self.document_text, self.pending_text),
@ -257,8 +262,8 @@ impl ReplLanguageServer {
.await; .await;
} }
fn get_document_specifier(&self) -> ModuleSpecifier { fn get_document_uri(&self) -> Uri {
self.cwd_uri.join("$deno$repl.ts").unwrap() Uri::from_str(self.cwd_uri.join("$deno$repl.ts").unwrap().as_str()).unwrap()
} }
} }

View file

@ -5,6 +5,7 @@ use super::lsp_custom::TestData;
use crate::lsp::client::TestingNotification; use crate::lsp::client::TestingNotification;
use crate::lsp::logging::lsp_warn; use crate::lsp::logging::lsp_warn;
use crate::lsp::urls::url_to_uri;
use crate::tools::test::TestDescription; use crate::tools::test::TestDescription;
use crate::tools::test::TestStepDescription; use crate::tools::test::TestStepDescription;
use crate::util::checksum; use crate::util::checksum;
@ -147,7 +148,7 @@ impl TestModule {
let label = self.label(maybe_root_uri); let label = self.label(maybe_root_uri);
TestingNotification::Module(lsp_custom::TestModuleNotificationParams { TestingNotification::Module(lsp_custom::TestModuleNotificationParams {
text_document: lsp::TextDocumentIdentifier { text_document: lsp::TextDocumentIdentifier {
uri: self.specifier.clone(), uri: url_to_uri(&self.specifier),
}, },
kind: lsp_custom::TestModuleNotificationKind::Replace, kind: lsp_custom::TestModuleNotificationKind::Replace,
label, label,

View file

@ -12,6 +12,8 @@ use crate::lsp::client::Client;
use crate::lsp::client::TestingNotification; use crate::lsp::client::TestingNotification;
use crate::lsp::config; use crate::lsp::config;
use crate::lsp::logging::lsp_log; use crate::lsp::logging::lsp_log;
use crate::lsp::urls::uri_to_url;
use crate::lsp::urls::url_to_uri;
use crate::tools::test; use crate::tools::test;
use crate::tools::test::create_test_event_channel; use crate::tools::test::create_test_event_channel;
use crate::tools::test::FailFastTracker; use crate::tools::test::FailFastTracker;
@ -30,9 +32,11 @@ use deno_core::ModuleSpecifier;
use deno_runtime::deno_permissions::Permissions; use deno_runtime::deno_permissions::Permissions;
use deno_runtime::tokio_util::create_and_run_current_thread; use deno_runtime::tokio_util::create_and_run_current_thread;
use indexmap::IndexMap; use indexmap::IndexMap;
use lsp_types::Uri;
use std::collections::HashMap; use std::collections::HashMap;
use std::collections::HashSet; use std::collections::HashSet;
use std::num::NonZeroUsize; use std::num::NonZeroUsize;
use std::str::FromStr;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use std::time::Instant; use std::time::Instant;
@ -53,12 +57,12 @@ fn as_queue_and_filters(
if let Some(include) = &params.include { if let Some(include) = &params.include {
for item in include { for item in include {
if let Some((test_definitions, _)) = tests.get(&item.text_document.uri) { let url = uri_to_url(&item.text_document.uri);
queue.insert(item.text_document.uri.clone()); if let Some((test_definitions, _)) = tests.get(&url) {
queue.insert(url.clone());
if let Some(id) = &item.id { if let Some(id) = &item.id {
if let Some(test) = test_definitions.get(id) { if let Some(test) = test_definitions.get(id) {
let filter = let filter = filters.entry(url).or_default();
filters.entry(item.text_document.uri.clone()).or_default();
if let Some(include) = filter.include.as_mut() { if let Some(include) = filter.include.as_mut() {
include.insert(test.id.clone(), test.clone()); include.insert(test.id.clone(), test.clone());
} else { } else {
@ -75,19 +79,19 @@ fn as_queue_and_filters(
} }
for item in &params.exclude { for item in &params.exclude {
if let Some((test_definitions, _)) = tests.get(&item.text_document.uri) { let url = uri_to_url(&item.text_document.uri);
if let Some((test_definitions, _)) = tests.get(&url) {
if let Some(id) = &item.id { if let Some(id) = &item.id {
// there is no way to exclude a test step // there is no way to exclude a test step
if item.step_id.is_none() { if item.step_id.is_none() {
if let Some(test) = test_definitions.get(id) { if let Some(test) = test_definitions.get(id) {
let filter = let filter = filters.entry(url.clone()).or_default();
filters.entry(item.text_document.uri.clone()).or_default();
filter.exclude.insert(test.id.clone(), test.clone()); filter.exclude.insert(test.id.clone(), test.clone());
} }
} }
} else { } else {
// the entire test module is excluded // the entire test module is excluded
queue.remove(&item.text_document.uri); queue.remove(&url);
} }
} }
} }
@ -193,7 +197,7 @@ impl TestRun {
Vec::new() Vec::new()
}; };
lsp_custom::EnqueuedTestModule { lsp_custom::EnqueuedTestModule {
text_document: lsp::TextDocumentIdentifier { uri: s.clone() }, text_document: lsp::TextDocumentIdentifier { uri: url_to_uri(s) },
ids, ids,
} }
}) })
@ -523,7 +527,7 @@ impl LspTestDescription {
&self, &self,
tests: &IndexMap<usize, LspTestDescription>, tests: &IndexMap<usize, LspTestDescription>,
) -> lsp_custom::TestIdentifier { ) -> lsp_custom::TestIdentifier {
let uri = ModuleSpecifier::parse(&self.location().file_name).unwrap(); let uri = Uri::from_str(&self.location().file_name).unwrap();
let static_id = self.static_id(); let static_id = self.static_id();
let mut root_desc = self; let mut root_desc = self;
while let Some(parent_id) = root_desc.parent_id() { while let Some(parent_id) = root_desc.parent_id() {
@ -598,7 +602,7 @@ impl LspTestReporter {
.send_test_notification(TestingNotification::Module( .send_test_notification(TestingNotification::Module(
lsp_custom::TestModuleNotificationParams { lsp_custom::TestModuleNotificationParams {
text_document: lsp::TextDocumentIdentifier { text_document: lsp::TextDocumentIdentifier {
uri: test_module.specifier.clone(), uri: url_to_uri(&test_module.specifier),
}, },
kind: lsp_custom::TestModuleNotificationKind::Insert, kind: lsp_custom::TestModuleNotificationKind::Insert,
label: test_module.label(self.maybe_root_uri.as_ref()), label: test_module.label(self.maybe_root_uri.as_ref()),
@ -711,7 +715,7 @@ impl LspTestReporter {
.send_test_notification(TestingNotification::Module( .send_test_notification(TestingNotification::Module(
lsp_custom::TestModuleNotificationParams { lsp_custom::TestModuleNotificationParams {
text_document: lsp::TextDocumentIdentifier { text_document: lsp::TextDocumentIdentifier {
uri: test_module.specifier.clone(), uri: url_to_uri(&test_module.specifier),
}, },
kind: lsp_custom::TestModuleNotificationKind::Insert, kind: lsp_custom::TestModuleNotificationKind::Insert,
label: test_module.label(self.maybe_root_uri.as_ref()), label: test_module.label(self.maybe_root_uri.as_ref()),
@ -796,14 +800,14 @@ mod tests {
include: Some(vec![ include: Some(vec![
lsp_custom::TestIdentifier { lsp_custom::TestIdentifier {
text_document: lsp::TextDocumentIdentifier { text_document: lsp::TextDocumentIdentifier {
uri: specifier.clone(), uri: url_to_uri(&specifier),
}, },
id: None, id: None,
step_id: None, step_id: None,
}, },
lsp_custom::TestIdentifier { lsp_custom::TestIdentifier {
text_document: lsp::TextDocumentIdentifier { text_document: lsp::TextDocumentIdentifier {
uri: non_test_specifier.clone(), uri: url_to_uri(&non_test_specifier),
}, },
id: None, id: None,
step_id: None, step_id: None,
@ -811,7 +815,7 @@ mod tests {
]), ]),
exclude: vec![lsp_custom::TestIdentifier { exclude: vec![lsp_custom::TestIdentifier {
text_document: lsp::TextDocumentIdentifier { text_document: lsp::TextDocumentIdentifier {
uri: specifier.clone(), uri: url_to_uri(&specifier),
}, },
id: Some( id: Some(
"69d9fe87f64f5b66cb8b631d4fd2064e8224b8715a049be54276c42189ff8f9f" "69d9fe87f64f5b66cb8b631d4fd2064e8224b8715a049be54276c42189ff8f9f"

View file

@ -10,6 +10,7 @@ use crate::lsp::config;
use crate::lsp::documents::DocumentsFilter; use crate::lsp::documents::DocumentsFilter;
use crate::lsp::language_server::StateSnapshot; use crate::lsp::language_server::StateSnapshot;
use crate::lsp::performance::Performance; use crate::lsp::performance::Performance;
use crate::lsp::urls::url_to_uri;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::parking_lot::Mutex; use deno_core::parking_lot::Mutex;
@ -26,10 +27,12 @@ use tower_lsp::jsonrpc::Error as LspError;
use tower_lsp::jsonrpc::Result as LspResult; use tower_lsp::jsonrpc::Result as LspResult;
use tower_lsp::lsp_types as lsp; use tower_lsp::lsp_types as lsp;
fn as_delete_notification(uri: ModuleSpecifier) -> TestingNotification { fn as_delete_notification(url: ModuleSpecifier) -> TestingNotification {
TestingNotification::DeleteModule( TestingNotification::DeleteModule(
lsp_custom::TestModuleDeleteNotificationParams { lsp_custom::TestModuleDeleteNotificationParams {
text_document: lsp::TextDocumentIdentifier { uri }, text_document: lsp::TextDocumentIdentifier {
uri: url_to_uri(&url),
},
}, },
) )
} }

View file

@ -19,6 +19,7 @@ use super::refactor::EXTRACT_TYPE;
use super::semantic_tokens; use super::semantic_tokens;
use super::semantic_tokens::SemanticTokensBuilder; use super::semantic_tokens::SemanticTokensBuilder;
use super::text::LineIndex; use super::text::LineIndex;
use super::urls::url_to_uri;
use super::urls::LspClientUrl; use super::urls::LspClientUrl;
use super::urls::INVALID_SPECIFIER; use super::urls::INVALID_SPECIFIER;
@ -2071,7 +2072,7 @@ impl DocumentSpan {
}; };
let link = lsp::LocationLink { let link = lsp::LocationLink {
origin_selection_range, origin_selection_range,
target_uri: target_uri.into_url(), target_uri: target_uri.to_uri(),
target_range, target_range,
target_selection_range, target_selection_range,
}; };
@ -2158,7 +2159,7 @@ impl NavigateToItem {
.ok()?; .ok()?;
let range = self.text_span.to_range(line_index); let range = self.text_span.to_range(line_index);
let location = lsp::Location { let location = lsp::Location {
uri: uri.into_url(), uri: uri.to_uri(),
range, range,
}; };
@ -2418,7 +2419,7 @@ impl ImplementationLocation {
LspClientUrl::new(ModuleSpecifier::parse("deno://invalid").unwrap()) LspClientUrl::new(ModuleSpecifier::parse("deno://invalid").unwrap())
}); });
lsp::Location { lsp::Location {
uri: uri.into_url(), uri: uri.to_uri(),
range: self.document_span.text_span.to_range(line_index), range: self.document_span.text_span.to_range(line_index),
} }
} }
@ -2483,7 +2484,7 @@ impl RenameLocations {
uri.clone(), uri.clone(),
lsp::TextDocumentEdit { lsp::TextDocumentEdit {
text_document: lsp::OptionalVersionedTextDocumentIdentifier { text_document: lsp::OptionalVersionedTextDocumentIdentifier {
uri: uri.as_url().clone(), uri: uri.to_uri(),
version: asset_or_doc.document_lsp_version(), version: asset_or_doc.document_lsp_version(),
}, },
edits: edits:
@ -2685,7 +2686,7 @@ impl FileTextChanges {
.collect(); .collect();
Ok(lsp::TextDocumentEdit { Ok(lsp::TextDocumentEdit {
text_document: lsp::OptionalVersionedTextDocumentIdentifier { text_document: lsp::OptionalVersionedTextDocumentIdentifier {
uri: specifier, uri: url_to_uri(&specifier),
version: asset_or_doc.document_lsp_version(), version: asset_or_doc.document_lsp_version(),
}, },
edits, edits,
@ -2712,7 +2713,7 @@ impl FileTextChanges {
if self.is_new_file.unwrap_or(false) { if self.is_new_file.unwrap_or(false) {
ops.push(lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create( ops.push(lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(
lsp::CreateFile { lsp::CreateFile {
uri: specifier.clone(), uri: url_to_uri(&specifier),
options: Some(lsp::CreateFileOptions { options: Some(lsp::CreateFileOptions {
ignore_if_exists: Some(true), ignore_if_exists: Some(true),
overwrite: None, overwrite: None,
@ -2729,7 +2730,7 @@ impl FileTextChanges {
.collect(); .collect();
ops.push(lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit { ops.push(lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
text_document: lsp::OptionalVersionedTextDocumentIdentifier { text_document: lsp::OptionalVersionedTextDocumentIdentifier {
uri: specifier, uri: url_to_uri(&specifier),
version: maybe_asset_or_document.and_then(|d| d.document_lsp_version()), version: maybe_asset_or_document.and_then(|d| d.document_lsp_version()),
}, },
edits, edits,
@ -3130,7 +3131,7 @@ impl ReferenceEntry {
.normalize_specifier(&specifier, file_referrer.as_deref()) .normalize_specifier(&specifier, file_referrer.as_deref())
.unwrap_or_else(|_| LspClientUrl::new(INVALID_SPECIFIER.clone())); .unwrap_or_else(|_| LspClientUrl::new(INVALID_SPECIFIER.clone()));
lsp::Location { lsp::Location {
uri: uri.into_url(), uri: uri.to_uri(),
range: self.document_span.text_span.to_range(line_index), range: self.document_span.text_span.to_range(line_index),
} }
} }
@ -3237,7 +3238,7 @@ impl CallHierarchyItem {
lsp::CallHierarchyItem { lsp::CallHierarchyItem {
name, name,
tags, tags,
uri: uri.into_url(), uri: uri.to_uri(),
detail: Some(detail), detail: Some(detail),
kind: self.kind.clone().into(), kind: self.kind.clone().into(),
range: self.span.to_range(line_index.clone()), range: self.span.to_range(line_index.clone()),
@ -5398,7 +5399,7 @@ mod tests {
sources: &[(&str, &str, i32, LanguageId)], sources: &[(&str, &str, i32, LanguageId)],
) -> (TempDir, TsServer, Arc<StateSnapshot>, LspCache) { ) -> (TempDir, TsServer, Arc<StateSnapshot>, LspCache) {
let temp_dir = TempDir::new(); let temp_dir = TempDir::new();
let cache = LspCache::new(Some(temp_dir.uri().join(".deno_dir").unwrap())); let cache = LspCache::new(Some(temp_dir.url().join(".deno_dir").unwrap()));
let mut config = Config::default(); let mut config = Config::default();
config config
.tree .tree
@ -5408,7 +5409,7 @@ mod tests {
"compilerOptions": ts_config, "compilerOptions": ts_config,
}) })
.to_string(), .to_string(),
temp_dir.uri().join("deno.json").unwrap(), temp_dir.url().join("deno.json").unwrap(),
&Default::default(), &Default::default(),
) )
.unwrap(), .unwrap(),
@ -5419,7 +5420,7 @@ mod tests {
let mut documents = Documents::default(); let mut documents = Documents::default();
documents.update_config(&config, &resolver, &cache, &Default::default()); documents.update_config(&config, &resolver, &cache, &Default::default());
for (relative_specifier, source, version, language_id) in sources { for (relative_specifier, source, version, language_id) in sources {
let specifier = temp_dir.uri().join(relative_specifier).unwrap(); let specifier = temp_dir.url().join(relative_specifier).unwrap();
documents.open(specifier, *version, *language_id, (*source).into(), None); documents.open(specifier, *version, *language_id, (*source).into(), None);
} }
let snapshot = Arc::new(StateSnapshot { let snapshot = Arc::new(StateSnapshot {
@ -5489,7 +5490,7 @@ mod tests {
)], )],
) )
.await; .await;
let specifier = temp_dir.uri().join("a.ts").unwrap(); let specifier = temp_dir.url().join("a.ts").unwrap();
let diagnostics = ts_server let diagnostics = ts_server
.get_diagnostics(snapshot, vec![specifier.clone()], Default::default()) .get_diagnostics(snapshot, vec![specifier.clone()], Default::default())
.await .await
@ -5536,7 +5537,7 @@ mod tests {
)], )],
) )
.await; .await;
let specifier = temp_dir.uri().join("a.ts").unwrap(); let specifier = temp_dir.url().join("a.ts").unwrap();
let diagnostics = ts_server let diagnostics = ts_server
.get_diagnostics(snapshot, vec![specifier.clone()], Default::default()) .get_diagnostics(snapshot, vec![specifier.clone()], Default::default())
.await .await
@ -5567,7 +5568,7 @@ mod tests {
)], )],
) )
.await; .await;
let specifier = temp_dir.uri().join("a.ts").unwrap(); let specifier = temp_dir.url().join("a.ts").unwrap();
let diagnostics = ts_server let diagnostics = ts_server
.get_diagnostics(snapshot, vec![specifier.clone()], Default::default()) .get_diagnostics(snapshot, vec![specifier.clone()], Default::default())
.await .await
@ -5594,7 +5595,7 @@ mod tests {
)], )],
) )
.await; .await;
let specifier = temp_dir.uri().join("a.ts").unwrap(); let specifier = temp_dir.url().join("a.ts").unwrap();
let diagnostics = ts_server let diagnostics = ts_server
.get_diagnostics(snapshot, vec![specifier.clone()], Default::default()) .get_diagnostics(snapshot, vec![specifier.clone()], Default::default())
.await .await
@ -5644,7 +5645,7 @@ mod tests {
)], )],
) )
.await; .await;
let specifier = temp_dir.uri().join("a.ts").unwrap(); let specifier = temp_dir.url().join("a.ts").unwrap();
let diagnostics = ts_server let diagnostics = ts_server
.get_diagnostics(snapshot, vec![specifier.clone()], Default::default()) .get_diagnostics(snapshot, vec![specifier.clone()], Default::default())
.await .await
@ -5678,7 +5679,7 @@ mod tests {
)], )],
) )
.await; .await;
let specifier = temp_dir.uri().join("a.ts").unwrap(); let specifier = temp_dir.url().join("a.ts").unwrap();
let diagnostics = ts_server let diagnostics = ts_server
.get_diagnostics(snapshot, vec![specifier.clone()], Default::default()) .get_diagnostics(snapshot, vec![specifier.clone()], Default::default())
.await .await
@ -5736,7 +5737,7 @@ mod tests {
)], )],
) )
.await; .await;
let specifier = temp_dir.uri().join("a.ts").unwrap(); let specifier = temp_dir.url().join("a.ts").unwrap();
let diagnostics = ts_server let diagnostics = ts_server
.get_diagnostics(snapshot, vec![specifier.clone()], Default::default()) .get_diagnostics(snapshot, vec![specifier.clone()], Default::default())
.await .await
@ -5829,7 +5830,7 @@ mod tests {
b"export const b = \"b\";\n", b"export const b = \"b\";\n",
) )
.unwrap(); .unwrap();
let specifier = temp_dir.uri().join("a.ts").unwrap(); let specifier = temp_dir.url().join("a.ts").unwrap();
let diagnostics = ts_server let diagnostics = ts_server
.get_diagnostics( .get_diagnostics(
snapshot.clone(), snapshot.clone(),
@ -5879,7 +5880,7 @@ mod tests {
[(&specifier_dep, ChangeKind::Opened)], [(&specifier_dep, ChangeKind::Opened)],
None, None,
); );
let specifier = temp_dir.uri().join("a.ts").unwrap(); let specifier = temp_dir.url().join("a.ts").unwrap();
let diagnostics = ts_server let diagnostics = ts_server
.get_diagnostics( .get_diagnostics(
snapshot.clone(), snapshot.clone(),
@ -5951,7 +5952,7 @@ mod tests {
&[("a.ts", fixture, 1, LanguageId::TypeScript)], &[("a.ts", fixture, 1, LanguageId::TypeScript)],
) )
.await; .await;
let specifier = temp_dir.uri().join("a.ts").unwrap(); let specifier = temp_dir.url().join("a.ts").unwrap();
let info = ts_server let info = ts_server
.get_completions( .get_completions(
snapshot.clone(), snapshot.clone(),
@ -5966,7 +5967,7 @@ mod tests {
trigger_kind: None, trigger_kind: None,
}, },
Default::default(), Default::default(),
Some(temp_dir.uri()), Some(temp_dir.url()),
) )
.await .await
.unwrap(); .unwrap();
@ -5983,7 +5984,7 @@ mod tests {
preferences: None, preferences: None,
data: None, data: None,
}, },
Some(temp_dir.uri()), Some(temp_dir.url()),
) )
.await .await
.unwrap() .unwrap()
@ -6105,7 +6106,7 @@ mod tests {
], ],
) )
.await; .await;
let specifier = temp_dir.uri().join("a.ts").unwrap(); let specifier = temp_dir.url().join("a.ts").unwrap();
let fmt_options_config = FmtOptionsConfig { let fmt_options_config = FmtOptionsConfig {
semi_colons: Some(false), semi_colons: Some(false),
single_quote: Some(true), single_quote: Some(true),
@ -6126,7 +6127,7 @@ mod tests {
..Default::default() ..Default::default()
}, },
FormatCodeSettings::from(&fmt_options_config), FormatCodeSettings::from(&fmt_options_config),
Some(temp_dir.uri()), Some(temp_dir.url()),
) )
.await .await
.unwrap(); .unwrap();
@ -6152,7 +6153,7 @@ mod tests {
}), }),
data: entry.data.clone(), data: entry.data.clone(),
}, },
Some(temp_dir.uri()), Some(temp_dir.url()),
) )
.await .await
.unwrap() .unwrap()
@ -6217,8 +6218,8 @@ mod tests {
let changes = ts_server let changes = ts_server
.get_edits_for_file_rename( .get_edits_for_file_rename(
snapshot, snapshot,
temp_dir.uri().join("b.ts").unwrap(), temp_dir.url().join("b.ts").unwrap(),
temp_dir.uri().join("🦕.ts").unwrap(), temp_dir.url().join("🦕.ts").unwrap(),
FormatCodeSettings::default(), FormatCodeSettings::default(),
UserPreferences::default(), UserPreferences::default(),
) )
@ -6227,7 +6228,7 @@ mod tests {
assert_eq!( assert_eq!(
changes, changes,
vec![FileTextChanges { vec![FileTextChanges {
file_name: temp_dir.uri().join("a.ts").unwrap().to_string(), file_name: temp_dir.url().join("a.ts").unwrap().to_string(),
text_changes: vec![TextChange { text_changes: vec![TextChange {
span: TextSpan { span: TextSpan {
start: 8, start: 8,
@ -6286,7 +6287,7 @@ mod tests {
let resolved = op_resolve_inner( let resolved = op_resolve_inner(
&mut state, &mut state,
ResolveArgs { ResolveArgs {
base: temp_dir.uri().join("a.ts").unwrap().to_string(), base: temp_dir.url().join("a.ts").unwrap().to_string(),
is_base_cjs: false, is_base_cjs: false,
specifiers: vec!["./b.ts".to_string()], specifiers: vec!["./b.ts".to_string()],
}, },
@ -6295,7 +6296,7 @@ mod tests {
assert_eq!( assert_eq!(
resolved, resolved,
vec![Some(( vec![Some((
temp_dir.uri().join("b.ts").unwrap().to_string(), temp_dir.url().join("b.ts").unwrap().to_string(),
MediaType::TypeScript.as_ts_extension().to_string() MediaType::TypeScript.as_ts_extension().to_string()
))] ))]
); );

View file

@ -6,8 +6,10 @@ use deno_core::parking_lot::Mutex;
use deno_core::url::Position; use deno_core::url::Position;
use deno_core::url::Url; use deno_core::url::Url;
use deno_core::ModuleSpecifier; use deno_core::ModuleSpecifier;
use lsp_types::Uri;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use std::collections::HashMap; use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Arc; use std::sync::Arc;
use super::cache::LspCache; use super::cache::LspCache;
@ -111,6 +113,10 @@ impl LspClientUrl {
self.0 self.0
} }
pub fn to_uri(&self) -> Uri {
url_to_uri(&self.0)
}
pub fn as_str(&self) -> &str { pub fn as_str(&self) -> &str {
self.0.as_str() self.0.as_str()
} }
@ -145,6 +151,14 @@ impl LspUrlMapInner {
} }
} }
pub fn url_to_uri(url: &Url) -> Uri {
Uri::from_str(url.as_str()).unwrap()
}
pub fn uri_to_url(uri: &Uri) -> Url {
Url::parse(uri.as_str()).unwrap()
}
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub enum LspUrlKind { pub enum LspUrlKind {
File, File,
@ -218,12 +232,13 @@ impl LspUrlMap {
/// Note: Sometimes the url provided by the client may not have a trailing slash, /// Note: Sometimes the url provided by the client may not have a trailing slash,
/// so we need to force it to in the mapping and nee to explicitly state whether /// so we need to force it to in the mapping and nee to explicitly state whether
/// this is a file or directory url. /// this is a file or directory url.
pub fn normalize_url(&self, url: &Url, kind: LspUrlKind) -> ModuleSpecifier { pub fn normalize_url(&self, uri: &Uri, kind: LspUrlKind) -> ModuleSpecifier {
if let Some(remote_url) = self.cache.unvendored_specifier(url) { let url = uri_to_url(uri);
if let Some(remote_url) = self.cache.unvendored_specifier(&url) {
return remote_url; return remote_url;
} }
let mut inner = self.inner.lock(); let mut inner = self.inner.lock();
if let Some(specifier) = inner.get_specifier(url).cloned() { if let Some(specifier) = inner.get_specifier(&url).cloned() {
return specifier; return specifier;
} }
let mut specifier = None; let mut specifier = None;
@ -234,13 +249,13 @@ impl LspUrlMap {
LspUrlKind::File => Url::from_file_path(path).unwrap(), LspUrlKind::File => Url::from_file_path(path).unwrap(),
}); });
} }
} else if let Some(s) = file_like_to_file_specifier(url) { } else if let Some(s) = file_like_to_file_specifier(&url) {
specifier = Some(s); specifier = Some(s);
} else if let Some(s) = from_deno_url(url) { } else if let Some(s) = from_deno_url(&url) {
specifier = Some(s); specifier = Some(s);
} }
let specifier = specifier.unwrap_or_else(|| url.clone()); let specifier = specifier.unwrap_or_else(|| url.clone());
inner.put(specifier.clone(), LspClientUrl(url.clone())); inner.put(specifier.clone(), LspClientUrl(url));
specifier specifier
} }
} }
@ -296,7 +311,7 @@ mod tests {
assert_eq!(actual_url.as_url(), &expected_url); assert_eq!(actual_url.as_url(), &expected_url);
let actual_specifier = let actual_specifier =
map.normalize_url(actual_url.as_url(), LspUrlKind::File); map.normalize_url(&actual_url.to_uri(), LspUrlKind::File);
assert_eq!(actual_specifier, fixture); assert_eq!(actual_specifier, fixture);
} }
@ -304,7 +319,7 @@ mod tests {
fn test_lsp_url_reverse() { fn test_lsp_url_reverse() {
let map = LspUrlMap::default(); let map = LspUrlMap::default();
let fixture = let fixture =
resolve_url("deno:/https/deno.land/x/pkg%401.0.0/mod.ts").unwrap(); Uri::from_str("deno:/https/deno.land/x/pkg%401.0.0/mod.ts").unwrap();
let actual_specifier = map.normalize_url(&fixture, LspUrlKind::File); let actual_specifier = map.normalize_url(&fixture, LspUrlKind::File);
let expected_specifier = let expected_specifier =
Url::parse("https://deno.land/x/pkg@1.0.0/mod.ts").unwrap(); Url::parse("https://deno.land/x/pkg@1.0.0/mod.ts").unwrap();
@ -313,7 +328,7 @@ mod tests {
let actual_url = map let actual_url = map
.normalize_specifier(&actual_specifier, None) .normalize_specifier(&actual_specifier, None)
.unwrap() .unwrap()
.as_url() .to_uri()
.clone(); .clone();
assert_eq!(actual_url, fixture); assert_eq!(actual_url, fixture);
} }
@ -330,7 +345,7 @@ mod tests {
assert_eq!(actual_url.as_url(), &expected_url); assert_eq!(actual_url.as_url(), &expected_url);
let actual_specifier = let actual_specifier =
map.normalize_url(actual_url.as_url(), LspUrlKind::File); map.normalize_url(&actual_url.to_uri(), LspUrlKind::File);
assert_eq!(actual_specifier, fixture); assert_eq!(actual_specifier, fixture);
} }
@ -345,7 +360,7 @@ mod tests {
assert_eq!(actual_url.as_url(), &expected_url); assert_eq!(actual_url.as_url(), &expected_url);
let actual_specifier = let actual_specifier =
map.normalize_url(actual_url.as_url(), LspUrlKind::File); map.normalize_url(&actual_url.to_uri(), LspUrlKind::File);
assert_eq!(actual_specifier, fixture); assert_eq!(actual_specifier, fixture);
} }
@ -361,7 +376,7 @@ mod tests {
assert_eq!(actual_url.as_url(), &expected_url); assert_eq!(actual_url.as_url(), &expected_url);
let actual_specifier = let actual_specifier =
map.normalize_url(actual_url.as_url(), LspUrlKind::File); map.normalize_url(&actual_url.to_uri(), LspUrlKind::File);
assert_eq!(actual_specifier, fixture); assert_eq!(actual_specifier, fixture);
} }
@ -369,7 +384,7 @@ mod tests {
#[test] #[test]
fn test_normalize_windows_path() { fn test_normalize_windows_path() {
let map = LspUrlMap::default(); let map = LspUrlMap::default();
let fixture = resolve_url( let fixture = Uri::from_str(
"file:///c%3A/Users/deno/Desktop/file%20with%20spaces%20in%20name.txt", "file:///c%3A/Users/deno/Desktop/file%20with%20spaces%20in%20name.txt",
) )
.unwrap(); .unwrap();
@ -384,7 +399,7 @@ mod tests {
#[test] #[test]
fn test_normalize_percent_encoded_path() { fn test_normalize_percent_encoded_path() {
let map = LspUrlMap::default(); let map = LspUrlMap::default();
let fixture = resolve_url( let fixture = Uri::from_str(
"file:///Users/deno/Desktop/file%20with%20spaces%20in%20name.txt", "file:///Users/deno/Desktop/file%20with%20spaces%20in%20name.txt",
) )
.unwrap(); .unwrap();
@ -398,9 +413,9 @@ mod tests {
#[test] #[test]
fn test_normalize_deno_status() { fn test_normalize_deno_status() {
let map = LspUrlMap::default(); let map = LspUrlMap::default();
let fixture = resolve_url("deno:/status.md").unwrap(); let fixture = Uri::from_str("deno:/status.md").unwrap();
let actual = map.normalize_url(&fixture, LspUrlKind::File); let actual = map.normalize_url(&fixture, LspUrlKind::File);
assert_eq!(actual, fixture); assert_eq!(actual.as_str(), fixture.as_str());
} }
#[test] #[test]

View file

@ -1246,15 +1246,15 @@ mod test {
for (ext_from, ext_to) in [("js", "ts"), ("js", "tsx"), ("mjs", "mts")] { for (ext_from, ext_to) in [("js", "ts"), ("js", "tsx"), ("mjs", "mts")] {
let ts_file = temp_dir.join(format!("file.{}", ext_to)); let ts_file = temp_dir.join(format!("file.{}", ext_to));
ts_file.write(""); ts_file.write("");
assert_eq!(resolve(&ts_file.uri_file()), None); assert_eq!(resolve(&ts_file.url_file()), None);
assert_eq!( assert_eq!(
resolve( resolve(
&temp_dir &temp_dir
.uri_dir() .url_dir()
.join(&format!("file.{}", ext_from)) .join(&format!("file.{}", ext_from))
.unwrap() .unwrap()
), ),
Some(SloppyImportsResolution::JsToTs(ts_file.uri_file())), Some(SloppyImportsResolution::JsToTs(ts_file.url_file())),
); );
ts_file.remove_file(); ts_file.remove_file();
} }
@ -1266,11 +1266,11 @@ mod test {
assert_eq!( assert_eq!(
resolve( resolve(
&temp_dir &temp_dir
.uri_dir() .url_dir()
.join("file") // no ext .join("file") // no ext
.unwrap() .unwrap()
), ),
Some(SloppyImportsResolution::NoExtension(file.uri_file())) Some(SloppyImportsResolution::NoExtension(file.url_file()))
); );
file.remove_file(); file.remove_file();
} }
@ -1281,15 +1281,15 @@ mod test {
ts_file.write(""); ts_file.write("");
let js_file = temp_dir.join("file.js"); let js_file = temp_dir.join("file.js");
js_file.write(""); js_file.write("");
assert_eq!(resolve(&js_file.uri_file()), None); assert_eq!(resolve(&js_file.url_file()), None);
} }
// only js exists, .js specified // only js exists, .js specified
{ {
let js_only_file = temp_dir.join("js_only.js"); let js_only_file = temp_dir.join("js_only.js");
js_only_file.write(""); js_only_file.write("");
assert_eq!(resolve(&js_only_file.uri_file()), None); assert_eq!(resolve(&js_only_file.url_file()), None);
assert_eq!(resolve_types(&js_only_file.uri_file()), None); assert_eq!(resolve_types(&js_only_file.url_file()), None);
} }
// resolving a directory to an index file // resolving a directory to an index file
@ -1299,8 +1299,8 @@ mod test {
let index_file = routes_dir.join("index.ts"); let index_file = routes_dir.join("index.ts");
index_file.write(""); index_file.write("");
assert_eq!( assert_eq!(
resolve(&routes_dir.uri_file()), resolve(&routes_dir.url_file()),
Some(SloppyImportsResolution::Directory(index_file.uri_file())), Some(SloppyImportsResolution::Directory(index_file.url_file())),
); );
} }
@ -1313,8 +1313,8 @@ mod test {
let api_file = temp_dir.join("api.ts"); let api_file = temp_dir.join("api.ts");
api_file.write(""); api_file.write("");
assert_eq!( assert_eq!(
resolve(&api_dir.uri_file()), resolve(&api_dir.url_file()),
Some(SloppyImportsResolution::NoExtension(api_file.uri_file())), Some(SloppyImportsResolution::NoExtension(api_file.url_file())),
); );
} }
} }

View file

@ -3,8 +3,8 @@
use crate::http_util; use crate::http_util;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::serde_json; use deno_core::serde_json;
use deno_core::url::Url;
use deno_runtime::deno_fetch; use deno_runtime::deno_fetch;
use lsp_types::Url;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use crate::http_util::HttpClient; use crate::http_util::HttpClient;

View file

@ -21,9 +21,9 @@ use deno_ast::SourceRanged;
use deno_ast::SourceTextInfo; use deno_ast::SourceTextInfo;
use deno_core::anyhow::anyhow; use deno_core::anyhow::anyhow;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::url::Url;
use deno_graph::FastCheckDiagnostic; use deno_graph::FastCheckDiagnostic;
use deno_semver::Version; use deno_semver::Version;
use lsp_types::Url;
use super::unfurl::SpecifierUnfurlerDiagnostic; use super::unfurl::SpecifierUnfurlerDiagnostic;

View file

@ -8,13 +8,13 @@ use deno_ast::ParsedSource;
use deno_ast::SourceRangedForSpanned; use deno_ast::SourceRangedForSpanned;
use deno_ast::SourceTextInfo; use deno_ast::SourceTextInfo;
use deno_core::error::AnyError; use deno_core::error::AnyError;
use deno_core::url::Url;
use deno_graph::ModuleEntryRef; use deno_graph::ModuleEntryRef;
use deno_graph::ModuleGraph; use deno_graph::ModuleGraph;
use deno_graph::ResolutionResolved; use deno_graph::ResolutionResolved;
use deno_graph::WalkOptions; use deno_graph::WalkOptions;
use deno_semver::jsr::JsrPackageReqReference; use deno_semver::jsr::JsrPackageReqReference;
use deno_semver::npm::NpmPackageReqReference; use deno_semver::npm::NpmPackageReqReference;
use lsp_types::Url;
use crate::cache::ParsedSourceCache; use crate::cache::ParsedSourceCache;

View file

@ -25,9 +25,9 @@ use deno_core::futures::StreamExt;
use deno_core::serde_json; use deno_core::serde_json;
use deno_core::serde_json::json; use deno_core::serde_json::json;
use deno_core::serde_json::Value; use deno_core::serde_json::Value;
use deno_core::url::Url;
use deno_terminal::colors; use deno_terminal::colors;
use http_body_util::BodyExt; use http_body_util::BodyExt;
use lsp_types::Url;
use serde::Deserialize; use serde::Deserialize;
use serde::Serialize; use serde::Serialize;
use sha2::Digest; use sha2::Digest;

View file

@ -203,7 +203,7 @@ impl SpecifierUnfurler {
/// or `false` when the import was not analyzable. /// or `false` when the import was not analyzable.
fn try_unfurl_dynamic_dep( fn try_unfurl_dynamic_dep(
&self, &self,
module_url: &lsp_types::Url, module_url: &ModuleSpecifier,
text_info: &SourceTextInfo, text_info: &SourceTextInfo,
dep: &deno_graph::DynamicDependencyDescriptor, dep: &deno_graph::DynamicDependencyDescriptor,
text_changes: &mut Vec<deno_ast::TextChange>, text_changes: &mut Vec<deno_ast::TextChange>,

View file

@ -22,6 +22,7 @@ use deno_core::serde::Serialize;
use deno_core::serde::Serializer; use deno_core::serde::Serializer;
use deno_core::serde_json::json; use deno_core::serde_json::json;
use deno_core::serde_v8; use deno_core::serde_v8;
use deno_core::url::Url;
use deno_core::JsRuntime; use deno_core::JsRuntime;
use deno_core::ModuleSpecifier; use deno_core::ModuleSpecifier;
use deno_core::OpState; use deno_core::OpState;
@ -32,7 +33,6 @@ use deno_graph::ModuleGraph;
use deno_graph::ResolutionResolved; use deno_graph::ResolutionResolved;
use deno_runtime::deno_node::NodeResolver; use deno_runtime::deno_node::NodeResolver;
use deno_semver::npm::NpmPackageReqReference; use deno_semver::npm::NpmPackageReqReference;
use lsp_types::Url;
use node_resolver::errors::NodeJsErrorCode; use node_resolver::errors::NodeJsErrorCode;
use node_resolver::errors::NodeJsErrorCoded; use node_resolver::errors::NodeJsErrorCoded;
use node_resolver::NodeModuleKind; use node_resolver::NodeModuleKind;

File diff suppressed because it is too large Load diff

View file

@ -2090,7 +2090,7 @@ fn top_level_install_package_json_explicit_opt_in() {
rm_created_files(); rm_created_files();
let mut client = test_context.new_lsp_command().build(); let mut client = test_context.new_lsp_command().build();
client.initialize_default(); client.initialize_default();
let file_uri = temp_dir.uri().join("file.ts").unwrap(); let file_uri = temp_dir.url().join("file.ts").unwrap();
client.did_open(json!({ client.did_open(json!({
"textDocument": { "textDocument": {
"uri": file_uri, "uri": file_uri,

View file

@ -1,5 +1,6 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
use lsp_types::Uri;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use std::borrow::Cow; use std::borrow::Cow;
use std::collections::HashSet; use std::collections::HashSet;
@ -10,12 +11,13 @@ use std::io::Write;
use std::path::Path; use std::path::Path;
use std::path::PathBuf; use std::path::PathBuf;
use std::process::Command; use std::process::Command;
use std::str::FromStr;
use std::sync::Arc; use std::sync::Arc;
use anyhow::Context; use anyhow::Context;
use lsp_types::Url;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use serde::Serialize; use serde::Serialize;
use url::Url;
use crate::assertions::assert_wildcard_match; use crate::assertions::assert_wildcard_match;
use crate::testdata_path; use crate::testdata_path;
@ -52,14 +54,22 @@ impl PathRef {
PathRef(self.as_path().parent().unwrap().to_path_buf()) PathRef(self.as_path().parent().unwrap().to_path_buf())
} }
pub fn uri_dir(&self) -> Url { pub fn url_dir(&self) -> Url {
Url::from_directory_path(self.as_path()).unwrap() Url::from_directory_path(self.as_path()).unwrap()
} }
pub fn uri_file(&self) -> Url { pub fn url_file(&self) -> Url {
Url::from_file_path(self.as_path()).unwrap() Url::from_file_path(self.as_path()).unwrap()
} }
pub fn uri_dir(&self) -> Uri {
Uri::from_str(self.url_dir().as_str()).unwrap()
}
pub fn uri_file(&self) -> Uri {
Uri::from_str(self.url_file().as_str()).unwrap()
}
pub fn as_path(&self) -> &Path { pub fn as_path(&self) -> &Path {
self.0.as_path() self.0.as_path()
} }
@ -444,10 +454,14 @@ impl TempDir {
})) }))
} }
pub fn uri(&self) -> Url { pub fn url(&self) -> Url {
Url::from_directory_path(self.path()).unwrap() Url::from_directory_path(self.path()).unwrap()
} }
pub fn uri(&self) -> Uri {
Uri::from_str(self.url().as_str()).unwrap()
}
pub fn path(&self) -> &PathRef { pub fn path(&self) -> &PathRef {
self.0.path() self.0.path()
} }

View file

@ -21,7 +21,6 @@ use lsp_types::FoldingRangeClientCapabilities;
use lsp_types::InitializeParams; use lsp_types::InitializeParams;
use lsp_types::TextDocumentClientCapabilities; use lsp_types::TextDocumentClientCapabilities;
use lsp_types::TextDocumentSyncClientCapabilities; use lsp_types::TextDocumentSyncClientCapabilities;
use lsp_types::Url;
use lsp_types::WorkspaceClientCapabilities; use lsp_types::WorkspaceClientCapabilities;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use parking_lot::Condvar; use parking_lot::Condvar;
@ -47,10 +46,12 @@ use std::process::ChildStdin;
use std::process::ChildStdout; use std::process::ChildStdout;
use std::process::Command; use std::process::Command;
use std::process::Stdio; use std::process::Stdio;
use std::str::FromStr;
use std::sync::mpsc; use std::sync::mpsc;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use std::time::Instant; use std::time::Instant;
use url::Url;
static CONTENT_TYPE_REG: Lazy<Regex> = static CONTENT_TYPE_REG: Lazy<Regex> =
lazy_regex::lazy_regex!(r"(?i)^content-length:\s+(\d+)"); lazy_regex::lazy_regex!(r"(?i)^content-length:\s+(\d+)");
@ -234,7 +235,6 @@ impl InitializeParamsBuilder {
name: "test-harness".to_string(), name: "test-harness".to_string(),
version: Some("1.0.0".to_string()), version: Some("1.0.0".to_string()),
}), }),
root_uri: None,
initialization_options: Some(config_as_options), initialization_options: Some(config_as_options),
capabilities: ClientCapabilities { capabilities: ClientCapabilities {
text_document: Some(TextDocumentClientCapabilities { text_document: Some(TextDocumentClientCapabilities {
@ -289,8 +289,10 @@ impl InitializeParamsBuilder {
} }
} }
#[allow(deprecated)]
pub fn set_maybe_root_uri(&mut self, value: Option<Url>) -> &mut Self { pub fn set_maybe_root_uri(&mut self, value: Option<Url>) -> &mut Self {
self.params.root_uri = value; self.params.root_uri =
value.map(|v| lsp::Uri::from_str(v.as_str()).unwrap());
self self
} }
@ -871,7 +873,7 @@ impl LspClient {
mut config: Value, mut config: Value,
) { ) {
let mut builder = InitializeParamsBuilder::new(config.clone()); let mut builder = InitializeParamsBuilder::new(config.clone());
builder.set_root_uri(self.root_dir.uri_dir()); builder.set_root_uri(self.root_dir.url_dir());
do_build(&mut builder); do_build(&mut builder);
let params: InitializeParams = builder.build(); let params: InitializeParams = builder.build();
// `config` must be updated to account for the builder changes. // `config` must be updated to account for the builder changes.
@ -1234,7 +1236,7 @@ impl CollectedDiagnostics {
self self
.all_messages() .all_messages()
.iter() .iter()
.filter(|p| p.uri == *specifier) .filter(|p| p.uri.as_str() == specifier.as_str())
.flat_map(|p| p.diagnostics.iter()) .flat_map(|p| p.diagnostics.iter())
.cloned() .cloned()
.collect() .collect()
@ -1272,7 +1274,7 @@ impl CollectedDiagnostics {
.all_messages() .all_messages()
.iter() .iter()
.find(|p| { .find(|p| {
p.uri == specifier p.uri.as_str() == specifier.as_str()
&& p && p
.diagnostics .diagnostics
.iter() .iter()
@ -1323,7 +1325,11 @@ impl SourceFile {
range_of_nth(n, text, &self.src) range_of_nth(n, text, &self.src)
} }
pub fn uri(&self) -> lsp::Url { pub fn url(&self) -> Url {
self.path.url_file()
}
pub fn uri(&self) -> lsp::Uri {
self.path.uri_file() self.path.uri_file()
} }