1 //! "Recursive" Syntax highlighting for code in doctests and fixtures.
6 use hir::{InFile, Semantics};
7 use ide_db::{call_info::ActiveParameter, SymbolKind};
10 AstToken, NodeOrToken, SyntaxNode, SyntaxToken, TextRange, TextSize,
14 doc_links::{doc_attributes, extract_definitions_from_markdown, resolve_doc_path_for_def},
15 Analysis, HlMod, HlRange, HlTag, RootDatabase,
18 use super::{highlights::Highlights, injector::Injector};
20 pub(super) fn ra_fixture(
22 sema: &Semantics<RootDatabase>,
24 expanded: SyntaxToken,
26 let active_parameter = ActiveParameter::at_token(&sema, expanded)?;
27 if !active_parameter.ident().map_or(false, |name| name.text().starts_with("ra_fixture")) {
30 let value = literal.value()?;
32 if let Some(range) = literal.open_quote_text_range() {
33 hl.add(HlRange { range, highlight: HlTag::StringLiteral.into(), binding_hash: None })
36 let mut inj = Injector::default();
38 let mut text = &*value;
39 let mut offset: TextSize = 0.into();
41 while !text.is_empty() {
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)));
48 offset += TextSize::of(chunk);
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 });
57 let marker_len = TextSize::of(marker);
62 let (analysis, tmp_file_id) = Analysis::from_single_file(inj.text().to_string());
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;
73 if let Some(range) = literal.close_quote_text_range() {
74 hl.add(HlRange { range, highlight: HlTag::StringLiteral.into(), binding_hash: None })
80 const RUSTDOC_FENCE: &'static str = "```";
81 const RUSTDOC_FENCE_TOKENS: &[&'static str] = &[
93 /// Injection of syntax highlighting of doctests.
94 pub(super) fn doc_comment(
96 sema: &Semantics<RootDatabase>,
97 node: InFile<&SyntaxNode>,
99 let (attributes, def) = match doc_attributes(sema, node.value) {
104 let mut inj = Injector::default();
105 inj.add_unmapped("fn doctest() {\n");
107 let attrs_source_map = attributes.source_map(sema.db);
109 let mut is_codeblock = false;
110 let mut is_doctest = false;
112 // Replace the original, line-spanning comment ranges by new, only comment-prefix
113 // spanning comment ranges.
114 let mut new_comments = Vec::new();
117 if let Some((docs, doc_mapping)) = attributes.docs_with_rangemap(sema.db) {
118 extract_definitions_from_markdown(docs.as_str())
120 .filter_map(|(range, link, ns)| {
121 let def = resolve_doc_path_for_def(sema.db, def, &link, ns)?;
122 let InFile { file_id, value: range } = doc_mapping.map(range)?;
123 (file_id == node.file_id).then(|| (range, def))
125 .for_each(|(range, def)| {
128 highlight: module_def_to_hl_tag(def)
129 | HlMod::Documentation
131 | HlMod::IntraDocLink,
137 for attr in attributes.by_key("doc").attrs() {
138 let InFile { file_id, value: src } = attrs_source_map.source_of(&attr);
139 if file_id != node.file_id {
142 let (line, range, prefix) = match &src {
143 Either::Left(it) => {
144 string = match find_doc_string_in_attr(attr, it) {
148 let text_range = string.syntax().text_range();
149 let text_range = TextRange::new(
150 text_range.start() + TextSize::from(1),
151 text_range.end() - TextSize::from(1),
153 let text = string.text();
154 (&text[1..text.len() - 1], text_range, "")
156 Either::Right(comment) => {
157 (comment.text(), comment.syntax().text_range(), comment.prefix())
161 let mut pos = TextSize::from(prefix.len() as u32);
162 let mut range_start = range.start();
163 for line in line.split('\n') {
164 let line_len = TextSize::from(line.len() as u32);
165 let prev_range_start = {
166 let next_range_start = range_start + line_len + TextSize::from(1);
167 mem::replace(&mut range_start, next_range_start)
169 // only first line has the prefix so take it away for future iterations
170 let mut pos = mem::take(&mut pos);
172 match line.find(RUSTDOC_FENCE) {
174 is_codeblock = !is_codeblock;
175 // Check whether code is rust by inspecting fence guards
176 let guards = &line[idx + RUSTDOC_FENCE.len()..];
178 guards.split(',').all(|sub| RUSTDOC_FENCE_TOKENS.contains(&sub.trim()));
179 is_doctest = is_codeblock && is_rust;
182 None if !is_doctest => continue,
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);
190 // lines marked with `#` should be ignored in output, we skip the `#` char
191 if line[pos.into()..].starts_with('#') {
192 pos += TextSize::of('#');
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");
201 if new_comments.is_empty() {
202 return; // no need to run an analysis on an empty file
205 inj.add_unmapped("\n}");
207 let (analysis, tmp_file_id) = Analysis::from_single_file(inj.text().to_string());
209 for HlRange { range, highlight, binding_hash } in
210 analysis.with_db(|db| super::highlight(db, tmp_file_id, None, true)).unwrap()
212 for range in inj.map_range_up(range) {
213 hl.add(HlRange { range, highlight: highlight | HlMod::Injected, binding_hash });
217 for range in new_comments {
220 highlight: HlTag::Comment | HlMod::Documentation,
226 fn find_doc_string_in_attr(attr: &hir::Attr, it: &ast::Attr) -> Option<ast::String> {
229 Some(ast::Expr::Literal(lit)) => match lit.kind() {
230 ast::LiteralKind::String(it) => Some(it),
233 // #[cfg_attr(..., doc = "", ...)]
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
240 .descendants_with_tokens()
241 .filter_map(NodeOrToken::into_token)
242 .filter_map(ast::String::cast)
244 string.text().get(1..string.text().len() - 1).map_or(false, |it| it == text)
251 fn module_def_to_hl_tag(def: hir::ModuleDef) -> HlTag {
252 let symbol = match def {
253 hir::ModuleDef::Module(_) => SymbolKind::Module,
254 hir::ModuleDef::Function(_) => SymbolKind::Function,
255 hir::ModuleDef::Adt(hir::Adt::Struct(_)) => SymbolKind::Struct,
256 hir::ModuleDef::Adt(hir::Adt::Enum(_)) => SymbolKind::Enum,
257 hir::ModuleDef::Adt(hir::Adt::Union(_)) => SymbolKind::Union,
258 hir::ModuleDef::Variant(_) => SymbolKind::Variant,
259 hir::ModuleDef::Const(_) => SymbolKind::Const,
260 hir::ModuleDef::Static(_) => SymbolKind::Static,
261 hir::ModuleDef::Trait(_) => SymbolKind::Trait,
262 hir::ModuleDef::TypeAlias(_) => SymbolKind::TypeAlias,
263 hir::ModuleDef::BuiltinType(_) => return HlTag::BuiltinType,
265 HlTag::Symbol(symbol)