1use crate::parser::LangId;
4use aft_store::content::{TodoMarker, TodoMarkers};
5use std::path::Path;
6use tree_sitter::{Node, Tree};
7
8pub const MAX_LINES_PER_FILE: usize = 100_000;
9pub const MAX_TEXT_CHARS: usize = 200;
10pub const MARKERS: [&str; 5] = ["TODO", "FIXME", "HACK", "XXX", "BUG"];
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum TodoLanguage {
15 Tree(LangId),
17 Lexical,
20}
21
22impl TodoLanguage {
23 pub fn name(self) -> String {
26 match self {
27 Self::Tree(language) => format!("{language:?}").to_lowercase(),
28 Self::Lexical => "lexical".to_string(),
29 }
30 }
31
32 pub fn from_name(name: &str) -> Option<Self> {
34 if name == "lexical" {
35 return Some(Self::Lexical);
36 }
37 crate::callgraph_store::join::language_id(name).map(Self::Tree)
38 }
39}
40
41pub fn path_todo_language(path: &Path) -> Option<TodoLanguage> {
47 if is_plain_json(path) {
48 return None;
49 }
50 crate::parser::language_for_extension(path)
51 .or_else(|| crate::parser::detect_language_any(path, cfg!(feature = "wasm-grammars")))
52 .map(TodoLanguage::Tree)
53}
54
55pub fn is_header(path: &Path) -> bool {
58 path.extension().and_then(|extension| extension.to_str()) == Some("h")
59}
60
61pub fn header_matches(language: &str) -> bool {
66 matches!(language, "c" | "cpp" | "objc" | "lexical")
67}
68
69pub fn is_plain_json(path: &Path) -> bool {
72 path.extension()
73 .and_then(|extension| extension.to_str())
74 .is_some_and(|extension| extension.eq_ignore_ascii_case("json"))
75}
76
77pub fn text_of(source: &[u8]) -> Option<&str> {
80 if source.contains(&0) {
81 return None;
82 }
83 std::str::from_utf8(source).ok()
84}
85
86pub fn markers_from_tree(source: &[u8], language: LangId, tree: &Tree) -> TodoMarkers {
89 let items = text_of(source).map(|text| {
90 let mut comment_nodes = Vec::new();
91 collect_comment_nodes(tree.root_node(), language, text, &mut comment_nodes);
92 comment_nodes.sort_by_key(|node| node.start_byte());
93 let mut items = Vec::new();
94 for node in comment_nodes {
95 scan_comment_node(node, text, language, &mut items);
96 }
97 items.sort_by_key(|item| item.line);
98 items.dedup_by_key(|item| item.line);
99 items
100 });
101 TodoMarkers {
102 language: TodoLanguage::Tree(language).name(),
103 items,
104 }
105}
106
107pub fn markers_lexical(source: &[u8]) -> TodoMarkers {
110 let items = text_of(source).map(|text| {
111 let mut state = LexicalState::default();
112 text.lines()
113 .take(MAX_LINES_PER_FILE)
114 .enumerate()
115 .filter_map(|(index, line)| scan_lexical_line(line, index + 1, &mut state))
116 .collect()
117 });
118 TodoMarkers {
119 language: TodoLanguage::Lexical.name(),
120 items,
121 }
122}
123pub fn collect_comment_nodes<'tree>(
124 root: Node<'tree>,
125 language: LangId,
126 source: &str,
127 comments: &mut Vec<Node<'tree>>,
128) {
129 let mut pending = vec![root];
130 while let Some(node) = pending.pop() {
131 if is_comment_node(node, language, source) {
132 comments.push(node);
133 continue;
134 }
135
136 let mut children = Vec::new();
137 let mut cursor = node.walk();
138 if cursor.goto_first_child() {
139 loop {
140 children.push(cursor.node());
141 if !cursor.goto_next_sibling() {
142 break;
143 }
144 }
145 }
146 pending.extend(children.into_iter().rev());
147 }
148}
149
150pub fn is_comment_node(node: Node<'_>, language: LangId, source: &str) -> bool {
151 let kind = node.kind();
152 if language == LangId::Luau {
153 return crate::luau::COMMENT_KINDS.contains(&kind);
154 }
155 if kind == "comment" || kind.ends_with("_comment") {
156 return true;
157 }
158
159 language == LangId::Markdown
160 && matches!(kind, "html_block" | "html_inline")
161 && node
162 .utf8_text(source.as_bytes())
163 .is_ok_and(|text| text.trim_start().starts_with("<!--"))
164}
165
166pub fn scan_comment_node(
167 mut node: Node<'_>,
168 source: &str,
169 language: LangId,
170 items: &mut Vec<TodoMarker>,
171) {
172 if language == LangId::Luau {
173 let Some(content) = node.child_by_field_name("content") else {
176 return;
177 };
178 node = content;
179 }
180 let Ok(comment) = node.utf8_text(source.as_bytes()) else {
181 return;
182 };
183 let first_line = node.start_position().row + 1;
184 let mut in_block_comment = false;
185 for (offset, line) in comment.lines().enumerate() {
186 let line_number = first_line + offset;
187 if line_number > MAX_LINES_PER_FILE {
188 break;
189 }
190 let item = if language == LangId::Luau {
191 parse_todo_body(strip_block_comment_prefix(line), line_number)
192 } else {
193 scan_line(line, line_number, &mut in_block_comment)
194 };
195 if let Some(item) = item {
196 items.push(item);
197 }
198 }
199}
200
201#[derive(Debug, Clone, Copy)]
202pub struct QuoteState {
203 pub delimiter: u8,
204 pub raw_hashes: Option<usize>,
205}
206
207#[derive(Debug, Default)]
208pub struct LexicalState {
209 pub quote: Option<QuoteState>,
210 pub block_closer: Option<&'static str>,
211}
212
213pub fn scan_lexical_line(
214 line: &str,
215 line_number: usize,
216 state: &mut LexicalState,
217) -> Option<TodoMarker> {
218 let mut cursor = 0usize;
219 while cursor < line.len() {
220 if let Some(closer) = state.block_closer {
221 let closer_offset = line[cursor..].find(closer);
222 let body_end = closer_offset
223 .map(|offset| cursor + offset)
224 .unwrap_or(line.len());
225 let body = strip_block_comment_prefix(&line[cursor..body_end]);
226 let item = parse_todo_body(body, line_number);
227 let Some(closer_offset) = closer_offset else {
228 return item;
229 };
230 state.block_closer = None;
231 cursor += closer_offset + closer.len();
232 if item.is_some() {
233 return item;
234 }
235 continue;
236 }
237
238 if let Some(quote) = state.quote {
239 cursor = advance_quoted_cursor(line, cursor, quote, state);
240 continue;
241 }
242
243 if let Some((quote, after_opener)) = raw_quote_start(line, cursor) {
244 state.quote = Some(quote);
245 cursor = after_opener;
246 continue;
247 }
248
249 let byte = line.as_bytes()[cursor];
250 if matches!(byte, b'\'' | b'"' | b'`') {
251 state.quote = Some(QuoteState {
252 delimiter: byte,
253 raw_hashes: None,
254 });
255 cursor += 1;
256 continue;
257 }
258
259 let Some((prefix, closer)) = comment_prefix_at(line, cursor) else {
260 cursor += next_char_len(line, cursor);
261 continue;
262 };
263 if !is_comment_prefix_boundary(line, cursor, prefix) {
264 cursor += prefix.len();
265 continue;
266 }
267
268 let body_start = cursor + prefix.len();
269 if let Some(closer) = closer {
270 let closer_offset = line[body_start..].find(closer);
271 let body_end = closer_offset
272 .map(|offset| body_start + offset)
273 .unwrap_or(line.len());
274 let body = strip_block_comment_prefix(&line[body_start..body_end]);
275 let item = parse_todo_body(body, line_number);
276 if let Some(offset) = closer_offset {
277 cursor = body_start + offset + closer.len();
278 } else {
279 state.block_closer = Some(closer);
280 return item;
281 }
282 if item.is_some() {
283 return item;
284 }
285 continue;
286 }
287
288 return parse_todo_body(line[body_start..].trim_start(), line_number);
289 }
290
291 None
292}
293
294pub fn advance_quoted_cursor(
295 line: &str,
296 cursor: usize,
297 quote: QuoteState,
298 state: &mut LexicalState,
299) -> usize {
300 let byte = line.as_bytes()[cursor];
301 if quote.raw_hashes.is_none() && byte == b'\\' {
302 let escaped = cursor + 1;
303 return escaped + next_char_len(line, escaped);
304 }
305 if byte != quote.delimiter {
306 return cursor + next_char_len(line, cursor);
307 }
308
309 let hashes = quote.raw_hashes.unwrap_or_default();
310 let after_quote = cursor + 1;
311 let hashes_match = line.as_bytes().get(after_quote..).is_some_and(|rest| {
312 rest.len() >= hashes && rest[..hashes].iter().all(|byte| *byte == b'#')
313 });
314 if hashes_match {
315 state.quote = None;
316 after_quote + hashes
317 } else {
318 cursor + 1
319 }
320}
321
322pub fn raw_quote_start(line: &str, cursor: usize) -> Option<(QuoteState, usize)> {
323 if line.as_bytes().get(cursor) != Some(&b'r') {
324 return None;
325 }
326
327 let mut opener_end = cursor + 1;
328 while line.as_bytes().get(opener_end) == Some(&b'#') {
329 opener_end += 1;
330 }
331 if line.as_bytes().get(opener_end) != Some(&b'"') {
332 return None;
333 }
334
335 Some((
336 QuoteState {
337 delimiter: b'"',
338 raw_hashes: Some(opener_end - cursor - 1),
339 },
340 opener_end + 1,
341 ))
342}
343
344pub fn comment_prefix_at(
345 line: &str,
346 cursor: usize,
347) -> Option<(&'static str, Option<&'static str>)> {
348 let rest = &line[cursor..];
349 if rest.starts_with("<!--") {
350 Some(("<!--", Some("-->")))
351 } else if rest.starts_with("//") {
352 Some(("//", None))
353 } else if rest.starts_with("/*") {
354 Some(("/*", Some("*/")))
355 } else if rest.starts_with('#') {
356 Some(("#", None))
357 } else if rest.starts_with("--") {
358 Some(("--", None))
359 } else {
360 None
361 }
362}
363
364pub fn next_char_len(line: &str, cursor: usize) -> usize {
365 line.get(cursor..)
366 .and_then(|rest| rest.chars().next())
367 .map(char::len_utf8)
368 .unwrap_or_default()
369}
370
371pub fn scan_line(
372 line: &str,
373 line_number: usize,
374 in_block_comment: &mut bool,
375) -> Option<TodoMarker> {
376 if *in_block_comment {
377 let item = parse_todo_body(strip_block_comment_prefix(line), line_number);
378 if line.contains("*/") {
379 *in_block_comment = false;
380 }
381 if item.is_some() {
382 return item;
383 }
384 }
385
386 let mut search_start = 0usize;
387 let mut found_item = None;
388 while search_start < line.len() {
389 let Some(prefix_match) = find_next_comment_prefix(line, search_start) else {
390 break;
391 };
392 let body = &line[prefix_match.body_start..];
393 if prefix_match.starts_block_comment && !body.contains("*/") {
394 *in_block_comment = true;
395 }
396 let body = if prefix_match.starts_block_comment {
397 strip_block_comment_prefix(body)
398 } else {
399 body.trim_start()
400 };
401 if let Some(item) = parse_todo_body(body, line_number) {
402 found_item = Some(item);
403 break;
404 }
405 search_start = prefix_match.body_start;
406 }
407
408 found_item
409}
410
411#[derive(Debug, Clone, Copy)]
412pub struct CommentPrefixMatch {
413 pub body_start: usize,
414 pub starts_block_comment: bool,
415}
416
417pub fn find_next_comment_prefix(line: &str, search_start: usize) -> Option<CommentPrefixMatch> {
418 let prefixes = ["<!--", "//", "/*", "#", "--"];
419 prefixes
420 .iter()
421 .filter_map(|prefix| find_prefix_match(line, search_start, prefix))
422 .min_by_key(|prefix_match| prefix_match.body_start)
423}
424
425pub fn find_prefix_match(
426 line: &str,
427 search_start: usize,
428 prefix: &str,
429) -> Option<CommentPrefixMatch> {
430 let mut cursor = search_start;
431 while cursor < line.len() {
432 let offset = line[cursor..].find(prefix)?;
433 let prefix_start = cursor + offset;
434 if is_comment_prefix_boundary(line, prefix_start, prefix) {
435 return Some(CommentPrefixMatch {
436 body_start: prefix_start + prefix.len(),
437 starts_block_comment: prefix == "/*",
438 });
439 }
440 cursor = prefix_start + prefix.len();
441 }
442 None
443}
444
445pub fn is_comment_prefix_boundary(line: &str, prefix_start: usize, prefix: &str) -> bool {
446 if prefix == "<!--" {
447 return true;
448 }
449 prefix_start == 0
450 || line[..prefix_start]
451 .chars()
452 .next_back()
453 .is_some_and(char::is_whitespace)
454}
455
456pub fn strip_block_comment_prefix(body: &str) -> &str {
457 let mut trimmed = body.trim_start();
458 while let Some(rest) = trimmed.strip_prefix('*') {
459 trimmed = rest.trim_start();
460 }
461 trimmed
462}
463
464pub fn parse_todo_body(body: &str, line_number: usize) -> Option<TodoMarker> {
465 let body = body.trim_start();
466 for marker in MARKERS {
467 let Some(rest) = body.strip_prefix(marker) else {
468 continue;
469 };
470 let Some((author, text_start)) = parse_marker_suffix(marker, rest) else {
471 continue;
472 };
473 return Some(TodoMarker {
474 line: u32::try_from(line_number).unwrap_or(u32::MAX),
476 marker: marker.to_string(),
477 author,
478 text: truncate_text(strip_comment_closer(text_start)),
479 });
480 }
481 None
482}
483
484pub fn parse_marker_suffix<'a>(
485 marker: &'static str,
486 rest: &'a str,
487) -> Option<(Option<String>, &'a str)> {
488 if rest.is_empty() {
489 return Some((None, rest));
490 }
491
492 let trimmed = rest.trim_start();
493 if let Some(after_colon) = trimmed.strip_prefix(':') {
494 return Some((None, after_colon.trim_start()));
495 }
496 if let Some(after_author_start) = trimmed.strip_prefix('(') {
497 if !matches!(marker, "TODO" | "FIXME") {
498 return None;
499 }
500 let author_end = after_author_start.find(')')?;
501 let author = after_author_start[..author_end].trim();
502 if author.is_empty() {
503 return None;
504 }
505 let after_author = &after_author_start[author_end + 1..];
506 let after_author = after_author.trim_start();
507 let text_start = after_author
508 .strip_prefix(':')
509 .map(str::trim_start)
510 .unwrap_or(after_author);
511 return Some((Some(author.to_string()), text_start));
512 }
513 if rest.chars().next().is_some_and(char::is_whitespace) {
514 return Some((None, rest.trim_start()));
515 }
516 if rest.starts_with("*/") || rest.starts_with("-->") {
517 return Some((None, rest));
518 }
519 None
520}
521
522pub fn strip_comment_closer(text: &str) -> &str {
523 let mut trimmed = text.trim();
524 loop {
525 let without_closer = trimmed
526 .strip_suffix("*/")
527 .or_else(|| trimmed.strip_suffix("-->"));
528 let Some(next) = without_closer else {
529 break;
530 };
531 trimmed = next.trim_end();
532 }
533 trimmed
534}
535
536pub fn truncate_text(text: &str) -> String {
537 text.chars().take(MAX_TEXT_CHARS).collect()
538}