1 //! "Recursive" Syntax highlighting for code in doctests and fixtures.
6 use hir::{InFile, Semantics};
8 active_parameter::ActiveParameter, base_db::FileId, defs::Definition, rust_doc::is_rust_fence,
12 ast::{self, AstNode, IsString, QuoteOffsets},
13 AstToken, NodeOrToken, SyntaxNode, TextRange, TextSize,
17 doc_links::{doc_attributes, extract_definitions_from_docs, resolve_doc_path_for_def},
18 syntax_highlighting::{highlights::Highlights, injector::Injector},
19 Analysis, HlMod, HlRange, HlTag, RootDatabase,
22 pub(super) fn ra_fixture(
24 sema: &Semantics<'_, RootDatabase>,
25 literal: &ast::String,
26 expanded: &ast::String,
28 let active_parameter = ActiveParameter::at_token(sema, expanded.syntax().clone())?;
29 if !active_parameter.ident().map_or(false, |name| name.text().starts_with("ra_fixture")) {
32 let value = literal.value()?;
34 if let Some(range) = literal.open_quote_text_range() {
35 hl.add(HlRange { range, highlight: HlTag::StringLiteral.into(), binding_hash: None })
38 let mut inj = Injector::default();
40 let mut text = &*value;
41 let mut offset: TextSize = 0.into();
43 while !text.is_empty() {
45 let idx = text.find(marker).unwrap_or(text.len());
46 let (chunk, next) = text.split_at(idx);
47 inj.add(chunk, TextRange::at(offset, TextSize::of(chunk)));
50 offset += TextSize::of(chunk);
52 if let Some(next) = text.strip_prefix(marker) {
53 if let Some(range) = literal.map_range_up(TextRange::at(offset, TextSize::of(marker))) {
54 hl.add(HlRange { range, highlight: HlTag::Keyword.into(), binding_hash: None });
59 let marker_len = TextSize::of(marker);
64 let (analysis, tmp_file_id) = Analysis::from_single_file(inj.take_text());
66 for mut hl_range in analysis.highlight(tmp_file_id).unwrap() {
67 for range in inj.map_range_up(hl_range.range) {
68 if let Some(range) = literal.map_range_up(range) {
69 hl_range.range = range;
75 if let Some(range) = literal.close_quote_text_range() {
76 hl.add(HlRange { range, highlight: HlTag::StringLiteral.into(), binding_hash: None })
82 const RUSTDOC_FENCE_LENGTH: usize = 3;
83 const RUSTDOC_FENCES: [&str; 2] = ["```", "~~~"];
85 /// Injection of syntax highlighting of doctests and intra doc links.
86 pub(super) fn doc_comment(
88 sema: &Semantics<'_, RootDatabase>,
92 let (attributes, def) = match doc_attributes(sema, node) {
96 let src_file_id = src_file_id.into();
98 // Extract intra-doc links and emit highlights for them.
99 if let Some((docs, doc_mapping)) = attributes.docs_with_rangemap(sema.db) {
100 extract_definitions_from_docs(&docs)
102 .filter_map(|(range, link, ns)| {
103 doc_mapping.map(range).filter(|mapping| mapping.file_id == src_file_id).and_then(
104 |InFile { value: mapped_range, .. }| {
105 Some(mapped_range).zip(resolve_doc_path_for_def(sema.db, def, &link, ns))
109 .for_each(|(range, def)| {
112 highlight: module_def_to_hl_tag(def)
113 | HlMod::Documentation
115 | HlMod::IntraDocLink,
121 // Extract doc-test sources from the docs and calculate highlighting for them.
123 let mut inj = Injector::default();
124 inj.add_unmapped("fn doctest() {\n");
126 let attrs_source_map = attributes.source_map(sema.db);
128 let mut is_codeblock = false;
129 let mut is_doctest = false;
131 let mut new_comments = Vec::new();
134 for attr in attributes.by_key("doc").attrs() {
135 let InFile { file_id, value: src } = attrs_source_map.source_of(attr);
136 if file_id != src_file_id {
139 let (line, range) = match &src {
140 Either::Left(it) => {
141 string = match find_doc_string_in_attr(attr, it) {
145 let text = string.text();
146 let text_range = string.syntax().text_range();
147 match string.quote_offsets() {
148 Some(QuoteOffsets { contents, .. }) => {
149 (&text[contents - text_range.start()], contents)
151 None => (text, text_range),
154 Either::Right(comment) => {
155 let value = comment.prefix().len();
156 let range = comment.syntax().text_range();
158 &comment.text()[value..],
159 TextRange::new(range.start() + TextSize::try_from(value).unwrap(), range.end()),
164 let mut range_start = range.start();
165 for line in line.split('\n') {
166 let line_len = TextSize::from(line.len() as u32);
167 let prev_range_start = {
168 let next_range_start = range_start + line_len + TextSize::from(1);
169 mem::replace(&mut range_start, next_range_start)
171 let mut pos = TextSize::from(0);
173 match RUSTDOC_FENCES.into_iter().find_map(|fence| line.find(fence)) {
175 is_codeblock = !is_codeblock;
176 // Check whether code is rust by inspecting fence guards
177 let guards = &line[idx + RUSTDOC_FENCE_LENGTH..];
178 let is_rust = is_rust_fence(guards);
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.take_text());
209 if let Ok(ranges) = analysis.with_db(|db| super::highlight(db, tmp_file_id, None, true)) {
210 for HlRange { range, highlight, binding_hash } in ranges {
211 for range in inj.map_range_up(range) {
212 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: Definition) -> HlTag {
252 let symbol = match def {
253 Definition::Module(_) => SymbolKind::Module,
254 Definition::Function(_) => SymbolKind::Function,
255 Definition::Adt(hir::Adt::Struct(_)) => SymbolKind::Struct,
256 Definition::Adt(hir::Adt::Enum(_)) => SymbolKind::Enum,
257 Definition::Adt(hir::Adt::Union(_)) => SymbolKind::Union,
258 Definition::Variant(_) => SymbolKind::Variant,
259 Definition::Const(_) => SymbolKind::Const,
260 Definition::Static(_) => SymbolKind::Static,
261 Definition::Trait(_) => SymbolKind::Trait,
262 Definition::TypeAlias(_) => SymbolKind::TypeAlias,
263 Definition::BuiltinType(_) => return HlTag::BuiltinType,
264 Definition::Macro(_) => SymbolKind::Macro,
265 Definition::Field(_) => SymbolKind::Field,
266 Definition::SelfType(_) => SymbolKind::Impl,
267 Definition::Local(_) => SymbolKind::Local,
268 Definition::GenericParam(gp) => match gp {
269 hir::GenericParam::TypeParam(_) => SymbolKind::TypeParam,
270 hir::GenericParam::ConstParam(_) => SymbolKind::ConstParam,
271 hir::GenericParam::LifetimeParam(_) => SymbolKind::LifetimeParam,
273 Definition::Label(_) => SymbolKind::Label,
274 Definition::BuiltinAttr(_) => SymbolKind::BuiltinAttr,
275 Definition::ToolModule(_) => SymbolKind::ToolModule,
276 Definition::DeriveHelper(_) => SymbolKind::DeriveHelper,
278 HlTag::Symbol(symbol)