aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
Diffstat (limited to 'crates')
-rw-r--r--crates/ra_ide_api/src/diagnostics.rs7
-rw-r--r--crates/ra_ide_api/src/lib.rs39
-rw-r--r--crates/ra_ide_api/src/matching_brace.rs45
-rw-r--r--crates/ra_ide_api/src/snapshots/tests__highlighting.snap34
-rw-r--r--crates/ra_ide_api/src/syntax_highlighting.rs81
-rw-r--r--crates/ra_ide_api/src/typing.rs (renamed from crates/ra_ide_api_light/src/typing.rs)80
-rw-r--r--crates/ra_ide_api_light/src/lib.rs140
-rw-r--r--crates/ra_ide_api_light/src/snapshots/tests__highlighting.snap32
8 files changed, 222 insertions, 236 deletions
diff --git a/crates/ra_ide_api/src/diagnostics.rs b/crates/ra_ide_api/src/diagnostics.rs
index e1c5a1b39..b9dc424c6 100644
--- a/crates/ra_ide_api/src/diagnostics.rs
+++ b/crates/ra_ide_api/src/diagnostics.rs
@@ -1,6 +1,5 @@
1use itertools::Itertools; 1use itertools::Itertools;
2use hir::{Problem, source_binder}; 2use hir::{Problem, source_binder};
3use ra_ide_api_light::Severity;
4use ra_db::SourceDatabase; 3use ra_db::SourceDatabase;
5use ra_syntax::{ 4use ra_syntax::{
6 Location, SourceFile, SyntaxKind, TextRange, SyntaxNode, 5 Location, SourceFile, SyntaxKind, TextRange, SyntaxNode,
@@ -11,6 +10,12 @@ use ra_text_edit::{TextEdit, TextEditBuilder};
11 10
12use crate::{Diagnostic, FileId, FileSystemEdit, SourceChange, SourceFileEdit, db::RootDatabase}; 11use crate::{Diagnostic, FileId, FileSystemEdit, SourceChange, SourceFileEdit, db::RootDatabase};
13 12
13#[derive(Debug, Copy, Clone)]
14pub enum Severity {
15 Error,
16 WeakWarning,
17}
18
14pub(crate) fn diagnostics(db: &RootDatabase, file_id: FileId) -> Vec<Diagnostic> { 19pub(crate) fn diagnostics(db: &RootDatabase, file_id: FileId) -> Vec<Diagnostic> {
15 let source_file = db.parse(file_id); 20 let source_file = db.parse(file_id);
16 let mut res = Vec::new(); 21 let mut res = Vec::new();
diff --git a/crates/ra_ide_api/src/lib.rs b/crates/ra_ide_api/src/lib.rs
index a838c30da..99f18b6b8 100644
--- a/crates/ra_ide_api/src/lib.rs
+++ b/crates/ra_ide_api/src/lib.rs
@@ -37,6 +37,8 @@ mod line_index;
37mod folding_ranges; 37mod folding_ranges;
38mod line_index_utils; 38mod line_index_utils;
39mod join_lines; 39mod join_lines;
40mod typing;
41mod matching_brace;
40 42
41#[cfg(test)] 43#[cfg(test)]
42mod marks; 44mod marks;
@@ -69,10 +71,10 @@ pub use crate::{
69 line_index::{LineIndex, LineCol}, 71 line_index::{LineIndex, LineCol},
70 line_index_utils::translate_offset_with_edit, 72 line_index_utils::translate_offset_with_edit,
71 folding_ranges::{Fold, FoldKind}, 73 folding_ranges::{Fold, FoldKind},
74 syntax_highlighting::HighlightedRange,
75 diagnostics::Severity,
72}; 76};
73pub use ra_ide_api_light::{ 77pub use ra_ide_api_light::StructureNode;
74 HighlightedRange, Severity, StructureNode, LocalEdit,
75};
76pub use ra_db::{ 78pub use ra_db::{
77 Canceled, CrateGraph, CrateId, FileId, FilePosition, FileRange, SourceRootId, 79 Canceled, CrateGraph, CrateId, FileId, FilePosition, FileRange, SourceRootId,
78 Edition 80 Edition
@@ -266,7 +268,7 @@ impl Analysis {
266 /// supported). 268 /// supported).
267 pub fn matching_brace(&self, position: FilePosition) -> Option<TextUnit> { 269 pub fn matching_brace(&self, position: FilePosition) -> Option<TextUnit> {
268 let file = self.db.parse(position.file_id); 270 let file = self.db.parse(position.file_id);
269 ra_ide_api_light::matching_brace(&file, position.offset) 271 matching_brace::matching_brace(&file, position.offset)
270 } 272 }
271 273
272 /// Returns a syntax tree represented as `String`, for debug purposes. 274 /// Returns a syntax tree represented as `String`, for debug purposes.
@@ -294,9 +296,7 @@ impl Analysis {
294 /// Returns an edit which should be applied when opening a new line, fixing 296 /// Returns an edit which should be applied when opening a new line, fixing
295 /// up minor stuff like continuing the comment. 297 /// up minor stuff like continuing the comment.
296 pub fn on_enter(&self, position: FilePosition) -> Option<SourceChange> { 298 pub fn on_enter(&self, position: FilePosition) -> Option<SourceChange> {
297 let file = self.db.parse(position.file_id); 299 typing::on_enter(&self.db, position)
298 let edit = ra_ide_api_light::on_enter(&file, position.offset)?;
299 Some(SourceChange::from_local_edit(position.file_id, edit))
300 } 300 }
301 301
302 /// Returns an edit which should be applied after `=` was typed. Primarily, 302 /// Returns an edit which should be applied after `=` was typed. Primarily,
@@ -304,15 +304,18 @@ impl Analysis {
304 // FIXME: use a snippet completion instead of this hack here. 304 // FIXME: use a snippet completion instead of this hack here.
305 pub fn on_eq_typed(&self, position: FilePosition) -> Option<SourceChange> { 305 pub fn on_eq_typed(&self, position: FilePosition) -> Option<SourceChange> {
306 let file = self.db.parse(position.file_id); 306 let file = self.db.parse(position.file_id);
307 let edit = ra_ide_api_light::on_eq_typed(&file, position.offset)?; 307 let edit = typing::on_eq_typed(&file, position.offset)?;
308 Some(SourceChange::from_local_edit(position.file_id, edit)) 308 Some(SourceChange {
309 label: "add semicolon".to_string(),
310 source_file_edits: vec![SourceFileEdit { edit, file_id: position.file_id }],
311 file_system_edits: vec![],
312 cursor_position: None,
313 })
309 } 314 }
310 315
311 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately. 316 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
312 pub fn on_dot_typed(&self, position: FilePosition) -> Option<SourceChange> { 317 pub fn on_dot_typed(&self, position: FilePosition) -> Option<SourceChange> {
313 let file = self.db.parse(position.file_id); 318 typing::on_dot_typed(&self.db, position)
314 let edit = ra_ide_api_light::on_dot_typed(&file, position.offset)?;
315 Some(SourceChange::from_local_edit(position.file_id, edit))
316 } 319 }
317 320
318 /// Returns a tree representation of symbols in the file. Useful to draw a 321 /// Returns a tree representation of symbols in the file. Useful to draw a
@@ -434,18 +437,6 @@ impl Analysis {
434 } 437 }
435} 438}
436 439
437impl SourceChange {
438 pub(crate) fn from_local_edit(file_id: FileId, edit: LocalEdit) -> SourceChange {
439 let file_edit = SourceFileEdit { file_id, edit: edit.edit };
440 SourceChange {
441 label: edit.label,
442 source_file_edits: vec![file_edit],
443 file_system_edits: vec![],
444 cursor_position: edit.cursor_position.map(|offset| FilePosition { offset, file_id }),
445 }
446 }
447}
448
449#[test] 440#[test]
450fn analysis_is_send() { 441fn analysis_is_send() {
451 fn is_send<T: Send>() {} 442 fn is_send<T: Send>() {}
diff --git a/crates/ra_ide_api/src/matching_brace.rs b/crates/ra_ide_api/src/matching_brace.rs
new file mode 100644
index 000000000..d1405f14f
--- /dev/null
+++ b/crates/ra_ide_api/src/matching_brace.rs
@@ -0,0 +1,45 @@
1use ra_syntax::{
2 SourceFile, TextUnit,
3 algo::find_leaf_at_offset,
4 SyntaxKind::{self, *},
5 ast::AstNode,
6};
7
8pub fn matching_brace(file: &SourceFile, offset: TextUnit) -> Option<TextUnit> {
9 const BRACES: &[SyntaxKind] =
10 &[L_CURLY, R_CURLY, L_BRACK, R_BRACK, L_PAREN, R_PAREN, L_ANGLE, R_ANGLE];
11 let (brace_node, brace_idx) = find_leaf_at_offset(file.syntax(), offset)
12 .filter_map(|node| {
13 let idx = BRACES.iter().position(|&brace| brace == node.kind())?;
14 Some((node, idx))
15 })
16 .next()?;
17 let parent = brace_node.parent()?;
18 let matching_kind = BRACES[brace_idx ^ 1];
19 let matching_node = parent.children().find(|node| node.kind() == matching_kind)?;
20 Some(matching_node.range().start())
21}
22
23#[cfg(test)]
24mod tests {
25 use test_utils::{add_cursor, assert_eq_text, extract_offset};
26
27 use super::*;
28
29 #[test]
30 fn test_matching_brace() {
31 fn do_check(before: &str, after: &str) {
32 let (pos, before) = extract_offset(before);
33 let file = SourceFile::parse(&before);
34 let new_pos = match matching_brace(&file, pos) {
35 None => pos,
36 Some(pos) => pos,
37 };
38 let actual = add_cursor(&before, new_pos);
39 assert_eq_text!(after, &actual);
40 }
41
42 do_check("struct Foo { a: i32, }<|>", "struct Foo <|>{ a: i32, }");
43 }
44
45}
diff --git a/crates/ra_ide_api/src/snapshots/tests__highlighting.snap b/crates/ra_ide_api/src/snapshots/tests__highlighting.snap
new file mode 100644
index 000000000..72029e0ed
--- /dev/null
+++ b/crates/ra_ide_api/src/snapshots/tests__highlighting.snap
@@ -0,0 +1,34 @@
1---
2created: "2019-03-23T16:20:31.394314144Z"
3creator: [email protected]
4source: crates/ra_ide_api/src/syntax_highlighting.rs
5expression: result
6---
7Ok(
8 [
9 HighlightedRange {
10 range: [1; 11),
11 tag: "comment"
12 },
13 HighlightedRange {
14 range: [12; 14),
15 tag: "keyword"
16 },
17 HighlightedRange {
18 range: [15; 19),
19 tag: "function"
20 },
21 HighlightedRange {
22 range: [29; 37),
23 tag: "macro"
24 },
25 HighlightedRange {
26 range: [38; 50),
27 tag: "string"
28 },
29 HighlightedRange {
30 range: [52; 54),
31 tag: "literal"
32 }
33 ]
34)
diff --git a/crates/ra_ide_api/src/syntax_highlighting.rs b/crates/ra_ide_api/src/syntax_highlighting.rs
index fdd87bcff..a0c5e78ad 100644
--- a/crates/ra_ide_api/src/syntax_highlighting.rs
+++ b/crates/ra_ide_api/src/syntax_highlighting.rs
@@ -1,12 +1,81 @@
1use ra_syntax::AstNode; 1use rustc_hash::FxHashSet;
2
3use ra_syntax::{ast, AstNode, TextRange, Direction, SyntaxKind::*};
2use ra_db::SourceDatabase; 4use ra_db::SourceDatabase;
3 5
4use crate::{ 6use crate::{FileId, db::RootDatabase};
5 FileId, HighlightedRange, 7
6 db::RootDatabase, 8#[derive(Debug)]
7}; 9pub struct HighlightedRange {
10 pub range: TextRange,
11 pub tag: &'static str,
12}
8 13
9pub(crate) fn highlight(db: &RootDatabase, file_id: FileId) -> Vec<HighlightedRange> { 14pub(crate) fn highlight(db: &RootDatabase, file_id: FileId) -> Vec<HighlightedRange> {
10 let source_file = db.parse(file_id); 15 let source_file = db.parse(file_id);
11 ra_ide_api_light::highlight(source_file.syntax()) 16
17 // Visited nodes to handle highlighting priorities
18 let mut highlighted = FxHashSet::default();
19 let mut res = Vec::new();
20 for node in source_file.syntax().descendants() {
21 if highlighted.contains(&node) {
22 continue;
23 }
24 let tag = match node.kind() {
25 COMMENT => "comment",
26 STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => "string",
27 ATTR => "attribute",
28 NAME_REF => "text",
29 NAME => "function",
30 INT_NUMBER | FLOAT_NUMBER | CHAR | BYTE => "literal",
31 LIFETIME => "parameter",
32 k if k.is_keyword() => "keyword",
33 _ => {
34 if let Some(macro_call) = ast::MacroCall::cast(node) {
35 if let Some(path) = macro_call.path() {
36 if let Some(segment) = path.segment() {
37 if let Some(name_ref) = segment.name_ref() {
38 highlighted.insert(name_ref.syntax());
39 let range_start = name_ref.syntax().range().start();
40 let mut range_end = name_ref.syntax().range().end();
41 for sibling in path.syntax().siblings(Direction::Next) {
42 match sibling.kind() {
43 EXCL | IDENT => range_end = sibling.range().end(),
44 _ => (),
45 }
46 }
47 res.push(HighlightedRange {
48 range: TextRange::from_to(range_start, range_end),
49 tag: "macro",
50 })
51 }
52 }
53 }
54 }
55 continue;
56 }
57 };
58 res.push(HighlightedRange { range: node.range(), tag })
59 }
60 res
61}
62
63#[cfg(test)]
64mod tests {
65 use insta::assert_debug_snapshot_matches;
66
67 use crate::mock_analysis::single_file;
68
69 #[test]
70 fn test_highlighting() {
71 let (analysis, file_id) = single_file(
72 r#"
73// comment
74fn main() {}
75 println!("Hello, {}!", 92);
76"#,
77 );
78 let result = analysis.highlight(file_id);
79 assert_debug_snapshot_matches!("highlighting", result);
80 }
12} 81}
diff --git a/crates/ra_ide_api_light/src/typing.rs b/crates/ra_ide_api/src/typing.rs
index c69270333..94b228466 100644
--- a/crates/ra_ide_api_light/src/typing.rs
+++ b/crates/ra_ide_api/src/typing.rs
@@ -5,30 +5,37 @@ use ra_syntax::{
5 ast::{self, AstToken}, 5 ast::{self, AstToken},
6}; 6};
7use ra_fmt::leading_indent; 7use ra_fmt::leading_indent;
8use crate::{LocalEdit, TextEditBuilder}; 8use ra_text_edit::{TextEdit, TextEditBuilder};
9use ra_db::{FilePosition, SourceDatabase};
10use crate::{db::RootDatabase, SourceChange, SourceFileEdit};
9 11
10pub fn on_enter(file: &SourceFile, offset: TextUnit) -> Option<LocalEdit> { 12pub(crate) fn on_enter(db: &RootDatabase, position: FilePosition) -> Option<SourceChange> {
11 let comment = 13 let file = db.parse(position.file_id);
12 find_leaf_at_offset(file.syntax(), offset).left_biased().and_then(ast::Comment::cast)?; 14 let comment = find_leaf_at_offset(file.syntax(), position.offset)
15 .left_biased()
16 .and_then(ast::Comment::cast)?;
13 17
14 if let ast::CommentFlavor::Multiline = comment.flavor() { 18 if let ast::CommentFlavor::Multiline = comment.flavor() {
15 return None; 19 return None;
16 } 20 }
17 21
18 let prefix = comment.prefix(); 22 let prefix = comment.prefix();
19 if offset < comment.syntax().range().start() + TextUnit::of_str(prefix) + TextUnit::from(1) { 23 if position.offset
24 < comment.syntax().range().start() + TextUnit::of_str(prefix) + TextUnit::from(1)
25 {
20 return None; 26 return None;
21 } 27 }
22 28
23 let indent = node_indent(file, comment.syntax())?; 29 let indent = node_indent(&file, comment.syntax())?;
24 let inserted = format!("\n{}{} ", indent, prefix); 30 let inserted = format!("\n{}{} ", indent, prefix);
25 let cursor_position = offset + TextUnit::of_str(&inserted); 31 let cursor_position = position.offset + TextUnit::of_str(&inserted);
26 let mut edit = TextEditBuilder::default(); 32 let mut edit = TextEditBuilder::default();
27 edit.insert(offset, inserted); 33 edit.insert(position.offset, inserted);
28 Some(LocalEdit { 34 Some(SourceChange {
29 label: "on enter".to_string(), 35 label: "on enter".to_string(),
30 edit: edit.finish(), 36 source_file_edits: vec![SourceFileEdit { edit: edit.finish(), file_id: position.file_id }],
31 cursor_position: Some(cursor_position), 37 file_system_edits: vec![],
38 cursor_position: Some(FilePosition { offset: cursor_position, file_id: position.file_id }),
32 }) 39 })
33} 40}
34 41
@@ -52,7 +59,7 @@ fn node_indent<'a>(file: &'a SourceFile, node: &SyntaxNode) -> Option<&'a str> {
52 Some(&text[pos..]) 59 Some(&text[pos..])
53} 60}
54 61
55pub fn on_eq_typed(file: &SourceFile, eq_offset: TextUnit) -> Option<LocalEdit> { 62pub fn on_eq_typed(file: &SourceFile, eq_offset: TextUnit) -> Option<TextEdit> {
56 assert_eq!(file.syntax().text().char_at(eq_offset), Some('=')); 63 assert_eq!(file.syntax().text().char_at(eq_offset), Some('='));
57 let let_stmt: &ast::LetStmt = find_node_at_offset(file.syntax(), eq_offset)?; 64 let let_stmt: &ast::LetStmt = find_node_at_offset(file.syntax(), eq_offset)?;
58 if let_stmt.has_semi() { 65 if let_stmt.has_semi() {
@@ -72,17 +79,14 @@ pub fn on_eq_typed(file: &SourceFile, eq_offset: TextUnit) -> Option<LocalEdit>
72 let offset = let_stmt.syntax().range().end(); 79 let offset = let_stmt.syntax().range().end();
73 let mut edit = TextEditBuilder::default(); 80 let mut edit = TextEditBuilder::default();
74 edit.insert(offset, ";".to_string()); 81 edit.insert(offset, ";".to_string());
75 Some(LocalEdit { 82 Some(edit.finish())
76 label: "add semicolon".to_string(),
77 edit: edit.finish(),
78 cursor_position: None,
79 })
80} 83}
81 84
82pub fn on_dot_typed(file: &SourceFile, dot_offset: TextUnit) -> Option<LocalEdit> { 85pub(crate) fn on_dot_typed(db: &RootDatabase, position: FilePosition) -> Option<SourceChange> {
83 assert_eq!(file.syntax().text().char_at(dot_offset), Some('.')); 86 let file = db.parse(position.file_id);
87 assert_eq!(file.syntax().text().char_at(position.offset), Some('.'));
84 88
85 let whitespace = find_leaf_at_offset(file.syntax(), dot_offset) 89 let whitespace = find_leaf_at_offset(file.syntax(), position.offset)
86 .left_biased() 90 .left_biased()
87 .and_then(ast::Whitespace::cast)?; 91 .and_then(ast::Whitespace::cast)?;
88 92
@@ -103,15 +107,18 @@ pub fn on_dot_typed(file: &SourceFile, dot_offset: TextUnit) -> Option<LocalEdit
103 } 107 }
104 let mut edit = TextEditBuilder::default(); 108 let mut edit = TextEditBuilder::default();
105 edit.replace( 109 edit.replace(
106 TextRange::from_to(dot_offset - current_indent_len, dot_offset), 110 TextRange::from_to(position.offset - current_indent_len, position.offset),
107 target_indent.into(), 111 target_indent.into(),
108 ); 112 );
109 let res = LocalEdit { 113 let res = SourceChange {
110 label: "reindent dot".to_string(), 114 label: "reindent dot".to_string(),
111 edit: edit.finish(), 115 source_file_edits: vec![SourceFileEdit { edit: edit.finish(), file_id: position.file_id }],
112 cursor_position: Some( 116 file_system_edits: vec![],
113 dot_offset + target_indent_len - current_indent_len + TextUnit::of_char('.'), 117 cursor_position: Some(FilePosition {
114 ), 118 offset: position.offset + target_indent_len - current_indent_len
119 + TextUnit::of_char('.'),
120 file_id: position.file_id,
121 }),
115 }; 122 };
116 Some(res) 123 Some(res)
117} 124}
@@ -120,6 +127,8 @@ pub fn on_dot_typed(file: &SourceFile, dot_offset: TextUnit) -> Option<LocalEdit
120mod tests { 127mod tests {
121 use test_utils::{add_cursor, assert_eq_text, extract_offset}; 128 use test_utils::{add_cursor, assert_eq_text, extract_offset};
122 129
130 use crate::mock_analysis::single_file;
131
123 use super::*; 132 use super::*;
124 133
125 #[test] 134 #[test]
@@ -131,7 +140,7 @@ mod tests {
131 let before = edit.finish().apply(&before); 140 let before = edit.finish().apply(&before);
132 let file = SourceFile::parse(&before); 141 let file = SourceFile::parse(&before);
133 if let Some(result) = on_eq_typed(&file, offset) { 142 if let Some(result) = on_eq_typed(&file, offset) {
134 let actual = result.edit.apply(&before); 143 let actual = result.apply(&before);
135 assert_eq_text!(after, &actual); 144 assert_eq_text!(after, &actual);
136 } else { 145 } else {
137 assert_eq_text!(&before, after) 146 assert_eq_text!(&before, after)
@@ -177,9 +186,10 @@ fn foo() {
177 let mut edit = TextEditBuilder::default(); 186 let mut edit = TextEditBuilder::default();
178 edit.insert(offset, ".".to_string()); 187 edit.insert(offset, ".".to_string());
179 let before = edit.finish().apply(&before); 188 let before = edit.finish().apply(&before);
180 let file = SourceFile::parse(&before); 189 let (analysis, file_id) = single_file(&before);
181 if let Some(result) = on_dot_typed(&file, offset) { 190 if let Some(result) = analysis.on_dot_typed(FilePosition { offset, file_id }) {
182 let actual = result.edit.apply(&before); 191 assert_eq!(result.source_file_edits.len(), 1);
192 let actual = result.source_file_edits[0].edit.apply(&before);
183 assert_eq_text!(after, &actual); 193 assert_eq_text!(after, &actual);
184 } else { 194 } else {
185 assert_eq_text!(&before, after) 195 assert_eq_text!(&before, after)
@@ -358,10 +368,12 @@ fn foo() {
358 fn test_on_enter() { 368 fn test_on_enter() {
359 fn apply_on_enter(before: &str) -> Option<String> { 369 fn apply_on_enter(before: &str) -> Option<String> {
360 let (offset, before) = extract_offset(before); 370 let (offset, before) = extract_offset(before);
361 let file = SourceFile::parse(&before); 371 let (analysis, file_id) = single_file(&before);
362 let result = on_enter(&file, offset)?; 372 let result = analysis.on_enter(FilePosition { offset, file_id })?;
363 let actual = result.edit.apply(&before); 373
364 let actual = add_cursor(&actual, result.cursor_position.unwrap()); 374 assert_eq!(result.source_file_edits.len(), 1);
375 let actual = result.source_file_edits[0].edit.apply(&before);
376 let actual = add_cursor(&actual, result.cursor_position.unwrap().offset);
365 Some(actual) 377 Some(actual)
366 } 378 }
367 379
diff --git a/crates/ra_ide_api_light/src/lib.rs b/crates/ra_ide_api_light/src/lib.rs
index f21a91e18..df7f144b6 100644
--- a/crates/ra_ide_api_light/src/lib.rs
+++ b/crates/ra_ide_api_light/src/lib.rs
@@ -4,147 +4,9 @@
4//! an edit or some auxiliary info. 4//! an edit or some auxiliary info.
5 5
6mod structure; 6mod structure;
7mod typing;
8 7
9use rustc_hash::FxHashSet; 8use ra_syntax::TextRange;
10use ra_text_edit::TextEditBuilder;
11use ra_syntax::{
12 SourceFile, SyntaxNode, TextRange, TextUnit, Direction,
13 algo::find_leaf_at_offset,
14 SyntaxKind::{self, *},
15 ast::{self, AstNode},
16};
17 9
18pub use crate::{ 10pub use crate::{
19 structure::{file_structure, StructureNode}, 11 structure::{file_structure, StructureNode},
20 typing::{on_enter, on_dot_typed, on_eq_typed},
21}; 12};
22
23#[derive(Debug)]
24pub struct LocalEdit {
25 pub label: String,
26 pub edit: ra_text_edit::TextEdit,
27 pub cursor_position: Option<TextUnit>,
28}
29
30#[derive(Debug)]
31pub struct HighlightedRange {
32 pub range: TextRange,
33 pub tag: &'static str,
34}
35
36#[derive(Debug, Copy, Clone)]
37pub enum Severity {
38 Error,
39 WeakWarning,
40}
41
42#[derive(Debug)]
43pub struct Diagnostic {
44 pub range: TextRange,
45 pub msg: String,
46 pub severity: Severity,
47 pub fix: Option<LocalEdit>,
48}
49
50pub fn matching_brace(file: &SourceFile, offset: TextUnit) -> Option<TextUnit> {
51 const BRACES: &[SyntaxKind] =
52 &[L_CURLY, R_CURLY, L_BRACK, R_BRACK, L_PAREN, R_PAREN, L_ANGLE, R_ANGLE];
53 let (brace_node, brace_idx) = find_leaf_at_offset(file.syntax(), offset)
54 .filter_map(|node| {
55 let idx = BRACES.iter().position(|&brace| brace == node.kind())?;
56 Some((node, idx))
57 })
58 .next()?;
59 let parent = brace_node.parent()?;
60 let matching_kind = BRACES[brace_idx ^ 1];
61 let matching_node = parent.children().find(|node| node.kind() == matching_kind)?;
62 Some(matching_node.range().start())
63}
64
65pub fn highlight(root: &SyntaxNode) -> Vec<HighlightedRange> {
66 // Visited nodes to handle highlighting priorities
67 let mut highlighted = FxHashSet::default();
68 let mut res = Vec::new();
69 for node in root.descendants() {
70 if highlighted.contains(&node) {
71 continue;
72 }
73 let tag = match node.kind() {
74 COMMENT => "comment",
75 STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => "string",
76 ATTR => "attribute",
77 NAME_REF => "text",
78 NAME => "function",
79 INT_NUMBER | FLOAT_NUMBER | CHAR | BYTE => "literal",
80 LIFETIME => "parameter",
81 k if k.is_keyword() => "keyword",
82 _ => {
83 if let Some(macro_call) = ast::MacroCall::cast(node) {
84 if let Some(path) = macro_call.path() {
85 if let Some(segment) = path.segment() {
86 if let Some(name_ref) = segment.name_ref() {
87 highlighted.insert(name_ref.syntax());
88 let range_start = name_ref.syntax().range().start();
89 let mut range_end = name_ref.syntax().range().end();
90 for sibling in path.syntax().siblings(Direction::Next) {
91 match sibling.kind() {
92 EXCL | IDENT => range_end = sibling.range().end(),
93 _ => (),
94 }
95 }
96 res.push(HighlightedRange {
97 range: TextRange::from_to(range_start, range_end),
98 tag: "macro",
99 })
100 }
101 }
102 }
103 }
104 continue;
105 }
106 };
107 res.push(HighlightedRange { range: node.range(), tag })
108 }
109 res
110}
111
112#[cfg(test)]
113mod tests {
114 use ra_syntax::AstNode;
115 use insta::assert_debug_snapshot_matches;
116
117 use test_utils::{add_cursor, assert_eq_text, extract_offset};
118
119 use super::*;
120
121 #[test]
122 fn test_highlighting() {
123 let file = SourceFile::parse(
124 r#"
125// comment
126fn main() {}
127 println!("Hello, {}!", 92);
128"#,
129 );
130 let hls = highlight(file.syntax());
131 assert_debug_snapshot_matches!("highlighting", hls);
132 }
133
134 #[test]
135 fn test_matching_brace() {
136 fn do_check(before: &str, after: &str) {
137 let (pos, before) = extract_offset(before);
138 let file = SourceFile::parse(&before);
139 let new_pos = match matching_brace(&file, pos) {
140 None => pos,
141 Some(pos) => pos,
142 };
143 let actual = add_cursor(&before, new_pos);
144 assert_eq_text!(after, &actual);
145 }
146
147 do_check("struct Foo { a: i32, }<|>", "struct Foo <|>{ a: i32, }");
148 }
149
150}
diff --git a/crates/ra_ide_api_light/src/snapshots/tests__highlighting.snap b/crates/ra_ide_api_light/src/snapshots/tests__highlighting.snap
deleted file mode 100644
index ef306a7a0..000000000
--- a/crates/ra_ide_api_light/src/snapshots/tests__highlighting.snap
+++ /dev/null
@@ -1,32 +0,0 @@
1---
2created: "2019-01-22T14:45:01.959724300+00:00"
3creator: [email protected]
4expression: hls
5source: "crates\\ra_ide_api_light\\src\\lib.rs"
6---
7[
8 HighlightedRange {
9 range: [1; 11),
10 tag: "comment"
11 },
12 HighlightedRange {
13 range: [12; 14),
14 tag: "keyword"
15 },
16 HighlightedRange {
17 range: [15; 19),
18 tag: "function"
19 },
20 HighlightedRange {
21 range: [29; 37),
22 tag: "macro"
23 },
24 HighlightedRange {
25 range: [38; 50),
26 tag: "string"
27 },
28 HighlightedRange {
29 range: [52; 54),
30 tag: "literal"
31 }
32]