summaryrefslogtreecommitdiff
path: root/cli/lsp/handlers.rs
blob: 69cdd8041f19120e585f777d56e9c58fafb5b92d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

use super::lsp_extensions;
use super::state::ServerState;
use super::state::ServerStateSnapshot;
use super::text;
use super::tsc;
use super::utils;

use deno_core::error::custom_error;
use deno_core::error::AnyError;
use deno_core::serde_json;
use deno_core::ModuleSpecifier;
use dprint_plugin_typescript as dprint;
use lsp_types::CompletionParams;
use lsp_types::CompletionResponse;
use lsp_types::DocumentFormattingParams;
use lsp_types::DocumentHighlight;
use lsp_types::DocumentHighlightParams;
use lsp_types::GotoDefinitionParams;
use lsp_types::GotoDefinitionResponse;
use lsp_types::Hover;
use lsp_types::HoverParams;
use lsp_types::Location;
use lsp_types::ReferenceParams;
use lsp_types::TextEdit;
use std::path::PathBuf;

fn get_line_index(
  state: &mut ServerState,
  specifier: &ModuleSpecifier,
) -> Result<Vec<u32>, AnyError> {
  let line_index = if specifier.as_url().scheme() == "asset" {
    let server_state = state.snapshot();
    if let Some(source) =
      tsc::get_asset(specifier, &mut state.ts_runtime, &server_state)?
    {
      text::index_lines(&source)
    } else {
      return Err(custom_error(
        "NotFound",
        format!("asset source missing: {}", specifier),
      ));
    }
  } else {
    let file_cache = state.file_cache.read().unwrap();
    if let Some(file_id) = file_cache.lookup(specifier) {
      let file_text = file_cache.get_contents(file_id)?;
      text::index_lines(&file_text)
    } else {
      let mut sources = state.sources.write().unwrap();
      if let Some(line_index) = sources.get_line_index(specifier) {
        line_index
      } else {
        return Err(custom_error(
          "NotFound",
          format!("source for specifier not found: {}", specifier),
        ));
      }
    }
  };
  Ok(line_index)
}

pub fn handle_formatting(
  state: ServerStateSnapshot,
  params: DocumentFormattingParams,
) -> Result<Option<Vec<TextEdit>>, AnyError> {
  let specifier = utils::normalize_url(params.text_document.uri.clone());
  let file_cache = state.file_cache.read().unwrap();
  let file_id = file_cache.lookup(&specifier).unwrap();
  let file_text = file_cache.get_contents(file_id)?;

  let file_path = if let Ok(file_path) = params.text_document.uri.to_file_path()
  {
    file_path
  } else {
    PathBuf::from(params.text_document.uri.path())
  };
  let config = dprint::configuration::ConfigurationBuilder::new()
    .deno()
    .build();

  // TODO(@kitsonk) this could be handled better in `cli/tools/fmt.rs` in the
  // future.
  let new_text = dprint::format_text(&file_path, &file_text, &config)
    .map_err(|e| custom_error("FormatError", e))?;

  let text_edits = text::get_edits(&file_text, &new_text);
  if text_edits.is_empty() {
    Ok(None)
  } else {
    Ok(Some(text_edits))
  }
}

pub fn handle_document_highlight(
  state: &mut ServerState,
  params: DocumentHighlightParams,
) -> Result<Option<Vec<DocumentHighlight>>, AnyError> {
  let specifier = utils::normalize_url(
    params.text_document_position_params.text_document.uri,
  );
  let line_index = get_line_index(state, &specifier)?;
  let server_state = state.snapshot();
  let files_to_search = vec![specifier.clone()];
  let maybe_document_highlights: Option<Vec<tsc::DocumentHighlights>> =
    serde_json::from_value(tsc::request(
      &mut state.ts_runtime,
      &server_state,
      tsc::RequestMethod::GetDocumentHighlights((
        specifier,
        text::to_char_pos(
          &line_index,
          params.text_document_position_params.position,
        ),
        files_to_search,
      )),
    )?)?;

  if let Some(document_highlights) = maybe_document_highlights {
    Ok(Some(
      document_highlights
        .into_iter()
        .map(|dh| dh.to_highlight(&line_index))
        .flatten()
        .collect(),
    ))
  } else {
    Ok(None)
  }
}

pub fn handle_goto_definition(
  state: &mut ServerState,
  params: GotoDefinitionParams,
) -> Result<Option<GotoDefinitionResponse>, AnyError> {
  let specifier = utils::normalize_url(
    params.text_document_position_params.text_document.uri,
  );
  let line_index = get_line_index(state, &specifier)?;
  let server_state = state.snapshot();
  let maybe_definition: Option<tsc::DefinitionInfoAndBoundSpan> =
    serde_json::from_value(tsc::request(
      &mut state.ts_runtime,
      &server_state,
      tsc::RequestMethod::GetDefinition((
        specifier,
        text::to_char_pos(
          &line_index,
          params.text_document_position_params.position,
        ),
      )),
    )?)?;

  if let Some(definition) = maybe_definition {
    Ok(
      definition
        .to_definition(&line_index, |s| get_line_index(state, &s).unwrap()),
    )
  } else {
    Ok(None)
  }
}

pub fn handle_hover(
  state: &mut ServerState,
  params: HoverParams,
) -> Result<Option<Hover>, AnyError> {
  let specifier = utils::normalize_url(
    params.text_document_position_params.text_document.uri,
  );
  let line_index = get_line_index(state, &specifier)?;
  let server_state = state.snapshot();
  let maybe_quick_info: Option<tsc::QuickInfo> =
    serde_json::from_value(tsc::request(
      &mut state.ts_runtime,
      &server_state,
      tsc::RequestMethod::GetQuickInfo((
        specifier,
        text::to_char_pos(
          &line_index,
          params.text_document_position_params.position,
        ),
      )),
    )?)?;

  if let Some(quick_info) = maybe_quick_info {
    Ok(Some(quick_info.to_hover(&line_index)))
  } else {
    Ok(None)
  }
}

pub fn handle_completion(
  state: &mut ServerState,
  params: CompletionParams,
) -> Result<Option<CompletionResponse>, AnyError> {
  let specifier =
    utils::normalize_url(params.text_document_position.text_document.uri);
  let line_index = get_line_index(state, &specifier)?;
  let server_state = state.snapshot();
  let maybe_completion_info: Option<tsc::CompletionInfo> =
    serde_json::from_value(tsc::request(
      &mut state.ts_runtime,
      &server_state,
      tsc::RequestMethod::GetCompletions((
        specifier,
        text::to_char_pos(&line_index, params.text_document_position.position),
        tsc::UserPreferences {
          // TODO(lucacasonato): enable this. see https://github.com/denoland/deno/pull/8651
          include_completions_with_insert_text: Some(false),
          ..Default::default()
        },
      )),
    )?)?;

  if let Some(completions) = maybe_completion_info {
    Ok(Some(completions.into_completion_response(&line_index)))
  } else {
    Ok(None)
  }
}

pub fn handle_references(
  state: &mut ServerState,
  params: ReferenceParams,
) -> Result<Option<Vec<Location>>, AnyError> {
  let specifier =
    utils::normalize_url(params.text_document_position.text_document.uri);
  let line_index = get_line_index(state, &specifier)?;
  let server_state = state.snapshot();
  let maybe_references: Option<Vec<tsc::ReferenceEntry>> =
    serde_json::from_value(tsc::request(
      &mut state.ts_runtime,
      &server_state,
      tsc::RequestMethod::GetReferences((
        specifier,
        text::to_char_pos(&line_index, params.text_document_position.position),
      )),
    )?)?;

  if let Some(references) = maybe_references {
    let mut results = Vec::new();
    for reference in references {
      if !params.context.include_declaration && reference.is_definition {
        continue;
      }
      let reference_specifier =
        ModuleSpecifier::resolve_url(&reference.file_name).unwrap();
      let line_index = get_line_index(state, &reference_specifier)?;
      results.push(reference.to_location(&line_index));
    }

    Ok(Some(results))
  } else {
    Ok(None)
  }
}

pub fn handle_virtual_text_document(
  state: &mut ServerState,
  params: lsp_extensions::VirtualTextDocumentParams,
) -> Result<String, AnyError> {
  let specifier = utils::normalize_url(params.text_document.uri);
  let url = specifier.as_url();
  let contents = if url.as_str() == "deno:///status.md" {
    let file_cache = state.file_cache.read().unwrap();
    format!(
      r#"# Deno Language Server Status

- Documents in memory: {}

"#,
      file_cache.len()
    )
  } else {
    match url.scheme() {
      "asset" => {
        let server_state = state.snapshot();
        if let Some(text) =
          tsc::get_asset(&specifier, &mut state.ts_runtime, &server_state)?
        {
          text
        } else {
          error!("Missing asset: {}", specifier);
          "".to_string()
        }
      }
      _ => {
        let mut sources = state.sources.write().unwrap();
        if let Some(text) = sources.get_text(&specifier) {
          text
        } else {
          return Err(custom_error(
            "NotFound",
            format!("The cached sources was not found: {}", specifier),
          ));
        }
      }
    }
  };
  Ok(contents)
}