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 if self.lang == Lang::Verilog {
310 let mut todo = vec![(id, 0u32)];
311 while let Some((at, depth)) = todo.pop() {
312 for &c in self.nodes.n[at].children.iter().rev() {
313 let c = c as usize;
314 if depth < 6
315 && !matches!(
316 self.nodes.n[c].kind,
317 "list_of_port_declarations" | "data_type_or_void"
318 )
319 {
320 todo.push((c, depth + 1));
321 }
322 }
323 if self.nodes.n[at].kind == "simple_identifier" {
324 return self.clean(self.text(at));
325 }
326 }
327 return String::new();
328 }
329 let field = if self.nodes.n[id].kind == "impl_item" {
331 "type"
332 } else {
333 "name"
334 };
335 if let Some(c) = self.nodes.field(id, field) {
336 return self.clean(self.text(c));
337 }
338 for c in self.children(id) {
340 if self.nodes.n[c].kind == "defun_header"
341 && let Some(n) = self.nodes.field(c, "function_name")
342 {
343 return self.clean(self.text(n));
344 }
345 }
346 let mut at = id;
348 for _ in 0..16 {
349 let next = self.nodes.field(at, "declarator").or_else(|| {
350 self.nodes.n[at]
351 .children
352 .iter()
353 .map(|&c| c as usize)
354 .find(|&c| {
355 let k = self.nodes.n[c].kind;
356 k.ends_with("declarator")
357 || is_identifier(k)
358 || matches!(
359 k,
360 "signature"
361 | "type_head"
362 | "call_expression"
363 | "where_expression"
364 | "typed_expression"
365 | "type_name"
366 | "function_clause"
367 | "function_command"
368 | "macro_command"
369 | "argument_list"
370 | "argument"
371 | "parametrized_type_expression"
372 )
373 })
374 });
375 match next {
376 Some(c) if is_identifier(self.nodes.n[c].kind) => return self.clean(self.text(c)),
377 Some(c) => at = c,
378 None => break,
379 }
380 }
381 String::new()
382 }
383
384 fn push(
385 &mut self,
386 kind: SymbolKind,
387 label: &str,
388 name: String,
389 id: usize,
390 depth: u32,
391 first: &mut Option<String>,
392 ) {
393 if self.out.symbols.len() >= MAX_SYMBOLS {
394 return;
395 }
396 if first.is_none() {
397 *first = Some(if name.is_empty() {
398 label.to_string()
399 } else {
400 format!("{label} {name}")
401 });
402 }
403 let (s, e) = (self.nodes.n[id].start, self.nodes.n[id].end);
404 let (start_line, end_line) = (self.line(s), self.line(e.saturating_sub(1).max(s)));
405 self.out.symbols.push(Symbol {
406 kind,
407 name,
408 start_line,
409 end_line,
410 depth,
411 });
412 }
413
414 fn import(&mut self, id: usize) {
415 if self.out.imports.len() < MAX_IMPORTS {
416 let t = self.clean(self.text(id));
417 self.out.imports.push(t);
418 }
419 }
420
421 fn children(&self, id: usize) -> Vec<usize> {
422 self.nodes.n[id]
423 .children
424 .iter()
425 .map(|&c| c as usize)
426 .collect()
427 }
428
429 fn single_scope(&self, elements: &[usize]) -> Option<usize> {
431 let mut found = None;
432 for (i, &e) in elements.iter().enumerate() {
433 match rule(self.lang, self.nodes.n[e].kind) {
434 Rule::Sym(_, _, Cont::Scope) if found.is_none() => found = Some(i),
435 Rule::Skip | Rule::Import => {}
436 _ => return None,
437 }
438 }
439 found
440 }
441
442 fn scope_inner(&mut self, id: usize, anchors: &mut Vec<(usize, usize, String)>) -> bool {
445 let Rule::Sym(k, label, _) = rule(self.lang, self.nodes.n[id].kind) else {
446 return false;
447 };
448 let base = self.out.symbols.len();
449 let name = self.name(id);
450 self.push(k, label, name, id, 0, &mut None);
451 let body = self.nodes.field(id, "body").unwrap_or(id);
452 let mut inner = Vec::new();
453 self.flatten(body, 1, &mut inner);
454 let mut found = Vec::new();
455 for (j, &e) in inner.iter().enumerate() {
456 let before = self.out.symbols.len();
457 let mut first = None;
458 self.walk(e, false, 1, 1, &mut first);
459 if self.out.symbols.len() > before
460 && let Some(title) = first
461 {
462 found.push((self.anchor_start(&inner, j), self.nodes.n[e].end, title));
463 }
464 }
465 if found.is_empty() {
466 self.out.symbols.truncate(base);
467 return false;
468 }
469 anchors.extend(found);
470 true
471 }
472
473 fn walk(
475 &mut self,
476 id: usize,
477 in_type: bool,
478 budget: u32,
479 depth: u32,
480 first: &mut Option<String>,
481 ) {
482 if depth >= MAX_DEPTH {
483 return;
484 }
485 let kind = self.nodes.n[id].kind;
486 match rule(self.lang, kind) {
487 Rule::Sym(k, label, cont) => {
488 let needs_body = self.lang.is_c_family()
489 && matches!(
490 kind,
491 "struct_specifier" | "class_specifier" | "enum_specifier"
492 );
493 if needs_body && self.nodes.field(id, "body").is_none() {
494 return;
495 }
496 let (k, label) = if k == SymbolKind::Function && in_type {
497 (SymbolKind::Method, "method")
498 } else {
499 (k, label)
500 };
501 let name = self.name(id);
502 self.push(k, label, name, id, depth, first);
503 if !matches!(cont, Cont::No) {
504 for c in self.children(id) {
505 self.walk(c, matches!(cont, Cont::Type), 1, depth + 1, first);
506 }
507 }
508 }
509 Rule::Wrap | Rule::Flat => {
510 for c in self.children(id) {
511 self.walk(c, in_type, budget, depth + 1, first);
512 }
513 }
514 Rule::Import => self.import(id),
515 Rule::Special(sp) => self.special(sp, id, depth, first),
516 Rule::Skip => {
517 if budget > 0 {
518 for c in self.children(id) {
519 self.walk(c, in_type, budget - 1, depth + 1, first);
520 }
521 }
522 }
523 }
524 }
525
526 fn special(&mut self, sp: Sp, id: usize, depth: u32, first: &mut Option<String>) {
527 match sp {
528 Sp::GoImport => self.go_imports(id, 0),
529 Sp::ExCall => self.ex_call(id, depth, first),
530 Sp::RAssign => {
531 let lhs = self.nodes.field(id, "lhs");
533 let rhs = self.nodes.field(id, "rhs");
534 if let (Some(l), Some(r)) = (lhs, rhs)
535 && self.nodes.n[r].kind == "function_definition"
536 && self.nodes.n[l].kind == "identifier"
537 {
538 let name = self.clean(self.text(l));
539 self.push(SymbolKind::Function, "function", name, id, depth, first);
540 }
541 }
542 Sp::GoType => {
543 for c in self.children(id) {
544 if !matches!(self.nodes.n[c].kind, "type_spec" | "type_alias") {
545 continue;
546 }
547 let shape = self.nodes.field(c, "type").map(|t| self.nodes.n[t].kind);
548 let (k, label) = match shape {
549 Some("struct_type") => (SymbolKind::Struct, "struct"),
550 Some("interface_type") => (SymbolKind::Interface, "interface"),
551 _ => (SymbolKind::Type, "type"),
552 };
553 let name = self.name(c);
554 self.push(k, label, name, c, depth, first);
555 }
556 }
557 Sp::JsVar => {
558 for c in self.children(id) {
559 if self.nodes.n[c].kind != "variable_declarator" {
560 continue;
561 }
562 let (k, label) =
563 match self.nodes.field(c, "value").map(|v| self.nodes.n[v].kind) {
564 Some(
565 "arrow_function"
566 | "function_expression"
567 | "function"
568 | "generator_function",
569 ) => (SymbolKind::Function, "function"),
570 Some("class") => (SymbolKind::Class, "class"),
571 _ => continue,
572 };
573 let name = self.name(c);
574 self.push(k, label, name, c, depth, first);
575 }
576 }
577 Sp::CDecl => {
578 let Some(t) = self.nodes.field(id, "type") else {
580 return;
581 };
582 let (k, label) = match self.nodes.n[t].kind {
583 "struct_specifier" => (SymbolKind::Struct, "struct"),
584 "class_specifier" => (SymbolKind::Class, "class"),
585 "enum_specifier" => (SymbolKind::Enum, "enum"),
586 _ => return,
587 };
588 if self.nodes.field(t, "body").is_none() {
589 return;
590 }
591 let mut name = self
592 .nodes
593 .field(t, "name")
594 .map_or(String::new(), |c| self.clean(self.text(c)));
595 if name.is_empty() {
596 name = self
597 .nodes
598 .field(id, "declarator")
599 .map_or(String::new(), |c| self.clean(self.text(c)));
600 }
601 self.push(k, label, name, id, depth, first);
602 }
603 }
604 }
605
606 fn ex_call(&mut self, id: usize, depth: u32, first: &mut Option<String>) {
608 let Some(t) = self.nodes.field(id, "target") else {
609 return;
610 };
611 if self.nodes.n[t].kind != "identifier" {
612 return;
613 }
614 let word = self.text(t).to_string();
615 let kids = self.children(id);
616 let args = kids
617 .iter()
618 .copied()
619 .find(|&c| self.nodes.n[c].kind == "arguments");
620 let first_arg = args.and_then(|a| {
621 self.children(a)
622 .into_iter()
623 .find(|&c| self.nodes.n[c].kind != "comment")
624 });
625 let (kind, label, container) = match word.as_str() {
626 "import" | "alias" | "use" | "require" => return self.import(id),
627 "defmodule" => (SymbolKind::Module, "module", true),
628 "defprotocol" => (SymbolKind::Interface, "protocol", true),
629 "defimpl" => (SymbolKind::Module, "impl", true),
630 "def" | "defp" | "defmacro" | "defmacrop" => {
631 if depth > 0 {
632 (SymbolKind::Method, "method", false)
633 } else {
634 (SymbolKind::Function, "function", false)
635 }
636 }
637 _ => return,
638 };
639 let mut at = first_arg;
641 for _ in 0..8 {
642 match at {
643 Some(a) if self.nodes.n[a].kind == "binary_operator" => {
644 at = self.nodes.field(a, "left")
645 }
646 Some(a) if self.nodes.n[a].kind == "call" => at = self.nodes.field(a, "target"),
647 _ => break,
648 }
649 }
650 let name = at.map(|a| self.clean(self.text(a))).unwrap_or_default();
651 self.push(kind, label, name, id, depth, first);
652 if container {
653 for c in kids
654 .into_iter()
655 .filter(|&c| self.nodes.n[c].kind == "do_block")
656 {
657 for d in self.children(c) {
658 self.walk(d, true, 1, depth + 1, first);
659 }
660 }
661 }
662 }
663
664 fn go_imports(&mut self, id: usize, depth: u32) {
665 for c in self.children(id) {
666 match self.nodes.n[c].kind {
667 "import_spec" => self.import(c),
668 "import_spec_list" if depth < 2 => self.go_imports(c, depth + 1),
669 _ => {}
670 }
671 }
672 }
673}
674
675fn is_identifier(kind: &str) -> bool {
676 matches!(
677 kind,
678 "identifier"
679 | "simple_identifier"
680 | "field_identifier"
681 | "qualified_identifier"
682 | "type_identifier"
683 | "value_name"
684 | "module_name"
685 | "type_constructor"
686 | "class_name"
687 | "module_type_name"
688 | "moduleName"
689 | "function_name"
690 | "simple_name"
691 | "atom"
692 | "unquoted_argument"
693 | "lower_case_identifier"
694 | "method_identifier"
695 | "destructor_name"
696 | "operator_name"
697 )
698}