aboutsummaryrefslogtreecommitdiff
path: root/crates/ide/src/syntax_highlighting/inject.rs
blob: f359eacf2a0904ee3e597b17a4f44d90bff1d281 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
//! "Recursive" Syntax highlighting for code in doctests and fixtures.

use std::{mem, ops::Range};

use either::Either;
use hir::{HasAttrs, InFile, Semantics};
use ide_db::{call_info::ActiveParameter, defs::Definition, SymbolKind};
use syntax::{
    ast::{self, AstNode, AttrsOwner, DocCommentsOwner},
    match_ast, AstToken, NodeOrToken, SyntaxNode, SyntaxToken, TextRange, TextSize,
};

use crate::{
    doc_links::extract_definitions_from_markdown, Analysis, HlMod, HlRange, HlTag, RootDatabase,
};

use super::{highlights::Highlights, injector::Injector};

pub(super) fn ra_fixture(
    hl: &mut Highlights,
    sema: &Semantics<RootDatabase>,
    literal: ast::String,
    expanded: SyntaxToken,
) -> Option<()> {
    let active_parameter = ActiveParameter::at_token(&sema, expanded)?;
    if !active_parameter.name.starts_with("ra_fixture") {
        return None;
    }
    let value = literal.value()?;

    if let Some(range) = literal.open_quote_text_range() {
        hl.add(HlRange { range, highlight: HlTag::StringLiteral.into(), binding_hash: None })
    }

    let mut inj = Injector::default();

    let mut text = &*value;
    let mut offset: TextSize = 0.into();

    while !text.is_empty() {
        let marker = "$0";
        let idx = text.find(marker).unwrap_or(text.len());
        let (chunk, next) = text.split_at(idx);
        inj.add(chunk, TextRange::at(offset, TextSize::of(chunk)));

        text = next;
        offset += TextSize::of(chunk);

        if let Some(next) = text.strip_prefix(marker) {
            if let Some(range) = literal.map_range_up(TextRange::at(offset, TextSize::of(marker))) {
                hl.add(HlRange { range, highlight: HlTag::Keyword.into(), binding_hash: None });
            }

            text = next;

            let marker_len = TextSize::of(marker);
            offset += marker_len;
        }
    }

    let (analysis, tmp_file_id) = Analysis::from_single_file(inj.text().to_string());

    for mut hl_range in analysis.highlight(tmp_file_id).unwrap() {
        for range in inj.map_range_up(hl_range.range) {
            if let Some(range) = literal.map_range_up(range) {
                hl_range.range = range;
                hl.add(hl_range);
            }
        }
    }

    if let Some(range) = literal.close_quote_text_range() {
        hl.add(HlRange { range, highlight: HlTag::StringLiteral.into(), binding_hash: None })
    }

    Some(())
}

const RUSTDOC_FENCE: &'static str = "```";
const RUSTDOC_FENCE_TOKENS: &[&'static str] = &[
    "",
    "rust",
    "should_panic",
    "ignore",
    "no_run",
    "compile_fail",
    "edition2015",
    "edition2018",
    "edition2021",
];

// Basically an owned dyn AttrsOwner without extra Boxing
struct AttrsOwnerNode {
    node: SyntaxNode,
}

impl AttrsOwnerNode {
    fn new<N: DocCommentsOwner>(node: N) -> Self {
        AttrsOwnerNode { node: node.syntax().clone() }
    }
}

impl AttrsOwner for AttrsOwnerNode {}
impl AstNode for AttrsOwnerNode {
    fn can_cast(_: syntax::SyntaxKind) -> bool
    where
        Self: Sized,
    {
        false
    }
    fn cast(_: SyntaxNode) -> Option<Self>
    where
        Self: Sized,
    {
        None
    }
    fn syntax(&self) -> &SyntaxNode {
        &self.node
    }
}

fn doc_attributes<'node>(
    sema: &Semantics<RootDatabase>,
    node: &'node SyntaxNode,
) -> Option<(AttrsOwnerNode, hir::Attrs, Definition)> {
    match_ast! {
        match node {
            ast::SourceFile(it)  => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Module(def)))),
            ast::Module(it)      => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Module(def)))),
            ast::Fn(it)          => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Function(def)))),
            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))))),
            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))))),
            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))))),
            ast::Variant(it)     => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Variant(def)))),
            ast::Trait(it)       => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Trait(def)))),
            ast::Static(it)      => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Static(def)))),
            ast::Const(it)       => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::Const(def)))),
            ast::TypeAlias(it)   => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::ModuleDef(hir::ModuleDef::TypeAlias(def)))),
            ast::Impl(it)        => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::SelfType(def))),
            ast::RecordField(it) => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::Field(def))),
            ast::TupleField(it)  => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::Field(def))),
            ast::MacroRules(it)  => sema.to_def(&it).map(|def| (AttrsOwnerNode::new(it), def.attrs(sema.db), Definition::Macro(def))),
            // ast::MacroDef(it) => sema.to_def(&it).map(|def| (Box::new(it) as _, def.attrs(sema.db))),
            // ast::Use(it) => sema.to_def(&it).map(|def| (Box::new(it) as _, def.attrs(sema.db))),
            _ => return None
        }
    }
}

/// Injection of syntax highlighting of doctests.
pub(super) fn doc_comment(
    hl: &mut Highlights,
    sema: &Semantics<RootDatabase>,
    node: InFile<&SyntaxNode>,
) {
    let (owner, attributes, def) = match doc_attributes(sema, node.value) {
        Some(it) => it,
        None => return,
    };

    let mut inj = Injector::default();
    inj.add_unmapped("fn doctest() {\n");

    let attrs_source_map = match def {
        Definition::ModuleDef(hir::ModuleDef::Module(module)) => {
            attributes.source_map_for_module(sema.db, module.into())
        }
        _ => attributes.source_map(node.with_value(&owner)),
    };

    let mut is_codeblock = false;
    let mut is_doctest = false;

    // Replace the original, line-spanning comment ranges by new, only comment-prefix
    // spanning comment ranges.
    let mut new_comments = Vec::new();
    let mut intra_doc_links = Vec::new();
    let mut string;
    for attr in attributes.by_key("doc").attrs() {
        let InFile { file_id, value: src } = attrs_source_map.source_of(&attr);
        if file_id != node.file_id {
            continue;
        }
        let (line, range, prefix) = match &src {
            Either::Left(it) => {
                string = match find_doc_string_in_attr(attr, it) {
                    Some(it) => it,
                    None => continue,
                };
                let text_range = string.syntax().text_range();
                let text_range = TextRange::new(
                    text_range.start() + TextSize::from(1),
                    text_range.end() - TextSize::from(1),
                );
                let text = string.text();
                (&text[1..text.len() - 1], text_range, "")
            }
            Either::Right(comment) => {
                (comment.text(), comment.syntax().text_range(), comment.prefix())
            }
        };

        let mut pos = TextSize::from(prefix.len() as u32);
        let mut range_start = range.start();
        for line in line.split('\n') {
            let line_len = TextSize::from(line.len() as u32);
            let prev_range_start = {
                let next_range_start = range_start + line_len + TextSize::from(1);
                mem::replace(&mut range_start, next_range_start)
            };
            // only first line has the prefix so take it away for future iterations
            let mut pos = mem::take(&mut pos);

            match line.find(RUSTDOC_FENCE) {
                Some(idx) => {
                    is_codeblock = !is_codeblock;
                    // Check whether code is rust by inspecting fence guards
                    let guards = &line[idx + RUSTDOC_FENCE.len()..];
                    let is_rust =
                        guards.split(',').all(|sub| RUSTDOC_FENCE_TOKENS.contains(&sub.trim()));
                    is_doctest = is_codeblock && is_rust;
                    continue;
                }
                None if !is_doctest => {
                    intra_doc_links.extend(
                        extract_definitions_from_markdown(line)
                            .into_iter()
                            .filter_map(|(link, ns, range)| {
                                validate_intra_doc_link(sema.db, &def, &link, ns).zip(Some(range))
                            })
                            .map(|(def, Range { start, end })| {
                                (
                                    def,
                                    TextRange::at(
                                        prev_range_start + TextSize::from(start as u32),
                                        TextSize::from((end - start) as u32),
                                    ),
                                )
                            }),
                    );
                    continue;
                }
                None => (),
            }

            // whitespace after comment is ignored
            if let Some(ws) = line[pos.into()..].chars().next().filter(|c| c.is_whitespace()) {
                pos += TextSize::of(ws);
            }
            // lines marked with `#` should be ignored in output, we skip the `#` char
            if line[pos.into()..].starts_with('#') {
                pos += TextSize::of('#');
            }

            new_comments.push(TextRange::at(prev_range_start, pos));
            inj.add(&line[pos.into()..], TextRange::new(pos, line_len) + prev_range_start);
            inj.add_unmapped("\n");
        }
    }

    for (def, range) in intra_doc_links {
        hl.add(HlRange {
            range,
            highlight: module_def_to_hl_tag(def)
                | HlMod::Documentation
                | HlMod::Injected
                | HlMod::IntraDocLink,
            binding_hash: None,
        });
    }

    if new_comments.is_empty() {
        return; // no need to run an analysis on an empty file
    }

    inj.add_unmapped("\n}");

    let (analysis, tmp_file_id) = Analysis::from_single_file(inj.text().to_string());

    for HlRange { range, highlight, binding_hash } in
        analysis.with_db(|db| super::highlight(db, tmp_file_id, None, true)).unwrap()
    {
        for range in inj.map_range_up(range) {
            hl.add(HlRange { range, highlight: highlight | HlMod::Injected, binding_hash });
        }
    }

    for range in new_comments {
        hl.add(HlRange {
            range,
            highlight: HlTag::Comment | HlMod::Documentation,
            binding_hash: None,
        });
    }
}

fn find_doc_string_in_attr(attr: &hir::Attr, it: &ast::Attr) -> Option<ast::String> {
    match it.literal() {
        // #[doc = lit]
        Some(lit) => match lit.kind() {
            ast::LiteralKind::String(it) => Some(it),
            _ => None,
        },
        // #[cfg_attr(..., doc = "", ...)]
        None => {
            // We gotta hunt the string token manually here
            let text = attr.string_value()?;
            // FIXME: We just pick the first string literal that has the same text as the doc attribute
            // This means technically we might highlight the wrong one
            it.syntax()
                .descendants_with_tokens()
                .filter_map(NodeOrToken::into_token)
                .filter_map(ast::String::cast)
                .find(|string| {
                    string.text().get(1..string.text().len() - 1).map_or(false, |it| it == text)
                })
        }
    }
}

fn validate_intra_doc_link(
    db: &RootDatabase,
    def: &Definition,
    link: &str,
    ns: Option<hir::Namespace>,
) -> Option<hir::ModuleDef> {
    match def {
        Definition::ModuleDef(def) => match def {
            hir::ModuleDef::Module(it) => it.resolve_doc_path(db, &link, ns),
            hir::ModuleDef::Function(it) => it.resolve_doc_path(db, &link, ns),
            hir::ModuleDef::Adt(it) => it.resolve_doc_path(db, &link, ns),
            hir::ModuleDef::Variant(it) => it.resolve_doc_path(db, &link, ns),
            hir::ModuleDef::Const(it) => it.resolve_doc_path(db, &link, ns),
            hir::ModuleDef::Static(it) => it.resolve_doc_path(db, &link, ns),
            hir::ModuleDef::Trait(it) => it.resolve_doc_path(db, &link, ns),
            hir::ModuleDef::TypeAlias(it) => it.resolve_doc_path(db, &link, ns),
            hir::ModuleDef::BuiltinType(_) => None,
        },
        Definition::Macro(it) => it.resolve_doc_path(db, &link, ns),
        Definition::Field(it) => it.resolve_doc_path(db, &link, ns),
        Definition::SelfType(_)
        | Definition::Local(_)
        | Definition::GenericParam(_)
        | Definition::Label(_) => None,
    }
}

fn module_def_to_hl_tag(def: hir::ModuleDef) -> HlTag {
    let symbol = match def {
        hir::ModuleDef::Module(_) => SymbolKind::Module,
        hir::ModuleDef::Function(_) => SymbolKind::Function,
        hir::ModuleDef::Adt(hir::Adt::Struct(_)) => SymbolKind::Struct,
        hir::ModuleDef::Adt(hir::Adt::Enum(_)) => SymbolKind::Enum,
        hir::ModuleDef::Adt(hir::Adt::Union(_)) => SymbolKind::Union,
        hir::ModuleDef::Variant(_) => SymbolKind::Variant,
        hir::ModuleDef::Const(_) => SymbolKind::Const,
        hir::ModuleDef::Static(_) => SymbolKind::Static,
        hir::ModuleDef::Trait(_) => SymbolKind::Trait,
        hir::ModuleDef::TypeAlias(_) => SymbolKind::TypeAlias,
        hir::ModuleDef::BuiltinType(_) => return HlTag::BuiltinType,
    };
    HlTag::Symbol(symbol)
}