1 //! "Recursive" Syntax highlighting for code in doctests and fixtures.
3 use std::{mem, ops::Range};
6 use hir::{HasAttrs, Semantics};
7 use ide_db::{call_info::ActiveParameter, defs::Definition};
9 ast::{self, AstNode, AttrsOwner, DocCommentsOwner},
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 // Basically an owned dyn AttrsOwner without extra Boxing
93 struct AttrsOwnerNode {
98 fn new<N: DocCommentsOwner>(node: N) -> Self {
99 AttrsOwnerNode { node: node.syntax().clone() }
103 impl AttrsOwner for AttrsOwnerNode {}
104 impl AstNode for AttrsOwnerNode {
105 fn can_cast(_: syntax::SyntaxKind) -> bool
111 fn cast(_: SyntaxNode) -> Option<Self>
117 fn syntax(&self) -> &SyntaxNode {
122 fn doc_attributes<'node>(
123 sema: &Semantics<RootDatabase>,
124 node: &'node SyntaxNode,
125 ) -> Option<(AttrsOwnerNode, hir::Attrs, Definition)> {
128 ast::SourceFile(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Module(def)))),
129 ast::Module(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Module(def)))),
130 ast::Fn(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Function(def)))),
131 ast::Struct(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Adt(hir::Adt::Struct(def))))),
132 ast::Union(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Adt(hir::Adt::Union(def))))),
133 ast::Enum(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Adt(hir::Adt::Enum(def))))),
134 ast::Variant(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Variant(def)))),
135 ast::Trait(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Trait(def)))),
136 ast::Static(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Static(def)))),
137 ast::Const(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Const(def)))),
138 ast::TypeAlias(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::TypeAlias(def)))),
139 ast::Impl(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::SelfType(def))),
140 ast::RecordField(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::Field(def))),
141 ast::TupleField(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::Field(def))),
142 ast::MacroRules(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::Macro(def))),
143 // ast::MacroDef(it) => sema.to_def(&it).map(|def| (Box::new(it) as _, def.attrs(sema.db))),
144 // ast::Use(it) => sema.to_def(&it).map(|def| (Box::new(it) as _, def.attrs(sema.db))),
150 /// Injection of syntax highlighting of doctests.
151 pub(super) fn doc_comment(hl: &mut Highlights, sema: &Semantics<RootDatabase>, node: &SyntaxNode) {
152 let (owner, attributes, def) = match doc_attributes(sema, node) {
157 let mut inj = Injector::default();
158 inj.add_unmapped("fn doctest() {\n");
160 let attrs_source_map = attributes.source_map(&owner);
162 let mut is_codeblock = false;
163 let mut is_doctest = false;
165 // Replace the original, line-spanning comment ranges by new, only comment-prefix
166 // spanning comment ranges.
167 let mut new_comments = Vec::new();
168 let mut intra_doc_links = Vec::new();
170 for attr in attributes.by_key("doc").attrs() {
171 let src = attrs_source_map.source_of(&attr);
172 let (line, range, prefix) = match &src {
173 Either::Left(it) => {
174 string = match find_doc_string_in_attr(attr, it) {
178 let text_range = string.syntax().text_range();
179 let text_range = TextRange::new(
180 text_range.start() + TextSize::from(1),
181 text_range.end() - TextSize::from(1),
183 let text = string.text();
184 (&text[1..text.len() - 1], text_range, "")
186 Either::Right(comment) => {
187 (comment.text(), comment.syntax().text_range(), comment.prefix())
191 let mut pos = TextSize::from(prefix.len() as u32);
192 let mut range_start = range.start();
193 for line in line.split('\n') {
194 let line_len = TextSize::from(line.len() as u32);
195 let prev_range_start = {
196 let next_range_start = range_start + line_len + TextSize::from(1);
197 mem::replace(&mut range_start, next_range_start)
199 // only first line has the prefix so take it away for future iterations
200 let mut pos = mem::take(&mut pos);
202 match line.find(RUSTDOC_FENCE) {
204 is_codeblock = !is_codeblock;
205 // Check whether code is rust by inspecting fence guards
206 let guards = &line[idx + RUSTDOC_FENCE.len()..];
208 guards.split(',').all(|sub| RUSTDOC_FENCE_TOKENS.contains(&sub.trim()));
209 is_doctest = is_codeblock && is_rust;
212 None if !is_doctest => {
213 intra_doc_links.extend(
214 extract_definitions_from_markdown(line)
216 .filter(|(link, ns, _)| {
217 validate_intra_doc_link(sema.db, &def, link, *ns)
219 .map(|(.., Range { start, end })| {
221 prev_range_start + TextSize::from(start as u32),
222 TextSize::from((end - start) as u32),
231 // whitespace after comment is ignored
232 if let Some(ws) = line[pos.into()..].chars().next().filter(|c| c.is_whitespace()) {
233 pos += TextSize::of(ws);
235 // lines marked with `#` should be ignored in output, we skip the `#` char
236 if line[pos.into()..].starts_with('#') {
237 pos += TextSize::of('#');
240 new_comments.push(TextRange::at(prev_range_start, pos));
241 inj.add(&line[pos.into()..], TextRange::new(pos, line_len) + prev_range_start);
242 inj.add_unmapped("\n");
246 for range in intra_doc_links {
249 highlight: HlTag::IntraDocLink | HlMod::Documentation,
254 if new_comments.is_empty() {
255 return; // no need to run an analysis on an empty file
258 inj.add_unmapped("\n}");
260 let (analysis, tmp_file_id) = Analysis::from_single_file(inj.text().to_string());
262 for HlRange { range, highlight, binding_hash } in
263 analysis.with_db(|db| super::highlight(db, tmp_file_id, None, true)).unwrap()
265 for range in inj.map_range_up(range) {
266 hl.add(HlRange { range, highlight: highlight | HlMod::Injected, binding_hash });
270 for range in new_comments {
273 highlight: HlTag::Comment | HlMod::Documentation,
279 fn find_doc_string_in_attr(attr: &hir::Attr, it: &ast::Attr) -> Option<ast::String> {
282 Some(lit) => match lit.kind() {
283 ast::LiteralKind::String(it) => Some(it),
286 // #[cfg_attr(..., doc = "", ...)]
288 // We gotta hunt the string token manually here
289 let text = attr.string_value()?;
290 // FIXME: We just pick the first string literal that has the same text as the doc attribute
291 // This means technically we might highlight the wrong one
293 .descendants_with_tokens()
294 .filter_map(NodeOrToken::into_token)
295 .filter_map(ast::String::cast)
297 string.text().get(1..string.text().len() - 1).map_or(false, |it| it == text)
303 fn validate_intra_doc_link(
307 ns: Option<hir::Namespace>,
310 Definition::ModuleDef(def) => match def {
311 hir::ModuleDef::Module(it) => it.resolve_doc_path(db, &link, ns),
312 hir::ModuleDef::Function(it) => it.resolve_doc_path(db, &link, ns),
313 hir::ModuleDef::Adt(it) => it.resolve_doc_path(db, &link, ns),
314 hir::ModuleDef::Variant(it) => it.resolve_doc_path(db, &link, ns),
315 hir::ModuleDef::Const(it) => it.resolve_doc_path(db, &link, ns),
316 hir::ModuleDef::Static(it) => it.resolve_doc_path(db, &link, ns),
317 hir::ModuleDef::Trait(it) => it.resolve_doc_path(db, &link, ns),
318 hir::ModuleDef::TypeAlias(it) => it.resolve_doc_path(db, &link, ns),
319 hir::ModuleDef::BuiltinType(_) => None,
321 Definition::Macro(it) => it.resolve_doc_path(db, &link, ns),
322 Definition::Field(it) => it.resolve_doc_path(db, &link, ns),
323 Definition::SelfType(_)
324 | Definition::Local(_)
325 | Definition::GenericParam(_)
326 | Definition::Label(_) => None,