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 for (i, &e) in elements.iter().enumerate() {
96 let before = w.out.symbols.len();
97 let mut first = None;
98 w.walk(e, false, 0, 0, &mut first);
99 if w.out.symbols.len() > before
100 && let Some(title) = first
101 {
102 anchors.push((w.anchor_start(&elements, i), nodes.n[e].end, title));
103 }
104 }
105 if w.out.symbols.is_empty() {
106 return None;
107 }
108 let mut out = w.out;
109 out.sections = sections(source, anchors);
110 Some(out)
111}
112
113fn sections(source: &str, anchors: Vec<(usize, usize, String)>) -> Vec<Section> {
115 let mut out: Vec<Section> = Vec::with_capacity(anchors.len() + 1);
116 let mut at = 0usize;
117 for (i, (start, end, title)) in anchors.into_iter().enumerate() {
118 if i == 0 && !source.get(..start).unwrap_or("").trim().is_empty() {
119 out.push(Section {
120 start: 0,
121 end: start,
122 title: None,
123 });
124 at = start;
125 }
126 if end <= at {
128 continue;
129 }
130 let stop = line_end(source, end);
131 out.push(Section {
132 start: at,
133 end: stop,
134 title: Some(title),
135 });
136 at = stop;
137 }
138 match out.last_mut() {
139 Some(last) => last.end = source.len(),
140 None => out.push(Section {
141 start: 0,
142 end: source.len(),
143 title: None,
144 }),
145 }
146 out
147}
148
149fn line_end(source: &str, at: usize) -> usize {
150 match source
151 .as_bytes()
152 .get(at..)
153 .and_then(|b| b.iter().position(|&c| c == b'\n'))
154 {
155 Some(p) => at + p + 1,
156 None => source.len(),
157 }
158}
159
160fn line_starts(source: &str) -> Vec<usize> {
161 let mut v = vec![0];
162 v.extend(
163 source
164 .bytes()
165 .enumerate()
166 .filter(|(_, b)| *b == b'\n')
167 .map(|(i, _)| i + 1),
168 );
169 v
170}
171
172struct Node {
173 kind: &'static str,
174 field: Option<&'static str>,
175 start: usize,
176 end: usize,
177 children: Vec<u32>,
178}
179
180struct Nodes {
182 n: Vec<Node>,
183 error_bytes: usize,
184}
185
186impl Nodes {
187 fn build(tree: &crate::api::ParseTree, table: &'static Language) -> Option<Nodes> {
188 let mut n = vec![Node {
189 kind: "",
190 field: None,
191 start: 0,
192 end: 0,
193 children: Vec::new(),
194 }];
195 let mut stack = vec![(0u32, false)];
196 let mut error_bytes = 0usize;
197 tree.visit(table, |ev| match ev {
198 Ev::Open(v) => {
199 let id = n.len() as u32;
200 let (parent, in_error) = *stack.last().unwrap_or(&(0, false));
201 if v.error && !in_error {
202 error_bytes += v.end.saturating_sub(v.start);
203 }
204 n.push(Node {
205 kind: v.kind,
206 field: v.field,
207 start: v.start,
208 end: v.end,
209 children: Vec::new(),
210 });
211 n[parent as usize].children.push(id);
212 stack.push((id, in_error || v.error));
213 }
214 Ev::Close => {
215 stack.pop();
216 }
217 });
218 Some(Nodes { n, error_bytes })
219 }
220
221 fn top(&self) -> usize {
223 match self.n[0].children.as_slice() {
224 [only] => *only as usize,
225 _ => 0,
226 }
227 }
228
229 fn field(&self, id: usize, name: &str) -> Option<usize> {
230 self.n[id]
231 .children
232 .iter()
233 .map(|&c| c as usize)
234 .find(|&c| self.n[c].field == Some(name))
235 }
236}
237
238struct Walker<'a> {
239 lang: Lang,
240 source: &'a str,
241 nodes: &'a Nodes,
242 lines: Vec<usize>,
243 out: Outline,
244}
245
246impl Walker<'_> {
247 fn text(&self, id: usize) -> &str {
248 let n = &self.nodes.n[id];
249 self.source.get(n.start..n.end).unwrap_or("")
250 }
251
252 fn clean(&self, s: &str) -> String {
254 let mut out = String::with_capacity(s.len().min(MAX_TEXT));
255 for word in s.split_whitespace() {
256 if !out.is_empty() {
257 out.push(' ');
258 }
259 for c in word.chars() {
260 if out.len() + c.len_utf8() > MAX_TEXT {
261 return out;
262 }
263 out.push(c);
264 }
265 }
266 out
267 }
268
269 fn line(&self, at: usize) -> u32 {
270 self.lines.partition_point(|&s| s <= at) as u32
271 }
272
273 fn flatten(&self, id: usize, depth: u32, out: &mut Vec<usize>) {
275 for &c in &self.nodes.n[id].children {
276 let c = c as usize;
277 if matches!(rule(self.lang, self.nodes.n[c].kind), Rule::Flat) && depth < MAX_DEPTH {
278 self.flatten(c, depth + 1, out);
279 } else {
280 out.push(c);
281 }
282 }
283 }
284
285 fn anchor_start(&self, elements: &[usize], i: usize) -> usize {
287 let mut line = self.line(self.nodes.n[elements[i]].start);
288 for &e in elements[..i].iter().rev() {
289 let n = &self.nodes.n[e];
290 if !is_leading(n.kind) {
291 break;
292 }
293 let end_line = self.line(n.end.saturating_sub(1).max(n.start));
295 if end_line + 1 != line {
296 break;
297 }
298 line = self.line(n.start);
299 }
300 self.lines[line.saturating_sub(1) as usize]
301 }
302
303 fn name(&self, id: usize) -> String {
304 let field = if self.nodes.n[id].kind == "impl_item" {
306 "type"
307 } else {
308 "name"
309 };
310 if let Some(c) = self.nodes.field(id, field) {
311 return self.clean(self.text(c));
312 }
313 let mut at = id;
315 for _ in 0..16 {
316 let next = self.nodes.field(at, "declarator").or_else(|| {
317 self.nodes.n[at]
318 .children
319 .iter()
320 .map(|&c| c as usize)
321 .find(|&c| {
322 let k = self.nodes.n[c].kind;
323 k.ends_with("declarator") || is_identifier(k)
324 })
325 });
326 match next {
327 Some(c) if is_identifier(self.nodes.n[c].kind) => return self.clean(self.text(c)),
328 Some(c) => at = c,
329 None => break,
330 }
331 }
332 String::new()
333 }
334
335 fn push(
336 &mut self,
337 kind: SymbolKind,
338 label: &str,
339 name: String,
340 id: usize,
341 depth: u32,
342 first: &mut Option<String>,
343 ) {
344 if self.out.symbols.len() >= MAX_SYMBOLS {
345 return;
346 }
347 if first.is_none() {
348 *first = Some(if name.is_empty() {
349 label.to_string()
350 } else {
351 format!("{label} {name}")
352 });
353 }
354 let (s, e) = (self.nodes.n[id].start, self.nodes.n[id].end);
355 let (start_line, end_line) = (self.line(s), self.line(e.saturating_sub(1).max(s)));
356 self.out.symbols.push(Symbol {
357 kind,
358 name,
359 start_line,
360 end_line,
361 depth,
362 });
363 }
364
365 fn import(&mut self, id: usize) {
366 if self.out.imports.len() < MAX_IMPORTS {
367 let t = self.clean(self.text(id));
368 self.out.imports.push(t);
369 }
370 }
371
372 fn children(&self, id: usize) -> Vec<usize> {
373 self.nodes.n[id]
374 .children
375 .iter()
376 .map(|&c| c as usize)
377 .collect()
378 }
379
380 fn walk(
382 &mut self,
383 id: usize,
384 in_type: bool,
385 budget: u32,
386 depth: u32,
387 first: &mut Option<String>,
388 ) {
389 if depth >= MAX_DEPTH {
390 return;
391 }
392 let kind = self.nodes.n[id].kind;
393 match rule(self.lang, kind) {
394 Rule::Sym(k, label, cont) => {
395 let needs_body = self.lang.is_c_family()
396 && matches!(
397 kind,
398 "struct_specifier" | "class_specifier" | "enum_specifier"
399 );
400 if needs_body && self.nodes.field(id, "body").is_none() {
401 return;
402 }
403 let (k, label) = if k == SymbolKind::Function && in_type {
404 (SymbolKind::Method, "method")
405 } else {
406 (k, label)
407 };
408 let name = self.name(id);
409 self.push(k, label, name, id, depth, first);
410 if !matches!(cont, Cont::No) {
411 for c in self.children(id) {
412 self.walk(c, matches!(cont, Cont::Type), 1, depth + 1, first);
413 }
414 }
415 }
416 Rule::Wrap | Rule::Flat => {
417 for c in self.children(id) {
418 self.walk(c, in_type, budget, depth + 1, first);
419 }
420 }
421 Rule::Import => self.import(id),
422 Rule::Special(sp) => self.special(sp, id, depth, first),
423 Rule::Skip => {
424 if budget > 0 {
425 for c in self.children(id) {
426 self.walk(c, in_type, budget - 1, depth + 1, first);
427 }
428 }
429 }
430 }
431 }
432
433 fn special(&mut self, sp: Sp, id: usize, depth: u32, first: &mut Option<String>) {
434 match sp {
435 Sp::GoImport => self.go_imports(id, 0),
436 Sp::GoType => {
437 for c in self.children(id) {
438 if !matches!(self.nodes.n[c].kind, "type_spec" | "type_alias") {
439 continue;
440 }
441 let shape = self.nodes.field(c, "type").map(|t| self.nodes.n[t].kind);
442 let (k, label) = match shape {
443 Some("struct_type") => (SymbolKind::Struct, "struct"),
444 Some("interface_type") => (SymbolKind::Interface, "interface"),
445 _ => (SymbolKind::Type, "type"),
446 };
447 let name = self.name(c);
448 self.push(k, label, name, c, depth, first);
449 }
450 }
451 Sp::JsVar => {
452 for c in self.children(id) {
453 if self.nodes.n[c].kind != "variable_declarator" {
454 continue;
455 }
456 let (k, label) =
457 match self.nodes.field(c, "value").map(|v| self.nodes.n[v].kind) {
458 Some(
459 "arrow_function"
460 | "function_expression"
461 | "function"
462 | "generator_function",
463 ) => (SymbolKind::Function, "function"),
464 Some("class") => (SymbolKind::Class, "class"),
465 _ => continue,
466 };
467 let name = self.name(c);
468 self.push(k, label, name, c, depth, first);
469 }
470 }
471 Sp::CDecl => {
472 let Some(t) = self.nodes.field(id, "type") else {
474 return;
475 };
476 let (k, label) = match self.nodes.n[t].kind {
477 "struct_specifier" => (SymbolKind::Struct, "struct"),
478 "class_specifier" => (SymbolKind::Class, "class"),
479 "enum_specifier" => (SymbolKind::Enum, "enum"),
480 _ => return,
481 };
482 if self.nodes.field(t, "body").is_none() {
483 return;
484 }
485 let mut name = self
486 .nodes
487 .field(t, "name")
488 .map_or(String::new(), |c| self.clean(self.text(c)));
489 if name.is_empty() {
490 name = self
491 .nodes
492 .field(id, "declarator")
493 .map_or(String::new(), |c| self.clean(self.text(c)));
494 }
495 self.push(k, label, name, id, depth, first);
496 }
497 }
498 }
499
500 fn go_imports(&mut self, id: usize, depth: u32) {
501 for c in self.children(id) {
502 match self.nodes.n[c].kind {
503 "import_spec" => self.import(c),
504 "import_spec_list" if depth < 2 => self.go_imports(c, depth + 1),
505 _ => {}
506 }
507 }
508 }
509}
510
511fn is_identifier(kind: &str) -> bool {
512 matches!(
513 kind,
514 "identifier"
515 | "field_identifier"
516 | "qualified_identifier"
517 | "type_identifier"
518 | "destructor_name"
519 | "operator_name"
520 )
521}