1use crate::resolve_language;
2use std::{
3 collections::{BTreeMap, HashMap},
4 ops::Range,
5};
6use tree_sitter::{
7 Language, Node, Query, QueryCursor, QueryError, QueryMatch, StreamingIterator, Tree,
8};
9
10const SIGNATURE_LINES: usize = 12;
11const BODY_KINDS: [&str; 5] = [
12 "block",
13 "statement_block",
14 "declaration_list",
15 "class_body",
16 "compound_statement",
17];
18const RUSTDOC_FENCE_ATTRIBUTES: [&str; 6] = [
19 "ignore",
20 "no_run",
21 "should_panic",
22 "compile_fail",
23 "test_harness",
24 "standalone_crate",
25];
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28pub enum SymbolKind {
29 Function,
30 Method,
31 Type,
32 Interface,
33 Module,
34 Constant,
35 Macro,
36 Implementation,
37}
38
39#[derive(Debug, Clone, PartialEq, Eq, Hash)]
40pub struct LineSpan {
41 pub line: usize,
42 pub columns: Range<usize>,
43}
44
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct SymbolDefinition {
47 pub name: String,
48 pub kind: SymbolKind,
49 pub name_span: LineSpan,
50 pub lines: Range<usize>,
51 pub signature: String,
52 pub docs: Option<String>,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct SymbolReference {
57 pub name: String,
58 pub span: LineSpan,
59}
60
61#[derive(Debug, Clone, Default, PartialEq, Eq)]
62pub struct SymbolTags {
63 pub definitions: Vec<SymbolDefinition>,
64 pub references: Vec<SymbolReference>,
65}
66
67impl SymbolTags {
68 pub fn enclosing(&self, line: usize) -> impl Iterator<Item = &SymbolDefinition> {
69 self.definitions
70 .iter()
71 .filter(move |definition| definition.lines.contains(&line))
72 }
73
74 #[must_use]
75 pub fn references_on(&self, line: usize) -> &[SymbolReference] {
76 let start = self
77 .references
78 .partition_point(|reference| reference.span.line < line);
79 let end = self
80 .references
81 .partition_point(|reference| reference.span.line <= line);
82 &self.references[start..end]
83 }
84}
85
86pub fn has_symbols(language: &str, source: &str) -> bool {
87 resolve_language(language, source)
88 .and_then(tags_query)
89 .is_some()
90}
91
92fn tags_query(language: &str) -> Option<&'static str> {
93 Some(match language {
94 "go" => include_str!("../queries/tags/go.scm"),
95 "javascript" => {
96 concat!(
97 include_str!("../queries/tags/javascript.scm"),
98 include_str!("../queries/tags/jsdoc.scm")
99 )
100 }
101 "python" => include_str!("../queries/tags/python.scm"),
102 "rust" => include_str!("../queries/tags/rust.scm"),
103 "tsx" | "typescript" => {
104 concat!(
105 include_str!("../queries/tags/typescript.scm"),
106 include_str!("../queries/tags/jsdoc.scm")
107 )
108 }
109 _ => return None,
110 })
111}
112
113#[derive(Debug, Clone, Copy)]
114enum Role {
115 Definition(SymbolKind),
116 Reference,
117}
118
119#[derive(Debug, Clone, Copy)]
120enum Capture {
121 Name,
122 Doc,
123 Documented,
124 Role(Role),
125 Other,
126}
127
128impl Capture {
129 fn parse(name: &str) -> Self {
130 match name {
131 "name" => Self::Name,
132 "doc" => Self::Doc,
133 "documented" => Self::Documented,
134 _ if name.starts_with("reference.") => Self::Role(Role::Reference),
135 _ => name
136 .strip_prefix("definition.")
137 .map_or(Self::Other, |kind| {
138 Self::Role(Role::Definition(kind_of(kind)))
139 }),
140 }
141 }
142}
143
144fn kind_of(kind: &str) -> SymbolKind {
145 match kind {
146 "function" => SymbolKind::Function,
147 "method" => SymbolKind::Method,
148 "interface" => SymbolKind::Interface,
149 "module" => SymbolKind::Module,
150 "constant" => SymbolKind::Constant,
151 "macro" => SymbolKind::Macro,
152 "implementation" => SymbolKind::Implementation,
153 _ => SymbolKind::Type,
154 }
155}
156
157#[derive(Debug)]
158pub(crate) struct TagsGrammar {
159 rust: bool,
160 query: Query,
161 captures: Vec<Capture>,
162}
163
164impl TagsGrammar {
165 pub(crate) fn new(language: &str, grammar: &Language) -> Result<Option<Self>, QueryError> {
166 let Some(source) = tags_query(language) else {
167 return Ok(None);
168 };
169 let query = Query::new(grammar, source)?;
170 let captures = query
171 .capture_names()
172 .iter()
173 .map(|name| Capture::parse(name))
174 .collect();
175 Ok(Some(Self {
176 rust: language == "rust",
177 query,
178 captures,
179 }))
180 }
181
182 pub(crate) fn extract(&self, tree: &Tree, source: &str) -> SymbolTags {
183 let mut cursor = QueryCursor::new();
184 let mut matches = cursor.matches(&self.query, tree.root_node(), source.as_bytes());
185 let mut collector = TagCollector::new(source);
186 while let Some(found) = matches.next() {
187 collector.add(found.pattern_index, self.read_match(found));
188 }
189 collector.finish(self.rust)
190 }
191
192 fn read_match<'tree>(&self, found: &QueryMatch<'_, 'tree>) -> MatchedTag<'tree> {
193 let mut tag = MatchedTag::default();
194 for capture in found.captures() {
195 match self.captures[capture.index as usize] {
196 Capture::Name => tag.name = Some(capture.node),
197 Capture::Doc => tag.comments.push(capture.node),
198 Capture::Documented => tag.documented = Some(capture.node),
199 Capture::Role(role) => tag.role = Some((role, capture.node)),
200 Capture::Other => {}
201 }
202 }
203 tag
204 }
205}
206
207#[derive(Default)]
208struct MatchedTag<'tree> {
209 name: Option<Node<'tree>>,
210 role: Option<(Role, Node<'tree>)>,
211 documented: Option<Node<'tree>>,
212 comments: Vec<Node<'tree>>,
213}
214
215struct PendingDefinition<'tree> {
216 pattern: usize,
217 item: Node<'tree>,
218 definition: SymbolDefinition,
219}
220
221type NameKey = (usize, usize);
222
223struct TagCollector<'a, 'tree> {
224 source: &'a str,
225 definitions: BTreeMap<NameKey, PendingDefinition<'tree>>,
226 references: BTreeMap<NameKey, SymbolReference>,
227 docs: HashMap<usize, BTreeMap<usize, Node<'tree>>>,
228}
229
230impl<'a, 'tree> TagCollector<'a, 'tree> {
231 fn new(source: &'a str) -> Self {
232 Self {
233 source,
234 definitions: BTreeMap::new(),
235 references: BTreeMap::new(),
236 docs: HashMap::new(),
237 }
238 }
239
240 fn add(&mut self, pattern: usize, tag: MatchedTag<'tree>) {
241 if let Some(item) = tag.documented {
242 let comments = tag
243 .comments
244 .into_iter()
245 .map(|comment| (comment.start_byte(), comment));
246 self.docs.entry(item.id()).or_default().extend(comments);
247 }
248 let (Some(name), Some((role, item))) = (tag.name, tag.role) else {
249 return;
250 };
251 let Some(text) = symbol_text(self.source, name) else {
252 return;
253 };
254 match role {
255 Role::Definition(kind) => self.add_definition(pattern, kind, name, text, item),
256 Role::Reference => self.add_reference(name, text),
257 }
258 }
259
260 fn add_definition(
261 &mut self,
262 pattern: usize,
263 kind: SymbolKind,
264 name: Node<'tree>,
265 text: &str,
266 item: Node<'tree>,
267 ) {
268 let key = name_key(name);
269 if self
270 .definitions
271 .get(&key)
272 .is_some_and(|existing| existing.pattern <= pattern)
273 {
274 return;
275 }
276 let definition = SymbolDefinition {
277 name: text.to_owned(),
278 kind,
279 name_span: span(name),
280 lines: lines(item),
281 signature: signature(item, self.source),
282 docs: None,
283 };
284 self.definitions.insert(
285 key,
286 PendingDefinition {
287 pattern,
288 item,
289 definition,
290 },
291 );
292 }
293
294 fn add_reference(&mut self, name: Node<'tree>, text: &str) {
295 self.references
296 .entry(name_key(name))
297 .or_insert_with(|| SymbolReference {
298 name: text.to_owned(),
299 span: span(name),
300 });
301 }
302
303 fn finish(self, rust: bool) -> SymbolTags {
304 let Self {
305 source,
306 definitions,
307 mut references,
308 docs,
309 } = self;
310 references.retain(|key, _| !definitions.contains_key(key));
311 let definitions = definitions
312 .into_values()
313 .map(
314 |PendingDefinition {
315 item, definition, ..
316 }| SymbolDefinition {
317 docs: docs
318 .get(&item.id())
319 .and_then(|comments| render_docs(item, comments, source, rust)),
320 ..definition
321 },
322 )
323 .collect();
324 SymbolTags {
325 definitions,
326 references: references.into_values().collect(),
327 }
328 }
329}
330
331fn symbol_text<'a>(source: &'a str, name: Node<'_>) -> Option<&'a str> {
332 source
333 .get(name.byte_range())
334 .filter(|text| !text.is_empty() && !text.contains('\n'))
335}
336
337fn name_key(name: Node<'_>) -> NameKey {
338 (name.start_byte(), name.end_byte())
339}
340
341fn signature(item: Node<'_>, source: &str) -> String {
342 let mut cursor = item.walk();
343 let start = item
344 .children(&mut cursor)
345 .find(|child| !is_preamble(*child))
346 .unwrap_or(item);
347 let end = body(item)
348 .filter(|body| BODY_KINDS.contains(&body.kind()))
349 .map_or(item.end_byte(), |body| body.start_byte());
350 let text = source
351 .get(start.start_byte()..end)
352 .unwrap_or_default()
353 .trim_end();
354 let line_start = source[..start.start_byte()]
355 .rfind('\n')
356 .map_or(0, |index| index + 1);
357 let indent = source[line_start..]
358 .bytes()
359 .take_while(|byte| matches!(byte, b' ' | b'\t'))
360 .count();
361 let mut lines: Vec<&str> = text
362 .lines()
363 .enumerate()
364 .map(|(index, line)| {
365 if index == 0 {
366 line
367 } else {
368 strip_indent(line, indent)
369 }
370 })
371 .collect();
372 if lines.len() > SIGNATURE_LINES {
373 lines.truncate(SIGNATURE_LINES);
374 lines.push("…");
375 }
376 lines.join("\n")
377}
378
379fn is_preamble(node: Node<'_>) -> bool {
380 matches!(
381 node.kind(),
382 "attributes" | "decorator" | "comment" | "line_comment" | "block_comment"
383 )
384}
385
386fn body(item: Node<'_>) -> Option<Node<'_>> {
387 item.child_by_field_name("body").or_else(|| {
388 item.child_by_field_name("value")?
389 .child_by_field_name("body")
390 })
391}
392
393fn strip_indent(line: &str, indent: usize) -> &str {
394 let skip = line
395 .bytes()
396 .take(indent)
397 .take_while(|byte| matches!(byte, b' ' | b'\t'))
398 .count();
399 &line[skip..]
400}
401
402fn render_docs(
403 item: Node<'_>,
404 comments: &BTreeMap<usize, Node<'_>>,
405 source: &str,
406 rust: bool,
407) -> Option<String> {
408 let mut blocks: Vec<String> = comments
409 .values()
410 .rev()
411 .take_while(|comment| {
412 comment.start_byte() >= item.start_byte()
413 || comment
414 .next_sibling()
415 .is_none_or(|next| comment.end_position().row + 1 >= next.start_position().row)
416 })
417 .map(|comment| clean_comment(source.get(comment.byte_range()).unwrap_or_default()))
418 .collect();
419 blocks.reverse();
420 let docs = tidy_docs(&blocks.join("\n"), rust);
421 (!docs.is_empty()).then_some(docs)
422}
423
424fn tidy_docs(docs: &str, rust: bool) -> String {
425 if !rust {
426 return docs.trim().to_owned();
427 }
428 let mut fence: Option<(&str, bool)> = None;
429 let lines: Vec<&str> = docs
430 .lines()
431 .filter(|line| {
432 let trimmed = line.trim_start();
433 match fence {
434 Some((marker, _)) if trimmed.starts_with(marker) => fence = None,
435 Some((_, hides)) => {
436 return !(hides && (trimmed == "#" || trimmed.starts_with("# ")));
437 }
438 None => {
439 fence = fence_marker(trimmed)
440 .map(|marker| (marker, is_rust_fence(&trimmed[marker.len()..])));
441 }
442 }
443 true
444 })
445 .collect();
446 lines.join("\n").trim().to_owned()
447}
448
449fn fence_marker(line: &str) -> Option<&str> {
450 let ticks = line.len() - line.trim_start_matches('`').len();
451 let tildes = line.len() - line.trim_start_matches('~').len();
452 let length = ticks.max(tildes);
453 (length >= 3).then(|| &line[..length])
454}
455
456fn is_rust_fence(info: &str) -> bool {
457 info.split([',', ' '])
458 .map(str::trim)
459 .filter(|token| !token.is_empty())
460 .all(|token| {
461 token == "rust"
462 || token.starts_with("edition")
463 || RUSTDOC_FENCE_ATTRIBUTES.contains(&token)
464 })
465}
466
467fn clean_comment(text: &str) -> String {
468 let text = text.trim();
469 if let Some(line) = line_comment(text) {
470 return line.to_owned();
471 }
472 block_comment(text)
473 .unwrap_or_else(|| dedent(text))
474 .trim()
475 .to_owned()
476}
477
478fn line_comment(text: &str) -> Option<&str> {
479 let body = text.strip_prefix("//")?;
480 let body = body
481 .strip_prefix('!')
482 .unwrap_or_else(|| body.trim_start_matches('/'));
483 Some(body.trim_prefix(' '))
484}
485
486fn block_comment(text: &str) -> Option<String> {
487 let body = text.strip_prefix("/*")?;
488 let body = body.trim_suffix("*/");
489 let body = body.trim_prefix('*');
490 let lines: Vec<&str> = body
491 .lines()
492 .map(|line| {
493 let line = line.trim();
494 let line = line.trim_prefix('*');
495 line.trim_prefix(' ')
496 })
497 .collect();
498 Some(lines.join("\n"))
499}
500
501fn dedent(text: &str) -> String {
502 let indent = text
503 .lines()
504 .skip(1)
505 .filter(|line| !line.trim().is_empty())
506 .map(|line| line.len() - line.trim_start().len())
507 .min()
508 .unwrap_or(0);
509 let lines: Vec<&str> = text
510 .lines()
511 .enumerate()
512 .map(|(index, line)| {
513 if index == 0 {
514 line
515 } else {
516 line.get(indent..).unwrap_or_default().trim_end()
517 }
518 })
519 .collect();
520 lines.join("\n")
521}
522
523fn span(node: Node<'_>) -> LineSpan {
524 let start = node.start_position();
525 LineSpan {
526 line: start.row,
527 columns: start.column..start.column + node.byte_range().len(),
528 }
529}
530
531fn lines(node: Node<'_>) -> Range<usize> {
532 node.start_position().row..node.end_position().row + 1
533}