]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/syntax_highlighting/inject.rs
Merge #9655
[rust.git] / crates / ide / src / syntax_highlighting / inject.rs
1 //! "Recursive" Syntax highlighting for code in doctests and fixtures.
2
3 use std::mem;
4
5 use either::Either;
6 use hir::{InFile, Semantics};
7 use ide_db::{call_info::ActiveParameter, helpers::rust_doc::is_rust_fence, SymbolKind};
8 use syntax::{
9     ast::{self, AstNode, IsString},
10     AstToken, NodeOrToken, SyntaxNode, SyntaxToken, TextRange, TextSize,
11 };
12
13 use crate::{
14     doc_links::{doc_attributes, extract_definitions_from_docs, resolve_doc_path_for_def},
15     Analysis, HlMod, HlRange, HlTag, RootDatabase,
16 };
17
18 use super::{highlights::Highlights, injector::Injector};
19
20 pub(super) fn ra_fixture(
21     hl: &mut Highlights,
22     sema: &Semantics<RootDatabase>,
23     literal: ast::String,
24     expanded: SyntaxToken,
25 ) -> Option<()> {
26     let active_parameter = ActiveParameter::at_token(sema, expanded)?;
27     if !active_parameter.ident().map_or(false, |name| name.text().starts_with("ra_fixture")) {
28         return None;
29     }
30     let value = literal.value()?;
31
32     if let Some(range) = literal.open_quote_text_range() {
33         hl.add(HlRange { range, highlight: HlTag::StringLiteral.into(), binding_hash: None })
34     }
35
36     let mut inj = Injector::default();
37
38     let mut text = &*value;
39     let mut offset: TextSize = 0.into();
40
41     while !text.is_empty() {
42         let marker = "$0";
43         let idx = text.find(marker).unwrap_or(text.len());
44         let (chunk, next) = text.split_at(idx);
45         inj.add(chunk, TextRange::at(offset, TextSize::of(chunk)));
46
47         text = next;
48         offset += TextSize::of(chunk);
49
50         if let Some(next) = text.strip_prefix(marker) {
51             if let Some(range) = literal.map_range_up(TextRange::at(offset, TextSize::of(marker))) {
52                 hl.add(HlRange { range, highlight: HlTag::Keyword.into(), binding_hash: None });
53             }
54
55             text = next;
56
57             let marker_len = TextSize::of(marker);
58             offset += marker_len;
59         }
60     }
61
62     let (analysis, tmp_file_id) = Analysis::from_single_file(inj.text().to_string());
63
64     for mut hl_range in analysis.highlight(tmp_file_id).unwrap() {
65         for range in inj.map_range_up(hl_range.range) {
66             if let Some(range) = literal.map_range_up(range) {
67                 hl_range.range = range;
68                 hl.add(hl_range);
69             }
70         }
71     }
72
73     if let Some(range) = literal.close_quote_text_range() {
74         hl.add(HlRange { range, highlight: HlTag::StringLiteral.into(), binding_hash: None })
75     }
76
77     Some(())
78 }
79
80 const RUSTDOC_FENCE: &'static str = "```";
81
82 /// Injection of syntax highlighting of doctests.
83 pub(super) fn doc_comment(
84     hl: &mut Highlights,
85     sema: &Semantics<RootDatabase>,
86     node: InFile<&SyntaxNode>,
87 ) {
88     let (attributes, def) = match doc_attributes(sema, node.value) {
89         Some(it) => it,
90         None => return,
91     };
92
93     let mut inj = Injector::default();
94     inj.add_unmapped("fn doctest() {\n");
95
96     let attrs_source_map = attributes.source_map(sema.db);
97
98     let mut is_codeblock = false;
99     let mut is_doctest = false;
100
101     // Replace the original, line-spanning comment ranges by new, only comment-prefix
102     // spanning comment ranges.
103     let mut new_comments = Vec::new();
104     let mut string;
105
106     if let Some((docs, doc_mapping)) = attributes.docs_with_rangemap(sema.db) {
107         extract_definitions_from_docs(&docs)
108             .into_iter()
109             .filter_map(|(range, link, ns)| {
110                 let def = resolve_doc_path_for_def(sema.db, def, &link, ns)?;
111                 let InFile { file_id, value: range } = doc_mapping.map(range)?;
112                 (file_id == node.file_id).then(|| (range, def))
113             })
114             .for_each(|(range, def)| {
115                 hl.add(HlRange {
116                     range,
117                     highlight: module_def_to_hl_tag(def)
118                         | HlMod::Documentation
119                         | HlMod::Injected
120                         | HlMod::IntraDocLink,
121                     binding_hash: None,
122                 })
123             });
124     }
125
126     for attr in attributes.by_key("doc").attrs() {
127         let InFile { file_id, value: src } = attrs_source_map.source_of(attr);
128         if file_id != node.file_id {
129             continue;
130         }
131         let (line, range, prefix) = match &src {
132             Either::Left(it) => {
133                 string = match find_doc_string_in_attr(attr, it) {
134                     Some(it) => it,
135                     None => continue,
136                 };
137                 let text_range = string.syntax().text_range();
138                 let text_range = TextRange::new(
139                     text_range.start() + TextSize::from(1),
140                     text_range.end() - TextSize::from(1),
141                 );
142                 let text = string.text();
143                 (&text[1..text.len() - 1], text_range, "")
144             }
145             Either::Right(comment) => {
146                 (comment.text(), comment.syntax().text_range(), comment.prefix())
147             }
148         };
149
150         let mut pos = TextSize::from(prefix.len() as u32);
151         let mut range_start = range.start();
152         for line in line.split('\n') {
153             let line_len = TextSize::from(line.len() as u32);
154             let prev_range_start = {
155                 let next_range_start = range_start + line_len + TextSize::from(1);
156                 mem::replace(&mut range_start, next_range_start)
157             };
158             // only first line has the prefix so take it away for future iterations
159             let mut pos = mem::take(&mut pos);
160
161             match line.find(RUSTDOC_FENCE) {
162                 Some(idx) => {
163                     is_codeblock = !is_codeblock;
164                     // Check whether code is rust by inspecting fence guards
165                     let guards = &line[idx + RUSTDOC_FENCE.len()..];
166                     let is_rust = is_rust_fence(guards);
167                     is_doctest = is_codeblock && is_rust;
168                     continue;
169                 }
170                 None if !is_doctest => continue,
171                 None => (),
172             }
173
174             // whitespace after comment is ignored
175             if let Some(ws) = line[pos.into()..].chars().next().filter(|c| c.is_whitespace()) {
176                 pos += TextSize::of(ws);
177             }
178             // lines marked with `#` should be ignored in output, we skip the `#` char
179             if line[pos.into()..].starts_with('#') {
180                 pos += TextSize::of('#');
181             }
182
183             new_comments.push(TextRange::at(prev_range_start, pos));
184             inj.add(&line[pos.into()..], TextRange::new(pos, line_len) + prev_range_start);
185             inj.add_unmapped("\n");
186         }
187     }
188
189     if new_comments.is_empty() {
190         return; // no need to run an analysis on an empty file
191     }
192
193     inj.add_unmapped("\n}");
194
195     let (analysis, tmp_file_id) = Analysis::from_single_file(inj.text().to_string());
196
197     for HlRange { range, highlight, binding_hash } in
198         analysis.with_db(|db| super::highlight(db, tmp_file_id, None, true)).unwrap()
199     {
200         for range in inj.map_range_up(range) {
201             hl.add(HlRange { range, highlight: highlight | HlMod::Injected, binding_hash });
202         }
203     }
204
205     for range in new_comments {
206         hl.add(HlRange {
207             range,
208             highlight: HlTag::Comment | HlMod::Documentation,
209             binding_hash: None,
210         });
211     }
212 }
213
214 fn find_doc_string_in_attr(attr: &hir::Attr, it: &ast::Attr) -> Option<ast::String> {
215     match it.expr() {
216         // #[doc = lit]
217         Some(ast::Expr::Literal(lit)) => match lit.kind() {
218             ast::LiteralKind::String(it) => Some(it),
219             _ => None,
220         },
221         // #[cfg_attr(..., doc = "", ...)]
222         None => {
223             // We gotta hunt the string token manually here
224             let text = attr.string_value()?;
225             // FIXME: We just pick the first string literal that has the same text as the doc attribute
226             // This means technically we might highlight the wrong one
227             it.syntax()
228                 .descendants_with_tokens()
229                 .filter_map(NodeOrToken::into_token)
230                 .filter_map(ast::String::cast)
231                 .find(|string| {
232                     string.text().get(1..string.text().len() - 1).map_or(false, |it| it == text)
233                 })
234         }
235         _ => None,
236     }
237 }
238
239 fn module_def_to_hl_tag(def: hir::ModuleDef) -> HlTag {
240     let symbol = match def {
241         hir::ModuleDef::Module(_) => SymbolKind::Module,
242         hir::ModuleDef::Function(_) => SymbolKind::Function,
243         hir::ModuleDef::Adt(hir::Adt::Struct(_)) => SymbolKind::Struct,
244         hir::ModuleDef::Adt(hir::Adt::Enum(_)) => SymbolKind::Enum,
245         hir::ModuleDef::Adt(hir::Adt::Union(_)) => SymbolKind::Union,
246         hir::ModuleDef::Variant(_) => SymbolKind::Variant,
247         hir::ModuleDef::Const(_) => SymbolKind::Const,
248         hir::ModuleDef::Static(_) => SymbolKind::Static,
249         hir::ModuleDef::Trait(_) => SymbolKind::Trait,
250         hir::ModuleDef::TypeAlias(_) => SymbolKind::TypeAlias,
251         hir::ModuleDef::BuiltinType(_) => return HlTag::BuiltinType,
252     };
253     HlTag::Symbol(symbol)
254 }