1use crate::Limits;
6use crate::api::{Ev, parse};
7use crate::langs::{Cont, Lang, Rule, Sp, is_leading, rule};
8use crate::table::Language;
9
10const MAX_INPUT: usize = 2 << 20;
12const MAX_ERROR_PERCENT: usize = 20;
14const MAX_SYMBOLS: usize = 2000;
15const MAX_IMPORTS: usize = 500;
16const MAX_TEXT: usize = 200;
17const MAX_DEPTH: u32 = 64;
18const MAX_MILLIS: u64 = 3000;
19
20#[derive(Clone, Copy, PartialEq, Eq, Debug)]
21pub enum SymbolKind {
22 Function,
23 Method,
24 Class,
25 Struct,
26 Enum,
27 Interface,
28 Trait,
29 Type,
30 Module,
31}
32
33#[derive(Clone, Debug)]
34pub struct Symbol {
35 pub kind: SymbolKind,
36 pub name: String,
38 pub start_line: u32,
39 pub end_line: u32,
40 pub depth: u32,
41}
42
43#[derive(Clone, Debug)]
45pub struct Section {
46 pub start: usize,
47 pub end: usize,
48 pub title: Option<String>,
50}
51
52#[derive(Clone, Debug, Default)]
53pub struct Outline {
54 pub symbols: Vec<Symbol>,
55 pub imports: Vec<String>,
56 pub sections: Vec<Section>,
57}
58
59pub fn outline(tag: &str, source: &str) -> Option<Outline> {
61 let lang = Lang::from_tag(tag)?;
62 if source.is_empty() || source.len() > MAX_INPUT {
63 return None;
64 }
65 std::panic::catch_unwind(|| run(lang, source))
67 .ok()
68 .flatten()
69}
70
71fn run(lang: Lang, source: &str) -> Option<Outline> {
72 let table = lang.table()?;
73 let limits = Limits {
74 max_millis: MAX_MILLIS,
75 ..Limits::default()
76 };
77 let tree = parse(table, source.as_bytes(), limits);
78 if tree.truncated {
79 return None;
80 }
81 let nodes = Nodes::build(&tree, table)?;
82 if nodes.error_bytes * 100 > source.len() * MAX_ERROR_PERCENT {
83 return None;
84 }
85 let mut w = Walker {
86 lang,
87 source,
88 nodes: &nodes,
89 lines: line_starts(source),
90 out: Outline::default(),
91 };
92 let mut elements = Vec::new();
93 w.flatten(nodes.top(), 0, &mut elements);
94 let mut anchors = Vec::new();
95 let single_scope = w.single_scope(&elements);
96 for (i, &e) in elements.iter().enumerate() {
97 let before = w.out.symbols.len();
98 let mut first = None;
99 if single_scope == Some(i) && w.scope_inner(e, &mut anchors) {
100 continue;
101 }
102 w.walk(e, false, 0, 0, &mut first);
103 if w.out.symbols.len() > before
104 && let Some(title) = first
105 {
106 anchors.push((w.anchor_start(&elements, i), nodes.n[e].end, title));
107 }
108 }
109 if w.out.symbols.is_empty() {
110 return None;
111 }
112 let mut out = w.out;
113 out.sections = sections(source, anchors);
114 Some(out)
115}
116
117fn sections(source: &str, anchors: Vec<(usize, usize, String)>) -> Vec<Section> {
119 let mut out: Vec<Section> = Vec::with_capacity(anchors.len() + 1);
120 let mut at = 0usize;
121 for (i, (start, end, title)) in anchors.into_iter().enumerate() {
122 if i == 0 && !source.get(..start).unwrap_or("").trim().is_empty() {
123 out.push(Section {
124 start: 0,
125 end: start,
126 title: None,
127 });
128 at = start;
129 }
130 if end <= at {
132 continue;
133 }
134 let stop = line_end(source, end);
135 out.push(Section {
136 start: at,
137 end: stop,
138 title: Some(title),
139 });
140 at = stop;
141 }
142 match out.last_mut() {
143 Some(last) => last.end = source.len(),
144 None => out.push(Section {
145 start: 0,
146 end: source.len(),
147 title: None,
148 }),
149 }
150 out
151}
152
153fn line_end(source: &str, at: usize) -> usize {
154 match source
155 .as_bytes()
156 .get(at..)
157 .and_then(|b| b.iter().position(|&c| c == b'\n'))
158 {
159 Some(p) => at + p + 1,
160 None => source.len(),
161 }
162}
163
164fn line_starts(source: &str) -> Vec<usize> {
165 let mut v = vec![0];
166 v.extend(
167 source
168 .bytes()
169 .enumerate()
170 .filter(|(_, b)| *b == b'\n')
171 .map(|(i, _)| i + 1),
172 );
173 v
174}
175
176struct Node {
177 kind: &'static str,
178 field: Option<&'static str>,
179 start: usize,
180 end: usize,
181 children: Vec<u32>,
182}
183
184struct Nodes {
186 n: Vec<Node>,
187 error_bytes: usize,
188}
189
190impl Nodes {
191 fn build(tree: &crate::api::ParseTree, table: &'static Language) -> Option<Nodes> {
192 let mut n = vec![Node {
193 kind: "",
194 field: None,
195 start: 0,
196 end: 0,
197 children: Vec::new(),
198 }];
199 let mut stack = vec![(0u32, false)];
200 let mut error_bytes = 0usize;
201 tree.visit(table, |ev| match ev {
202 Ev::Open(v) => {
203 let id = n.len() as u32;
204 let (parent, in_error) = *stack.last().unwrap_or(&(0, false));
205 if v.error && !in_error {
206 error_bytes += v.end.saturating_sub(v.start);
207 }
208 n.push(Node {
209 kind: v.kind,
210 field: v.field,
211 start: v.start,
212 end: v.end,
213 children: Vec::new(),
214 });
215 n[parent as usize].children.push(id);
216 stack.push((id, in_error || v.error));
217 }
218 Ev::Close => {
219 stack.pop();
220 }
221 });
222 Some(Nodes { n, error_bytes })
223 }
224
225 fn top(&self) -> usize {
227 match self.n[0].children.as_slice() {
228 [only] => *only as usize,
229 _ => 0,
230 }
231 }
232
233 fn field(&self, id: usize, name: &str) -> Option<usize> {
234 self.n[id]
235 .children
236 .iter()
237 .map(|&c| c as usize)
238 .find(|&c| self.n[c].field == Some(name))
239 }
240}
241
242struct Walker<'a> {
243 lang: Lang,
244 source: &'a str,
245 nodes: &'a Nodes,
246 lines: Vec<usize>,
247 out: Outline,
248}
249
250impl Walker<'_> {
251 fn text(&self, id: usize) -> &str {
252 let n = &self.nodes.n[id];
253 self.source.get(n.start..n.end).unwrap_or("")
254 }
255
256 fn clean(&self, s: &str) -> String {
258 let mut out = String::with_capacity(s.len().min(MAX_TEXT));
259 for word in s.split_whitespace() {
260 if !out.is_empty() {
261 out.push(' ');
262 }
263 for c in word.chars() {
264 if out.len() + c.len_utf8() > MAX_TEXT {
265 return out;
266 }
267 out.push(c);
268 }
269 }
270 out
271 }
272
273 fn line(&self, at: usize) -> u32 {
274 self.lines.partition_point(|&s| s <= at) as u32
275 }
276
277 fn flatten(&self, id: usize, depth: u32, out: &mut Vec<usize>) {
279 for &c in &self.nodes.n[id].children {
280 let c = c as usize;
281 if matches!(rule(self.lang, self.nodes.n[c].kind), Rule::Flat) && depth < MAX_DEPTH {
282 self.flatten(c, depth + 1, out);
283 } else {
284 out.push(c);
285 }
286 }
287 }
288
289 fn anchor_start(&self, elements: &[usize], i: usize) -> usize {
291 let mut line = self.line(self.nodes.n[elements[i]].start);
292 for &e in elements[..i].iter().rev() {
293 let n = &self.nodes.n[e];
294 if !is_leading(n.kind) {
295 break;
296 }
297 let end_line = self.line(n.end.saturating_sub(1).max(n.start));
299 if end_line + 1 != line {
300 break;
301 }
302 line = self.line(n.start);
303 }
304 self.lines[line.saturating_sub(1) as usize]
305 }
306
307 fn name(&self, id: usize) -> String {
308 let field = if self.nodes.n[id].kind == "impl_item" {
310 "type"
311 } else {
312 "name"
313 };
314 if let Some(c) = self.nodes.field(id, field) {
315 return self.clean(self.text(c));
316 }
317 for c in self.children(id) {
319 if self.nodes.n[c].kind == "defun_header"
320 && let Some(n) = self.nodes.field(c, "function_name")
321 {
322 return self.clean(self.text(n));
323 }
324 }
325 let mut at = id;
327 for _ in 0..16 {
328 let next = self.nodes.field(at, "declarator").or_else(|| {
329 self.nodes.n[at]
330 .children
331 .iter()
332 .map(|&c| c as usize)
333 .find(|&c| {
334 let k = self.nodes.n[c].kind;
335 k.ends_with("declarator")
336 || is_identifier(k)
337 || matches!(
338 k,
339 "signature"
340 | "type_head"
341 | "call_expression"
342 | "where_expression"
343 | "typed_expression"
344 | "type_name"
345 | "function_clause"
346 | "function_command"
347 | "macro_command"
348 | "argument_list"
349 | "argument"
350 | "parametrized_type_expression"
351 )
352 })
353 });
354 match next {
355 Some(c) if is_identifier(self.nodes.n[c].kind) => return self.clean(self.text(c)),
356 Some(c) => at = c,
357 None => break,
358 }
359 }
360 String::new()
361 }
362
363 fn push(
364 &mut self,
365 kind: SymbolKind,
366 label: &str,
367 name: String,
368 id: usize,
369 depth: u32,
370 first: &mut Option<String>,
371 ) {
372 if self.out.symbols.len() >= MAX_SYMBOLS {
373 return;
374 }
375 if first.is_none() {
376 *first = Some(if name.is_empty() {
377 label.to_string()
378 } else {
379 format!("{label} {name}")
380 });
381 }
382 let (s, e) = (self.nodes.n[id].start, self.nodes.n[id].end);
383 let (start_line, end_line) = (self.line(s), self.line(e.saturating_sub(1).max(s)));
384 self.out.symbols.push(Symbol {
385 kind,
386 name,
387 start_line,
388 end_line,
389 depth,
390 });
391 }
392
393 fn import(&mut self, id: usize) {
394 if self.out.imports.len() < MAX_IMPORTS {
395 let t = self.clean(self.text(id));
396 self.out.imports.push(t);
397 }
398 }
399
400 fn children(&self, id: usize) -> Vec<usize> {
401 self.nodes.n[id]
402 .children
403 .iter()
404 .map(|&c| c as usize)
405 .collect()
406 }
407
408 fn single_scope(&self, elements: &[usize]) -> Option<usize> {
410 let mut found = None;
411 for (i, &e) in elements.iter().enumerate() {
412 match rule(self.lang, self.nodes.n[e].kind) {
413 Rule::Sym(_, _, Cont::Scope) if found.is_none() => found = Some(i),
414 Rule::Skip | Rule::Import => {}
415 _ => return None,
416 }
417 }
418 found
419 }
420
421 fn scope_inner(&mut self, id: usize, anchors: &mut Vec<(usize, usize, String)>) -> bool {
424 let Rule::Sym(k, label, _) = rule(self.lang, self.nodes.n[id].kind) else {
425 return false;
426 };
427 let base = self.out.symbols.len();
428 let name = self.name(id);
429 self.push(k, label, name, id, 0, &mut None);
430 let body = self.nodes.field(id, "body").unwrap_or(id);
431 let mut inner = Vec::new();
432 self.flatten(body, 1, &mut inner);
433 let mut found = Vec::new();
434 for (j, &e) in inner.iter().enumerate() {
435 let before = self.out.symbols.len();
436 let mut first = None;
437 self.walk(e, false, 1, 1, &mut first);
438 if self.out.symbols.len() > before
439 && let Some(title) = first
440 {
441 found.push((self.anchor_start(&inner, j), self.nodes.n[e].end, title));
442 }
443 }
444 if found.is_empty() {
445 self.out.symbols.truncate(base);
446 return false;
447 }
448 anchors.extend(found);
449 true
450 }
451
452 fn walk(
454 &mut self,
455 id: usize,
456 in_type: bool,
457 budget: u32,
458 depth: u32,
459 first: &mut Option<String>,
460 ) {
461 if depth >= MAX_DEPTH {
462 return;
463 }
464 let kind = self.nodes.n[id].kind;
465 match rule(self.lang, kind) {
466 Rule::Sym(k, label, cont) => {
467 let needs_body = self.lang.is_c_family()
468 && matches!(
469 kind,
470 "struct_specifier" | "class_specifier" | "enum_specifier"
471 );
472 if needs_body && self.nodes.field(id, "body").is_none() {
473 return;
474 }
475 let (k, label) = if k == SymbolKind::Function && in_type {
476 (SymbolKind::Method, "method")
477 } else {
478 (k, label)
479 };
480 let name = self.name(id);
481 self.push(k, label, name, id, depth, first);
482 if !matches!(cont, Cont::No) {
483 for c in self.children(id) {
484 self.walk(c, matches!(cont, Cont::Type), 1, depth + 1, first);
485 }
486 }
487 }
488 Rule::Wrap | Rule::Flat => {
489 for c in self.children(id) {
490 self.walk(c, in_type, budget, depth + 1, first);
491 }
492 }
493 Rule::Import => self.import(id),
494 Rule::Special(sp) => self.special(sp, id, depth, first),
495 Rule::Skip => {
496 if budget > 0 {
497 for c in self.children(id) {
498 self.walk(c, in_type, budget - 1, depth + 1, first);
499 }
500 }
501 }
502 }
503 }
504
505 fn special(&mut self, sp: Sp, id: usize, depth: u32, first: &mut Option<String>) {
506 match sp {
507 Sp::GoImport => self.go_imports(id, 0),
508 Sp::ExCall => self.ex_call(id, depth, first),
509 Sp::RAssign => {
510 let lhs = self.nodes.field(id, "lhs");
512 let rhs = self.nodes.field(id, "rhs");
513 if let (Some(l), Some(r)) = (lhs, rhs)
514 && self.nodes.n[r].kind == "function_definition"
515 && self.nodes.n[l].kind == "identifier"
516 {
517 let name = self.clean(self.text(l));
518 self.push(SymbolKind::Function, "function", name, id, depth, first);
519 }
520 }
521 Sp::GoType => {
522 for c in self.children(id) {
523 if !matches!(self.nodes.n[c].kind, "type_spec" | "type_alias") {
524 continue;
525 }
526 let shape = self.nodes.field(c, "type").map(|t| self.nodes.n[t].kind);
527 let (k, label) = match shape {
528 Some("struct_type") => (SymbolKind::Struct, "struct"),
529 Some("interface_type") => (SymbolKind::Interface, "interface"),
530 _ => (SymbolKind::Type, "type"),
531 };
532 let name = self.name(c);
533 self.push(k, label, name, c, depth, first);
534 }
535 }
536 Sp::JsVar => {
537 for c in self.children(id) {
538 if self.nodes.n[c].kind != "variable_declarator" {
539 continue;
540 }
541 let (k, label) =
542 match self.nodes.field(c, "value").map(|v| self.nodes.n[v].kind) {
543 Some(
544 "arrow_function"
545 | "function_expression"
546 | "function"
547 | "generator_function",
548 ) => (SymbolKind::Function, "function"),
549 Some("class") => (SymbolKind::Class, "class"),
550 _ => continue,
551 };
552 let name = self.name(c);
553 self.push(k, label, name, c, depth, first);
554 }
555 }
556 Sp::CDecl => {
557 let Some(t) = self.nodes.field(id, "type") else {
559 return;
560 };
561 let (k, label) = match self.nodes.n[t].kind {
562 "struct_specifier" => (SymbolKind::Struct, "struct"),
563 "class_specifier" => (SymbolKind::Class, "class"),
564 "enum_specifier" => (SymbolKind::Enum, "enum"),
565 _ => return,
566 };
567 if self.nodes.field(t, "body").is_none() {
568 return;
569 }
570 let mut name = self
571 .nodes
572 .field(t, "name")
573 .map_or(String::new(), |c| self.clean(self.text(c)));
574 if name.is_empty() {
575 name = self
576 .nodes
577 .field(id, "declarator")
578 .map_or(String::new(), |c| self.clean(self.text(c)));
579 }
580 self.push(k, label, name, id, depth, first);
581 }
582 }
583 }
584
585 fn ex_call(&mut self, id: usize, depth: u32, first: &mut Option<String>) {
587 let Some(t) = self.nodes.field(id, "target") else {
588 return;
589 };
590 if self.nodes.n[t].kind != "identifier" {
591 return;
592 }
593 let word = self.text(t).to_string();
594 let kids = self.children(id);
595 let args = kids
596 .iter()
597 .copied()
598 .find(|&c| self.nodes.n[c].kind == "arguments");
599 let first_arg = args.and_then(|a| {
600 self.children(a)
601 .into_iter()
602 .find(|&c| self.nodes.n[c].kind != "comment")
603 });
604 let (kind, label, container) = match word.as_str() {
605 "import" | "alias" | "use" | "require" => return self.import(id),
606 "defmodule" => (SymbolKind::Module, "module", true),
607 "defprotocol" => (SymbolKind::Interface, "protocol", true),
608 "defimpl" => (SymbolKind::Module, "impl", true),
609 "def" | "defp" | "defmacro" | "defmacrop" => {
610 if depth > 0 {
611 (SymbolKind::Method, "method", false)
612 } else {
613 (SymbolKind::Function, "function", false)
614 }
615 }
616 _ => return,
617 };
618 let mut at = first_arg;
620 for _ in 0..8 {
621 match at {
622 Some(a) if self.nodes.n[a].kind == "binary_operator" => {
623 at = self.nodes.field(a, "left")
624 }
625 Some(a) if self.nodes.n[a].kind == "call" => at = self.nodes.field(a, "target"),
626 _ => break,
627 }
628 }
629 let name = at.map(|a| self.clean(self.text(a))).unwrap_or_default();
630 self.push(kind, label, name, id, depth, first);
631 if container {
632 for c in kids
633 .into_iter()
634 .filter(|&c| self.nodes.n[c].kind == "do_block")
635 {
636 for d in self.children(c) {
637 self.walk(d, true, 1, depth + 1, first);
638 }
639 }
640 }
641 }
642
643 fn go_imports(&mut self, id: usize, depth: u32) {
644 for c in self.children(id) {
645 match self.nodes.n[c].kind {
646 "import_spec" => self.import(c),
647 "import_spec_list" if depth < 2 => self.go_imports(c, depth + 1),
648 _ => {}
649 }
650 }
651 }
652}
653
654fn is_identifier(kind: &str) -> bool {
655 matches!(
656 kind,
657 "identifier"
658 | "simple_identifier"
659 | "field_identifier"
660 | "qualified_identifier"
661 | "type_identifier"
662 | "value_name"
663 | "module_name"
664 | "type_constructor"
665 | "class_name"
666 | "module_type_name"
667 | "moduleName"
668 | "function_name"
669 | "simple_name"
670 | "atom"
671 | "unquoted_argument"
672 | "lower_case_identifier"
673 | "method_identifier"
674 | "destructor_name"
675 | "operator_name"
676 )
677}