Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(lsp): add registry import auto-complete #9934

Merged
merged 14 commits into from
Apr 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ dprint-plugin-markdown = "0.6.2"
dprint-plugin-typescript = "0.41.0"
encoding_rs = "0.8.28"
env_logger = "0.8.3"
fancy-regex = "0.5.0"
filetime = "0.2.14"
http = "0.2.3"
indexmap = { version = "1.6.2", features = ["serde"] }
Expand Down
4 changes: 2 additions & 2 deletions cli/file_fetcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub struct File {

/// Simple struct implementing in-process caching to prevent multiple
/// fs reads/net fetches for same file.
#[derive(Clone, Default)]
#[derive(Debug, Clone, Default)]
struct FileCache(Arc<Mutex<HashMap<ModuleSpecifier, File>>>);

impl FileCache {
Expand Down Expand Up @@ -312,7 +312,7 @@ fn strip_shebang(mut value: String) -> String {
}

/// A structure for resolving, fetching and caching source files.
#[derive(Clone)]
#[derive(Debug, Clone)]
pub struct FileFetcher {
auth_tokens: AuthTokens,
allow_remote: bool,
Expand Down
4 changes: 4 additions & 0 deletions cli/lsp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ with Deno:
- `deno/performance` - Requests the return of the timing averages for the
internal instrumentation of Deno.

It does not expect any parameters.
- `deno/reloadImportRegistries` - Reloads any cached responses from import
registries.

It does not expect any parameters.
- `deno/virtualTextDocument` - Requests a virtual text document from the LSP,
which is a read only document that can be displayed in the client. This allows
Expand Down
55 changes: 46 additions & 9 deletions cli/lsp/completions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use swc_ecmascript::visit::VisitWith;

const CURRENT_PATH: &str = ".";
const PARENT_PATH: &str = "..";
const LOCAL_PATHS: &[&str] = &[CURRENT_PATH, PARENT_PATH];

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
Expand All @@ -36,7 +37,7 @@ pub struct CompletionItemData {
/// Given a specifier, a position, and a snapshot, optionally return a
/// completion response, which will be valid import completions for the specific
/// context.
pub fn get_import_completions(
pub async fn get_import_completions(
specifier: &ModuleSpecifier,
position: &lsp::Position,
state_snapshot: &language_server::StateSnapshot,
Expand All @@ -55,17 +56,52 @@ pub fn get_import_completions(
items: get_local_completions(specifier, &current_specifier, &range)?,
}));
}
// completion of modules within the workspace
// completion of modules from a module registry or cache
if !current_specifier.is_empty() {
return Some(lsp::CompletionResponse::List(lsp::CompletionList {
is_incomplete: false,
items: get_workspace_completions(
let offset = if position.character > range.start.character {
(position.character - range.start.character) as usize
} else {
0
};
let maybe_items = state_snapshot
.module_registries
.get_completions(&current_specifier, offset, &range, state_snapshot)
.await;
let items = maybe_items.unwrap_or_else(|| {
get_workspace_completions(
specifier,
&current_specifier,
&range,
state_snapshot,
),
)
});
return Some(lsp::CompletionResponse::List(lsp::CompletionList {
is_incomplete: false,
items,
}));
} else {
let mut items: Vec<lsp::CompletionItem> = LOCAL_PATHS
.iter()
.map(|s| lsp::CompletionItem {
label: s.to_string(),
kind: Some(lsp::CompletionItemKind::Folder),
detail: Some("(local)".to_string()),
sort_text: Some("1".to_string()),
insert_text: Some(s.to_string()),
..Default::default()
})
.collect();
if let Some(origin_items) = state_snapshot
.module_registries
.get_origin_completions(&current_specifier, &range)
{
items.extend(origin_items);
}
return Some(lsp::CompletionResponse::List(lsp::CompletionList {
is_incomplete: false,
items,
}));
// TODO(@kitsonk) add bare specifiers from import map
}
}
}
Expand Down Expand Up @@ -738,8 +774,8 @@ mod tests {
}
}

#[test]
fn test_get_import_completions() {
#[tokio::test]
async fn test_get_import_completions() {
let specifier = resolve_url("file:///a/b/c.ts").unwrap();
let position = lsp::Position {
line: 0,
Expand All @@ -752,7 +788,8 @@ mod tests {
],
&[("https://deno.land/x/a/b/c.ts", "console.log(1);\n")],
);
let actual = get_import_completions(&specifier, &position, &state_snapshot);
let actual =
get_import_completions(&specifier, &position, &state_snapshot).await;
assert_eq!(
actual,
Some(lsp::CompletionResponse::List(lsp::CompletionList {
Expand Down
19 changes: 19 additions & 0 deletions cli/lsp/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use deno_core::url::Url;
use lspower::jsonrpc::Error as LSPError;
use lspower::jsonrpc::Result as LSPResult;
use lspower::lsp;
use std::collections::HashMap;

#[derive(Debug, Clone, Default)]
pub struct ClientCapabilities {
Expand Down Expand Up @@ -52,6 +53,8 @@ pub struct CompletionSettings {
pub paths: bool,
#[serde(default)]
pub auto_imports: bool,
#[serde(default)]
pub imports: ImportCompletionSettings,
}

impl Default for CompletionSettings {
Expand All @@ -61,6 +64,22 @@ impl Default for CompletionSettings {
names: true,
paths: true,
auto_imports: true,
imports: ImportCompletionSettings::default(),
}
}
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ImportCompletionSettings {
#[serde(default)]
pub hosts: HashMap<String, bool>,
}

impl Default for ImportCompletionSettings {
fn default() -> Self {
Self {
hosts: HashMap::default(),
}
}
}
Expand Down
Loading