1 //! Syntax highlighting injections such as highlighting of documentation tests.
3 use std::{collections::BTreeMap, convert::TryFrom};
6 use ide_db::call_info::ActiveParameter;
7 use itertools::Itertools;
8 use syntax::{ast, AstToken, SyntaxNode, SyntaxToken, TextRange, TextSize};
10 use crate::{Analysis, Highlight, HighlightModifier, HighlightTag, HighlightedRange, RootDatabase};
12 use super::HighlightedRangeStack;
14 pub(super) fn highlight_injection(
15 acc: &mut HighlightedRangeStack,
16 sema: &Semantics<RootDatabase>,
18 expanded: SyntaxToken,
20 let active_parameter = ActiveParameter::at_token(&sema, expanded)?;
21 if !active_parameter.name.starts_with("ra_fixture") {
24 let value = literal.value()?;
25 let (analysis, tmp_file_id) = Analysis::from_single_file(value.into_owned());
27 if let Some(range) = literal.open_quote_text_range() {
28 acc.add(HighlightedRange {
30 highlight: HighlightTag::StringLiteral.into(),
35 for mut h in analysis.highlight(tmp_file_id).unwrap() {
36 if let Some(r) = literal.map_range_up(h.range) {
42 if let Some(range) = literal.close_quote_text_range() {
43 acc.add(HighlightedRange {
45 highlight: HighlightTag::StringLiteral.into(),
53 /// Mapping from extracted documentation code to original code
54 type RangesMap = BTreeMap<TextSize, TextSize>;
56 const RUSTDOC_FENCE: &'static str = "```";
57 const RUSTDOC_FENCE_TOKENS: &[&'static str] = &[
69 /// Extracts Rust code from documentation comments as well as a mapping from
70 /// the extracted source code back to the original source ranges.
71 /// Lastly, a vector of new comment highlight ranges (spanning only the
72 /// comment prefix) is returned which is used in the syntax highlighting
73 /// injection to replace the previous (line-spanning) comment ranges.
74 pub(super) fn extract_doc_comments(
76 ) -> Option<(String, RangesMap, Vec<HighlightedRange>)> {
77 // wrap the doctest into function body to get correct syntax highlighting
78 let prefix = "fn doctest() {\n";
80 // Mapping from extracted documentation code to original code
81 let mut range_mapping: RangesMap = BTreeMap::new();
82 let mut line_start = TextSize::try_from(prefix.len()).unwrap();
83 let mut is_codeblock = false;
84 let mut is_doctest = false;
85 // Replace the original, line-spanning comment ranges by new, only comment-prefix
86 // spanning comment ranges.
87 let mut new_comments = Vec::new();
89 .children_with_tokens()
90 .filter_map(|el| el.into_token().and_then(ast::Comment::cast))
91 .filter(|comment| comment.kind().doc.is_some())
93 if let Some(idx) = comment.text().find(RUSTDOC_FENCE) {
94 is_codeblock = !is_codeblock;
95 // Check whether code is rust by inspecting fence guards
96 let guards = &comment.text()[idx + RUSTDOC_FENCE.len()..];
98 guards.split(',').all(|sub| RUSTDOC_FENCE_TOKENS.contains(&sub.trim()));
99 is_doctest = is_codeblock && is_rust;
106 let prefix_len = comment.prefix().len();
107 let line: &str = comment.text().as_str();
108 let range = comment.syntax().text_range();
110 // whitespace after comment is ignored
111 let pos = if let Some(ws) = line.chars().nth(prefix_len).filter(|c| c.is_whitespace()) {
112 prefix_len + ws.len_utf8()
117 // lines marked with `#` should be ignored in output, we skip the `#` char
118 let pos = if let Some(ws) = line.chars().nth(pos).filter(|&c| c == '#') {
124 range_mapping.insert(line_start, range.start() + TextSize::try_from(pos).unwrap());
125 new_comments.push(HighlightedRange {
126 range: TextRange::new(
128 range.start() + TextSize::try_from(pos).unwrap(),
130 highlight: HighlightTag::Comment | HighlightModifier::Documentation,
133 line_start += range.len() - TextSize::try_from(pos).unwrap();
134 line_start += TextSize::try_from('\n'.len_utf8()).unwrap();
136 line[pos..].to_owned()
140 if doctest.is_empty() {
144 let doctest = format!("{}{}{}", prefix, doctest, suffix);
145 Some((doctest, range_mapping, new_comments))
148 /// Injection of syntax highlighting of doctests.
149 pub(super) fn highlight_doc_comment(
151 range_mapping: RangesMap,
152 new_comments: Vec<HighlightedRange>,
153 stack: &mut HighlightedRangeStack,
155 let (analysis, tmp_file_id) = Analysis::from_single_file(text);
158 for mut h in analysis.with_db(|db| super::highlight(db, tmp_file_id, None, true)).unwrap() {
159 // Determine start offset and end offset in case of multi-line ranges
160 let mut start_offset = None;
161 let mut end_offset = None;
162 for (line_start, orig_line_start) in range_mapping.range(..h.range.end()).rev() {
163 // It's possible for orig_line_start - line_start to be negative. Add h.range.start()
164 // here and remove it from the end range after the loop below so that the values are
165 // always non-negative.
166 let offset = h.range.start() + orig_line_start - line_start;
167 if line_start <= &h.range.start() {
168 start_offset.get_or_insert(offset);
171 end_offset.get_or_insert(offset);
174 if let Some(start_offset) = start_offset {
175 h.range = TextRange::new(
177 h.range.end() + end_offset.unwrap_or(start_offset) - h.range.start(),
180 h.highlight |= HighlightModifier::Injected;
185 // Inject the comment prefix highlight ranges
187 for comment in new_comments {
190 stack.pop_and_inject(None);
191 stack.pop_and_inject(Some(Highlight::from(HighlightTag::Dummy) | HighlightModifier::Injected));