1 //! "Recursive" Syntax highlighting for code in doctests and fixtures.
4 use hir::{HasAttrs, Semantics};
5 use ide_db::call_info::ActiveParameter;
7 ast::{self, AstNode, AttrsOwner, DocCommentsOwner},
8 match_ast, AstToken, SyntaxNode, SyntaxToken, TextRange, TextSize,
11 use crate::{Analysis, HlMod, HlRange, HlTag, RootDatabase};
13 use super::{highlights::Highlights, injector::Injector};
15 pub(super) fn ra_fixture(
17 sema: &Semantics<RootDatabase>,
19 expanded: SyntaxToken,
21 let active_parameter = ActiveParameter::at_token(&sema, expanded)?;
22 if !active_parameter.name.starts_with("ra_fixture") {
25 let value = literal.value()?;
27 if let Some(range) = literal.open_quote_text_range() {
28 hl.add(HlRange { range, highlight: HlTag::StringLiteral.into(), binding_hash: None })
31 let mut inj = Injector::default();
33 let mut text = &*value;
34 let mut offset: TextSize = 0.into();
36 while !text.is_empty() {
38 let idx = text.find(marker).unwrap_or(text.len());
39 let (chunk, next) = text.split_at(idx);
40 inj.add(chunk, TextRange::at(offset, TextSize::of(chunk)));
43 offset += TextSize::of(chunk);
45 if let Some(next) = text.strip_prefix(marker) {
46 if let Some(range) = literal.map_range_up(TextRange::at(offset, TextSize::of(marker))) {
47 hl.add(HlRange { range, highlight: HlTag::Keyword.into(), binding_hash: None });
52 let marker_len = TextSize::of(marker);
57 let (analysis, tmp_file_id) = Analysis::from_single_file(inj.text().to_string());
59 for mut hl_range in analysis.highlight(tmp_file_id).unwrap() {
60 for range in inj.map_range_up(hl_range.range) {
61 if let Some(range) = literal.map_range_up(range) {
62 hl_range.range = range;
63 hl.add(hl_range.clone());
68 if let Some(range) = literal.close_quote_text_range() {
69 hl.add(HlRange { range, highlight: HlTag::StringLiteral.into(), binding_hash: None })
75 const RUSTDOC_FENCE: &'static str = "```";
76 const RUSTDOC_FENCE_TOKENS: &[&'static str] = &[
88 // Basically an owned dyn AttrsOwner without extra Boxing
89 struct AttrsOwnerNode {
94 fn new<N: DocCommentsOwner>(node: N) -> Self {
95 AttrsOwnerNode { node: node.syntax().clone() }
99 impl AttrsOwner for AttrsOwnerNode {}
100 impl AstNode for AttrsOwnerNode {
101 fn can_cast(_: syntax::SyntaxKind) -> bool
107 fn cast(_: SyntaxNode) -> Option<Self>
113 fn syntax(&self) -> &SyntaxNode {
118 fn doc_attributes<'node>(
119 sema: &Semantics<RootDatabase>,
120 node: &'node SyntaxNode,
121 ) -> Option<(AttrsOwnerNode, hir::Attrs)> {
124 ast::SourceFile(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db))),
125 ast::Fn(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db))),
126 ast::Struct(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db))),
127 ast::Union(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db))),
128 ast::RecordField(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db))),
129 ast::TupleField(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db))),
130 ast::Enum(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db))),
131 ast::Variant(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db))),
132 ast::Trait(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db))),
133 ast::Module(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db))),
134 ast::Static(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db))),
135 ast::Const(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db))),
136 ast::TypeAlias(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db))),
137 ast::Impl(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db))),
138 ast::MacroRules(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db))),
139 // ast::MacroDef(it) => sema.to_def(&it).map(|def| (Box::new(it) as _, def.attrs(sema.db))),
140 // ast::Use(it) => sema.to_def(&it).map(|def| (Box::new(it) as _, def.attrs(sema.db))),
146 /// Injection of syntax highlighting of doctests.
147 pub(super) fn doc_comment(hl: &mut Highlights, sema: &Semantics<RootDatabase>, node: &SyntaxNode) {
148 let (owner, attributes) = match doc_attributes(sema, node) {
153 if attributes.docs().map_or(true, |docs| !String::from(docs).contains(RUSTDOC_FENCE)) {
156 let doc_comments = attributes.by_key("doc").attrs().map(|attr| attr.to_src(&owner));
158 let mut inj = Injector::default();
159 inj.add_unmapped("fn doctest() {\n");
161 let mut is_codeblock = false;
162 let mut is_doctest = false;
164 // Replace the original, line-spanning comment ranges by new, only comment-prefix
165 // spanning comment ranges.
166 let mut new_comments = Vec::new();
167 for comment in doc_comments {
168 let (line, range, prefix) = match &comment {
169 Either::Left(_) => continue, // FIXME
170 Either::Right(comment) => {
171 (comment.text(), comment.syntax().text_range(), comment.prefix())
174 match line.find(RUSTDOC_FENCE) {
176 is_codeblock = !is_codeblock;
177 // Check whether code is rust by inspecting fence guards
178 let guards = &line[idx + RUSTDOC_FENCE.len()..];
180 guards.split(',').all(|sub| RUSTDOC_FENCE_TOKENS.contains(&sub.trim()));
181 is_doctest = is_codeblock && is_rust;
184 None if !is_doctest => continue,
188 let mut pos = TextSize::of(prefix);
189 // whitespace after comment is ignored
190 if let Some(ws) = line[pos.into()..].chars().next().filter(|c| c.is_whitespace()) {
191 pos += TextSize::of(ws);
193 // lines marked with `#` should be ignored in output, we skip the `#` char
194 if let Some(ws) = line[pos.into()..].chars().next().filter(|&c| c == '#') {
195 pos += TextSize::of(ws);
198 new_comments.push(TextRange::at(range.start(), pos));
200 inj.add(&line[pos.into()..], TextRange::new(range.start() + pos, range.end()));
201 inj.add_unmapped("\n");
203 inj.add_unmapped("\n}");
205 let (analysis, tmp_file_id) = Analysis::from_single_file(inj.text().to_string());
207 for h in analysis.with_db(|db| super::highlight(db, tmp_file_id, None, true)).unwrap() {
208 for r in inj.map_range_up(h.range) {
211 highlight: h.highlight | HlMod::Injected,
212 binding_hash: h.binding_hash,
217 for range in new_comments {
220 highlight: HlTag::Comment | HlMod::Documentation,