Skip to content

Commit 63dbff8

Browse files
Merge pull request #3 from JasperDeSutter/more-functionality
More demo functionality
2 parents 6134d03 + 8b2dcb2 commit 63dbff8

File tree

4 files changed

+199
-20
lines changed

4 files changed

+199
-20
lines changed

wasm-demo/src/conv.rs

Lines changed: 87 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use super::return_types;
22
use ra_ide_api::{
3-
CompletionItem, CompletionItemKind, FileId, FilePosition, InsertTextFormat, LineCol, LineIndex,
3+
CompletionItem, CompletionItemKind, Documentation, FileId, FilePosition, FunctionSignature,
4+
InsertTextFormat, LineCol, LineIndex, NavigationTarget, RangeInfo, Severity,
45
};
56
use ra_syntax::TextRange;
67
use ra_text_edit::AtomTextEdit;
@@ -50,7 +51,7 @@ impl ConvWith<&LineIndex> for TextRange {
5051
impl Conv for CompletionItemKind {
5152
type Output = return_types::CompletionItemKind;
5253

53-
fn conv(self) -> <Self as Conv>::Output {
54+
fn conv(self) -> Self::Output {
5455
use return_types::CompletionItemKind::*;
5556
match self {
5657
CompletionItemKind::Keyword => Keyword,
@@ -74,6 +75,17 @@ impl Conv for CompletionItemKind {
7475
}
7576
}
7677

78+
impl Conv for Severity {
79+
type Output = return_types::MarkerSeverity;
80+
81+
fn conv(self) -> Self::Output {
82+
match self {
83+
Severity::Error => return_types::MarkerSeverity::Error,
84+
Severity::WeakWarning => return_types::MarkerSeverity::Hint,
85+
}
86+
}
87+
}
88+
7789
impl ConvWith<&LineIndex> for &AtomTextEdit {
7890
type Output = return_types::TextEdit;
7991

@@ -124,11 +136,81 @@ impl ConvWith<&LineIndex> for CompletionItem {
124136
return_types::CompletionItemInsertTextRule::InsertAsSnippet
125137
}
126138
},
127-
documentation: self
128-
.documentation()
129-
.map(|doc| return_types::MarkdownString { value: doc.as_str().to_string() }),
139+
documentation: self.documentation().map(|doc| doc.conv()),
130140
filterText: self.lookup().to_string(),
131141
additionalTextEdits: additional_text_edits,
132142
}
133143
}
134144
}
145+
146+
impl Conv for Documentation {
147+
type Output = return_types::MarkdownString;
148+
fn conv(self) -> Self::Output {
149+
fn code_line_ignored_by_rustdoc(line: &str) -> bool {
150+
let trimmed = line.trim();
151+
trimmed == "#" || trimmed.starts_with("# ") || trimmed.starts_with("#\t")
152+
}
153+
154+
let mut processed_lines = Vec::new();
155+
let mut in_code_block = false;
156+
for line in self.as_str().lines() {
157+
if in_code_block && code_line_ignored_by_rustdoc(line) {
158+
continue;
159+
}
160+
161+
if line.starts_with("```") {
162+
in_code_block ^= true
163+
}
164+
165+
let line = if in_code_block && line.starts_with("```") && !line.contains("rust") {
166+
"```rust"
167+
} else {
168+
line
169+
};
170+
171+
processed_lines.push(line);
172+
}
173+
174+
return_types::MarkdownString { value: processed_lines.join("\n") }
175+
}
176+
}
177+
178+
impl Conv for FunctionSignature {
179+
type Output = return_types::SignatureInformation;
180+
fn conv(self) -> Self::Output {
181+
use return_types::{ParameterInformation, SignatureInformation};
182+
183+
let label = self.to_string();
184+
let documentation = self.doc.map(|it| it.conv());
185+
186+
let parameters: Vec<ParameterInformation> = self
187+
.parameters
188+
.into_iter()
189+
.map(|param| ParameterInformation { label: param })
190+
.collect();
191+
192+
SignatureInformation { label, documentation, parameters }
193+
}
194+
}
195+
196+
impl ConvWith<&LineIndex> for RangeInfo<Vec<NavigationTarget>> {
197+
type Output = Vec<return_types::LocationLink>;
198+
fn conv_with(self, line_index: &LineIndex) -> Self::Output {
199+
let selection = self.range.conv_with(&line_index);
200+
self.info
201+
.into_iter()
202+
.map(|nav| {
203+
let range = nav.full_range().conv_with(&line_index);
204+
205+
let target_selection_range =
206+
nav.focus_range().map(|it| it.conv_with(&line_index)).unwrap_or(range);
207+
208+
return_types::LocationLink {
209+
originSelectionRange: selection,
210+
range,
211+
targetSelectionRange: target_selection_range,
212+
}
213+
})
214+
.collect()
215+
}
216+
}

wasm-demo/src/lib.rs

Lines changed: 51 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#![cfg(target_arch = "wasm32")]
22
#![allow(non_snake_case)]
33

4-
use ra_ide_api::{Analysis, FileId, FilePosition, Severity};
4+
use ra_ide_api::{Analysis, FileId, FilePosition};
55
use ra_syntax::SyntaxKind;
66
use wasm_bindgen::prelude::*;
77

@@ -57,10 +57,7 @@ impl WorldState {
5757
d.range.conv_with(&line_index);
5858
Diagnostic {
5959
message: d.message,
60-
severity: match d.severity {
61-
Severity::Error => 8, // monaco MarkerSeverity.Error
62-
Severity::WeakWarning => 1, // monaco MarkerSeverity.Hint
63-
},
60+
severity: d.severity.conv(),
6461
startLineNumber,
6562
startColumn,
6663
endLineNumber,
@@ -199,12 +196,57 @@ impl WorldState {
199196
.source_file_edits
200197
.iter()
201198
.flat_map(|sfe| sfe.edit.as_atoms())
202-
.map(|atom| TextEdit {
203-
range: atom.delete.conv_with(&line_index),
204-
text: atom.insert.clone(),
205-
})
199+
.map(|atom| atom.conv_with(&line_index))
206200
.collect();
207201

208202
serde_wasm_bindgen::to_value(&result).unwrap()
209203
}
204+
205+
pub fn signature_help(&self, line_number: u32, column: u32) -> JsValue {
206+
log::warn!("signature_help");
207+
let line_index = self.analysis.file_line_index(self.file_id).unwrap();
208+
209+
let pos = Position { line_number, column }.conv_with((&line_index, self.file_id));
210+
let call_info = match self.analysis.call_info(pos) {
211+
Ok(Some(call_info)) => call_info,
212+
_ => return JsValue::NULL,
213+
};
214+
215+
let sig_info = call_info.signature.conv();
216+
217+
let result = SignatureHelp {
218+
signatures: [sig_info],
219+
activeSignature: 0,
220+
activeParameter: call_info.active_parameter,
221+
};
222+
serde_wasm_bindgen::to_value(&result).unwrap()
223+
}
224+
225+
pub fn definition(&self, line_number: u32, column: u32) -> JsValue {
226+
log::warn!("definition");
227+
let line_index = self.analysis.file_line_index(self.file_id).unwrap();
228+
229+
let pos = Position { line_number, column }.conv_with((&line_index, self.file_id));
230+
let nav_info = match self.analysis.goto_definition(pos) {
231+
Ok(Some(nav_info)) => nav_info,
232+
_ => return JsValue::NULL,
233+
};
234+
235+
let res = nav_info.conv_with(&line_index);
236+
serde_wasm_bindgen::to_value(&res).unwrap()
237+
}
238+
239+
pub fn type_definition(&self, line_number: u32, column: u32) -> JsValue {
240+
log::warn!("type_definition");
241+
let line_index = self.analysis.file_line_index(self.file_id).unwrap();
242+
243+
let pos = Position { line_number, column }.conv_with((&line_index, self.file_id));
244+
let nav_info = match self.analysis.goto_type_definition(pos) {
245+
Ok(Some(nav_info)) => nav_info,
246+
_ => return JsValue::NULL,
247+
};
248+
249+
let res = nav_info.conv_with(&line_index);
250+
serde_wasm_bindgen::to_value(&res).unwrap()
251+
}
210252
}

wasm-demo/src/return_types.rs

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,17 @@ pub struct Diagnostic {
5858
pub startColumn: u32,
5959
pub endLineNumber: u32,
6060
pub endColumn: u32,
61-
pub severity: u32,
61+
pub severity: MarkerSeverity,
62+
}
63+
64+
#[allow(dead_code)]
65+
#[derive(Serialize_repr)]
66+
#[repr(u8)]
67+
pub enum MarkerSeverity {
68+
Hint = 1,
69+
Info = 2,
70+
Warning = 4,
71+
Error = 8,
6272
}
6373

6474
#[derive(Serialize)]
@@ -127,3 +137,29 @@ pub enum CompletionItemInsertTextRule {
127137
*/
128138
InsertAsSnippet = 4,
129139
}
140+
141+
#[derive(Serialize)]
142+
pub struct ParameterInformation {
143+
pub label: String,
144+
}
145+
146+
#[derive(Serialize)]
147+
pub struct SignatureInformation {
148+
pub label: String,
149+
pub documentation: Option<MarkdownString>,
150+
pub parameters: Vec<ParameterInformation>,
151+
}
152+
153+
#[derive(Serialize)]
154+
pub struct SignatureHelp {
155+
pub signatures: [SignatureInformation; 1],
156+
pub activeSignature: u32,
157+
pub activeParameter: Option<usize>,
158+
}
159+
160+
#[derive(Serialize)]
161+
pub struct LocationLink {
162+
pub originSelectionRange: Range,
163+
pub range: Range,
164+
pub targetSelectionRange: Range,
165+
}

wasm-demo/www/index.js

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,8 @@ import encoding from 'text-encoding';
5353

5454
if (typeof TextEncoder === "undefined") {
5555
// Edge polyfill, https://rustwasm.github.io/docs/wasm-bindgen/reference/browser-support.html
56-
self.TextEncoder = encoding.TextEncoder
57-
self.TextDecoder = encoding.TextDecoder
56+
self.TextEncoder = encoding.TextEncoder;
57+
self.TextDecoder = encoding.TextDecoder;
5858
}
5959

6060
import './index.css';
@@ -118,7 +118,7 @@ monaco.languages.onLanguage(modeId, async () => {
118118
position,
119119
references,
120120
],
121-
}
121+
},
122122
};
123123
});
124124

@@ -147,10 +147,29 @@ monaco.languages.onLanguage(modeId, async () => {
147147
monaco.languages.registerCompletionItemProvider(modeId, {
148148
triggerCharacters: [".", ":", "="],
149149
provideCompletionItems(m, pos) {
150-
const suggestions = state.completions(pos.lineNumber, pos.column)
151-
return { suggestions }
150+
const suggestions = state.completions(pos.lineNumber, pos.column);
151+
return { suggestions };
152152
},
153153
});
154+
monaco.languages.registerSignatureHelpProvider(modeId, {
155+
signatureHelpTriggerCharacters: ['(', ','],
156+
provideSignatureHelp(m, pos) {
157+
const value = state.signature_help(pos.lineNumber, pos.column);
158+
if (!value) return null;
159+
return {
160+
value,
161+
dispose() { },
162+
};
163+
},
164+
});
165+
monaco.languages.registerDefinitionProvider(modeId, {
166+
provideDefinition: (m, pos) => state.definition(pos.lineNumber, pos.column)
167+
.map(def => ({ ...def, uri: m.uri })),
168+
});
169+
monaco.languages.registerTypeDefinitionProvider(modeId, {
170+
provideTypeDefinition: (m, pos) => state.type_definition(pos.lineNumber, pos.column)
171+
.map(def => ({ ...def, uri: m.uri })),
172+
});
154173

155174
class TokenState {
156175
constructor(line = 0) {

0 commit comments

Comments
 (0)