1 //! "Recursive" Syntax highlighting for code in doctests and fixtures.
3 use std::{mem, ops::Range};
6 use hir::{HasAttrs, InFile, Semantics};
7 use ide_db::{call_info::ActiveParameter, defs::Definition, SymbolKind};
10 match_ast, AstToken, NodeOrToken, SyntaxNode, SyntaxToken, TextRange, TextSize,
14 doc_links::extract_definitions_from_markdown, Analysis, HlMod, HlRange, HlTag, RootDatabase,
17 use super::{highlights::Highlights, injector::Injector};
19 pub(super) fn ra_fixture(
21 sema: &Semantics<RootDatabase>,
23 expanded: SyntaxToken,
25 let active_parameter = ActiveParameter::at_token(&sema, expanded)?;
26 if !active_parameter.name.starts_with("ra_fixture") {
29 let value = literal.value()?;
31 if let Some(range) = literal.open_quote_text_range() {
32 hl.add(HlRange { range, highlight: HlTag::StringLiteral.into(), binding_hash: None })
35 let mut inj = Injector::default();
37 let mut text = &*value;
38 let mut offset: TextSize = 0.into();
40 while !text.is_empty() {
42 let idx = text.find(marker).unwrap_or(text.len());
43 let (chunk, next) = text.split_at(idx);
44 inj.add(chunk, TextRange::at(offset, TextSize::of(chunk)));
47 offset += TextSize::of(chunk);
49 if let Some(next) = text.strip_prefix(marker) {
50 if let Some(range) = literal.map_range_up(TextRange::at(offset, TextSize::of(marker))) {
51 hl.add(HlRange { range, highlight: HlTag::Keyword.into(), binding_hash: None });
56 let marker_len = TextSize::of(marker);
61 let (analysis, tmp_file_id) = Analysis::from_single_file(inj.text().to_string());
63 for mut hl_range in analysis.highlight(tmp_file_id).unwrap() {
64 for range in inj.map_range_up(hl_range.range) {
65 if let Some(range) = literal.map_range_up(range) {
66 hl_range.range = range;
72 if let Some(range) = literal.close_quote_text_range() {
73 hl.add(HlRange { range, highlight: HlTag::StringLiteral.into(), binding_hash: None })
79 const RUSTDOC_FENCE: &'static str = "```";
80 const RUSTDOC_FENCE_TOKENS: &[&'static str] = &[
92 fn doc_attributes<'node>(
93 sema: &Semantics<RootDatabase>,
94 node: &'node SyntaxNode,
95 ) -> Option<(hir::AttrsWithOwner, Definition)> {
98 ast::SourceFile(it) => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Module(def)))),
99 ast::Module(it) => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Module(def)))),
100 ast::Fn(it) => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Function(def)))),
101 ast::Struct(it) => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Adt(hir::Adt::Struct(def))))),
102 ast::Union(it) => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Adt(hir::Adt::Union(def))))),
103 ast::Enum(it) => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Adt(hir::Adt::Enum(def))))),
104 ast::Variant(it) => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Variant(def)))),
105 ast::Trait(it) => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Trait(def)))),
106 ast::Static(it) => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Static(def)))),
107 ast::Const(it) => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Const(def)))),
108 ast::TypeAlias(it) => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::TypeAlias(def)))),
109 ast::Impl(it) => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::SelfType(def))),
110 ast::RecordField(it) => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::Field(def))),
111 ast::TupleField(it) => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::Field(def))),
112 ast::MacroRules(it) => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::Macro(def))),
113 // ast::MacroDef(it) => sema.to_def(&it).map(|def| (Box::new(it) as _, def.attrs(sema.db))),
114 // ast::Use(it) => sema.to_def(&it).map(|def| (Box::new(it) as _, def.attrs(sema.db))),
120 /// Injection of syntax highlighting of doctests.
121 pub(super) fn doc_comment(
123 sema: &Semantics<RootDatabase>,
124 node: InFile<&SyntaxNode>,
126 let (attributes, def) = match doc_attributes(sema, node.value) {
131 let mut inj = Injector::default();
132 inj.add_unmapped("fn doctest() {\n");
134 let attrs_source_map = attributes.source_map(sema.db);
136 let mut is_codeblock = false;
137 let mut is_doctest = false;
139 // Replace the original, line-spanning comment ranges by new, only comment-prefix
140 // spanning comment ranges.
141 let mut new_comments = Vec::new();
142 let mut intra_doc_links = Vec::new();
144 for attr in attributes.by_key("doc").attrs() {
145 let InFile { file_id, value: src } = attrs_source_map.source_of(&attr);
146 if file_id != node.file_id {
149 let (line, range, prefix) = match &src {
150 Either::Left(it) => {
151 string = match find_doc_string_in_attr(attr, it) {
155 let text_range = string.syntax().text_range();
156 let text_range = TextRange::new(
157 text_range.start() + TextSize::from(1),
158 text_range.end() - TextSize::from(1),
160 let text = string.text();
161 (&text[1..text.len() - 1], text_range, "")
163 Either::Right(comment) => {
164 (comment.text(), comment.syntax().text_range(), comment.prefix())
168 let mut pos = TextSize::from(prefix.len() as u32);
169 let mut range_start = range.start();
170 for line in line.split('\n') {
171 let line_len = TextSize::from(line.len() as u32);
172 let prev_range_start = {
173 let next_range_start = range_start + line_len + TextSize::from(1);
174 mem::replace(&mut range_start, next_range_start)
176 // only first line has the prefix so take it away for future iterations
177 let mut pos = mem::take(&mut pos);
179 match line.find(RUSTDOC_FENCE) {
181 is_codeblock = !is_codeblock;
182 // Check whether code is rust by inspecting fence guards
183 let guards = &line[idx + RUSTDOC_FENCE.len()..];
185 guards.split(',').all(|sub| RUSTDOC_FENCE_TOKENS.contains(&sub.trim()));
186 is_doctest = is_codeblock && is_rust;
189 None if !is_doctest => {
190 intra_doc_links.extend(
191 extract_definitions_from_markdown(line)
193 .filter_map(|(link, ns, range)| {
194 validate_intra_doc_link(sema.db, &def, &link, ns).zip(Some(range))
196 .map(|(def, Range { start, end })| {
200 prev_range_start + TextSize::from(start as u32),
201 TextSize::from((end - start) as u32),
211 // whitespace after comment is ignored
212 if let Some(ws) = line[pos.into()..].chars().next().filter(|c| c.is_whitespace()) {
213 pos += TextSize::of(ws);
215 // lines marked with `#` should be ignored in output, we skip the `#` char
216 if line[pos.into()..].starts_with('#') {
217 pos += TextSize::of('#');
220 new_comments.push(TextRange::at(prev_range_start, pos));
221 inj.add(&line[pos.into()..], TextRange::new(pos, line_len) + prev_range_start);
222 inj.add_unmapped("\n");
226 for (def, range) in intra_doc_links {
229 highlight: module_def_to_hl_tag(def)
230 | HlMod::Documentation
232 | HlMod::IntraDocLink,
237 if new_comments.is_empty() {
238 return; // no need to run an analysis on an empty file
241 inj.add_unmapped("\n}");
243 let (analysis, tmp_file_id) = Analysis::from_single_file(inj.text().to_string());
245 for HlRange { range, highlight, binding_hash } in
246 analysis.with_db(|db| super::highlight(db, tmp_file_id, None, true)).unwrap()
248 for range in inj.map_range_up(range) {
249 hl.add(HlRange { range, highlight: highlight | HlMod::Injected, binding_hash });
253 for range in new_comments {
256 highlight: HlTag::Comment | HlMod::Documentation,
262 fn find_doc_string_in_attr(attr: &hir::Attr, it: &ast::Attr) -> Option<ast::String> {
265 Some(ast::Expr::Literal(lit)) => match lit.kind() {
266 ast::LiteralKind::String(it) => Some(it),
269 // #[cfg_attr(..., doc = "", ...)]
271 // We gotta hunt the string token manually here
272 let text = attr.string_value()?;
273 // FIXME: We just pick the first string literal that has the same text as the doc attribute
274 // This means technically we might highlight the wrong one
276 .descendants_with_tokens()
277 .filter_map(NodeOrToken::into_token)
278 .filter_map(ast::String::cast)
280 string.text().get(1..string.text().len() - 1).map_or(false, |it| it == text)
287 fn validate_intra_doc_link(
291 ns: Option<hir::Namespace>,
292 ) -> Option<hir::ModuleDef> {
294 Definition::ModuleDef(def) => match def {
295 hir::ModuleDef::Module(it) => it.resolve_doc_path(db, &link, ns),
296 hir::ModuleDef::Function(it) => it.resolve_doc_path(db, &link, ns),
297 hir::ModuleDef::Adt(it) => it.resolve_doc_path(db, &link, ns),
298 hir::ModuleDef::Variant(it) => it.resolve_doc_path(db, &link, ns),
299 hir::ModuleDef::Const(it) => it.resolve_doc_path(db, &link, ns),
300 hir::ModuleDef::Static(it) => it.resolve_doc_path(db, &link, ns),
301 hir::ModuleDef::Trait(it) => it.resolve_doc_path(db, &link, ns),
302 hir::ModuleDef::TypeAlias(it) => it.resolve_doc_path(db, &link, ns),
303 hir::ModuleDef::BuiltinType(_) => None,
305 Definition::Macro(it) => it.resolve_doc_path(db, &link, ns),
306 Definition::Field(it) => it.resolve_doc_path(db, &link, ns),
307 Definition::SelfType(_)
308 | Definition::Local(_)
309 | Definition::GenericParam(_)
310 | Definition::Label(_) => None,
314 fn module_def_to_hl_tag(def: hir::ModuleDef) -> HlTag {
315 let symbol = match def {
316 hir::ModuleDef::Module(_) => SymbolKind::Module,
317 hir::ModuleDef::Function(_) => SymbolKind::Function,
318 hir::ModuleDef::Adt(hir::Adt::Struct(_)) => SymbolKind::Struct,
319 hir::ModuleDef::Adt(hir::Adt::Enum(_)) => SymbolKind::Enum,
320 hir::ModuleDef::Adt(hir::Adt::Union(_)) => SymbolKind::Union,
321 hir::ModuleDef::Variant(_) => SymbolKind::Variant,
322 hir::ModuleDef::Const(_) => SymbolKind::Const,
323 hir::ModuleDef::Static(_) => SymbolKind::Static,
324 hir::ModuleDef::Trait(_) => SymbolKind::Trait,
325 hir::ModuleDef::TypeAlias(_) => SymbolKind::TypeAlias,
326 hir::ModuleDef::BuiltinType(_) => return HlTag::BuiltinType,
328 HlTag::Symbol(symbol)