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