use crate::Limits;
use crate::api::{ParseTree, parse};
use crate::hw;
use crate::langs::{Cont, Lang, Rule, Sp, is_leading, rule};
use crate::table::Language;
use crate::tree::Arena;
const MAX_INPUT: usize = 2 << 20;
const MAX_ERROR_PERCENT: usize = 20;
const MAX_SYMBOLS: usize = 2000;
const MAX_IMPORTS: usize = 500;
const MAX_TEXT: usize = 200;
const MAX_DEPTH: u32 = 64;
const MAX_MILLIS: u64 = 3000;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SymbolKind {
Function,
Method,
Class,
Struct,
Enum,
Interface,
Trait,
Type,
Module,
}
#[derive(Clone, Debug)]
pub struct Symbol {
pub kind: SymbolKind,
pub name: String,
pub start_line: u32,
pub end_line: u32,
pub depth: u32,
}
#[derive(Clone, Debug)]
pub struct Section {
pub start: usize,
pub end: usize,
pub title: Option<String>,
}
#[derive(Clone, Debug, Default)]
pub struct Outline {
pub symbols: Vec<Symbol>,
pub imports: Vec<String>,
pub sections: Vec<Section>,
}
pub fn outline(tag: &str, source: &str) -> Option<Outline> {
let lang = Lang::from_tag(tag)?;
if source.is_empty() || source.len() > MAX_INPUT || !lang.has_outline_rules() {
return None;
}
std::panic::catch_unwind(|| run(lang, source))
.ok()
.flatten()
}
#[derive(Clone, Copy)]
struct VItem {
id: u32,
offset: u32,
kind: &'static str,
field: Option<&'static str>,
start: usize,
end: usize,
}
fn sum_error_bytes(tree: &ParseTree, table: &'static Language) -> usize {
let arena = &tree.arena;
if !tree.has_error() && !arena.n(tree.root).is_error() {
return 0;
}
let mut error_bytes = 0usize;
let mut stack = vec![(tree.root, 0u16, false)];
while let Some((id, alias, alias_named)) = stack.pop() {
let node = arena.n(id);
let visible = node.missing()
|| if alias != 0 {
alias_named
} else {
node.visible() && node.named()
};
if visible && node.is_error() {
error_bytes += node.size.bytes as usize;
continue;
}
if arena.cost(id) == 0 || node.child_count() == 0 {
continue;
}
let kids = arena.children(id);
let alias_seq = table.alias_sequence(node.prod);
let mut structural = 0usize;
for &child in kids {
let cn = arena.n(child);
let mut calias = 0u16;
let mut calias_named = false;
if !cn.extra() {
if let Some(seq) = alias_seq {
calias = seq.get(structural).copied().unwrap_or(0);
calias_named = calias != 0 && table.named(calias);
}
structural += 1;
}
if cn.is_error() || arena.cost(child) > 0 {
stack.push((child, calias, calias_named));
}
}
}
error_bytes
}
fn collect_visible_children(
arena: &Arena,
table: &'static Language,
parent_id: u32,
parent_offset: u32,
parent_visible: bool,
parent_field: Option<u16>,
out: &mut Vec<VItem>,
) {
struct ExpFrame {
id: u32,
visible: bool,
field: Option<u16>,
child_index: usize,
structural: usize,
next_offset: u32,
}
let mut stack = vec![ExpFrame {
id: parent_id,
visible: parent_visible,
field: parent_field,
child_index: 0,
structural: 0,
next_offset: parent_offset,
}];
while let Some(top) = stack.len().checked_sub(1) {
let pid = stack[top].id;
let node = arena.n(pid);
let ci = stack[top].child_index;
if ci >= node.child_count() as usize {
stack.pop();
continue;
}
let child = arena.children(pid)[ci];
let cn = arena.n(child);
let cur_offset = stack[top].next_offset;
let p_vis = stack[top].visible;
let p_field = stack[top].field;
let mut alias = 0u16;
let mut alias_named = false;
let mut field = None;
if !cn.extra() {
let st_idx = stack[top].structural;
if let Some(seq) = table.alias_sequence(node.prod) {
alias = seq.get(st_idx).copied().unwrap_or(0);
alias_named = alias != 0 && table.named(alias);
}
field = if p_vis { None } else { p_field };
if let Some(&(s, l)) = table.field_map_slices.get(node.prod as usize) {
let start_i = s as usize;
for &(fid, cidx, inh) in &table.field_map_entries[start_i..start_i + l as usize] {
if !inh && cidx as usize == st_idx {
field = Some(fid);
break;
}
}
}
stack[top].structural = st_idx + 1;
}
stack[top].next_offset = cur_offset + cn.total().bytes;
stack[top].child_index = ci + 1;
let vis = cn.missing()
|| if alias != 0 {
alias_named
} else {
cn.visible() && cn.named()
};
if vis {
let sym = if alias != 0 { alias } else { cn.sym };
let start = (cur_offset + cn.padding.bytes) as usize;
let end = start + cn.size.bytes as usize;
out.push(VItem {
id: child,
offset: cur_offset,
kind: table.symbol_name(sym),
field: field.map(|f| table.field_name(f)),
start,
end,
});
} else if cn.child_count() > 0 {
stack.push(ExpFrame {
id: child,
visible: false,
field,
child_index: 0,
structural: 0,
next_offset: cur_offset,
});
}
}
}
fn run(lang: Lang, source: &str) -> Option<Outline> {
let table = lang.table()?;
let limits = Limits {
max_millis: MAX_MILLIS,
..Limits::default()
};
let tree = parse(table, source.as_bytes(), limits);
if tree.truncated {
return None;
}
let error_bytes = sum_error_bytes(&tree, table);
if error_bytes * 100 > source.len() * MAX_ERROR_PERCENT {
return None;
}
let mut w = Walker {
lang,
source,
arena: &tree.arena,
table,
lines: Vec::new(),
out: Outline::default(),
};
let root_node = tree.arena.n(tree.root);
let root_vis = root_node.missing() || (root_node.visible() && root_node.named());
let mut top_items = Vec::new();
if root_vis {
collect_visible_children(&tree.arena, table, tree.root, 0, true, None, &mut top_items);
} else {
collect_visible_children(
&tree.arena,
table,
tree.root,
0,
false,
None,
&mut top_items,
);
if top_items.len() == 1 {
let only = top_items[0];
top_items.clear();
collect_visible_children(
&tree.arena,
table,
only.id,
only.offset,
true,
None,
&mut top_items,
);
}
}
let mut elements = Vec::with_capacity(top_items.len());
for item in top_items {
w.flatten_item(item, 0, &mut elements);
}
let mut anchors = Vec::new();
let single_scope = w.single_scope(&elements);
for (i, &e) in elements.iter().enumerate() {
let before = w.out.symbols.len();
let mut first = None;
if single_scope == Some(i) && w.scope_inner(e, &mut anchors) {
continue;
}
w.walk(e, false, 0, 0, &mut first);
if w.out.symbols.len() > before
&& let Some(title) = first
{
anchors.push((w.anchor_start(&elements, i), e.end, title));
}
}
if w.out.symbols.is_empty() {
return None;
}
let mut out = w.out;
out.sections = sections(source, anchors);
Some(out)
}
fn sections(source: &str, anchors: Vec<(usize, usize, String)>) -> Vec<Section> {
let mut out: Vec<Section> = Vec::with_capacity(anchors.len() + 1);
let mut at = 0usize;
for (i, (start, end, title)) in anchors.into_iter().enumerate() {
if i == 0 && !source.get(..start).unwrap_or("").trim().is_empty() {
out.push(Section {
start: 0,
end: start,
title: None,
});
at = start;
}
if end <= at {
continue;
}
let stop = line_end(source, end);
out.push(Section {
start: at,
end: stop,
title: Some(title),
});
at = stop;
}
match out.last_mut() {
Some(last) => last.end = source.len(),
None => out.push(Section {
start: 0,
end: source.len(),
title: None,
}),
}
out
}
#[inline]
fn line_end(source: &str, at: usize) -> usize {
match source
.as_bytes()
.get(at..)
.and_then(|b| hw::find_byte(b, b'\n'))
{
Some(p) => at + p + 1,
None => source.len(),
}
}
struct Walker<'a> {
lang: Lang,
source: &'a str,
arena: &'a Arena,
table: &'static Language,
lines: Vec<usize>,
out: Outline,
}
impl Walker<'_> {
#[inline]
fn ensure_lines(&mut self) {
if self.lines.is_empty() {
hw::find_line_starts(self.source.as_bytes(), &mut self.lines);
}
}
#[inline]
fn children_of(&self, item: VItem) -> Vec<VItem> {
let mut out = Vec::new();
collect_visible_children(
self.arena,
self.table,
item.id,
item.offset,
true,
None,
&mut out,
);
out
}
#[inline]
fn field_in(children: &[VItem], name: &str) -> Option<VItem> {
children.iter().copied().find(|c| c.field == Some(name))
}
#[inline]
fn field_of(&self, item: VItem, name: &str) -> Option<VItem> {
let kids = self.children_of(item);
Self::field_in(&kids, name)
}
#[inline]
fn text(&self, item: VItem) -> &str {
self.source.get(item.start..item.end).unwrap_or("")
}
fn clean(&self, s: &str) -> String {
let mut out = String::with_capacity(s.len().min(MAX_TEXT));
for word in s.split_whitespace() {
if !out.is_empty() {
out.push(' ');
}
for c in word.chars() {
if out.len() + c.len_utf8() > MAX_TEXT {
return out;
}
out.push(c);
}
}
out
}
#[inline]
fn line(&mut self, at: usize) -> u32 {
self.ensure_lines();
self.lines.partition_point(|&s| s <= at) as u32
}
fn flatten_item(&self, item: VItem, depth: u32, out: &mut Vec<VItem>) {
if matches!(rule(self.lang, item.kind), Rule::Flat) && depth < MAX_DEPTH {
for c in self.children_of(item) {
self.flatten_item(c, depth + 1, out);
}
} else {
out.push(item);
}
}
fn flatten_children(&self, parent: VItem, depth: u32, out: &mut Vec<VItem>) {
for c in self.children_of(parent) {
self.flatten_item(c, depth, out);
}
}
fn anchor_start(&mut self, elements: &[VItem], i: usize) -> usize {
let mut line = self.line(elements[i].start);
for &n in elements[..i].iter().rev() {
if !is_leading(n.kind) {
break;
}
let end_line = self.line(n.end.saturating_sub(1).max(n.start));
if end_line + 1 != line {
break;
}
line = self.line(n.start);
}
self.lines[line.saturating_sub(1) as usize]
}
fn name(&self, item: VItem, kids: &[VItem]) -> String {
if self.lang == Lang::Verilog {
let mut todo = vec![(item, 0u32)];
while let Some((at, depth)) = todo.pop() {
let cs = if at.id == item.id && at.offset == item.offset {
kids.to_vec()
} else {
self.children_of(at)
};
for &c in cs.iter().rev() {
if depth < 6
&& !matches!(c.kind, "list_of_port_declarations" | "data_type_or_void")
{
todo.push((c, depth + 1));
}
}
if at.kind == "simple_identifier" {
return self.clean(self.text(at));
}
}
return String::new();
}
let field = if item.kind == "impl_item" {
"type"
} else {
"name"
};
if let Some(c) = Self::field_in(kids, field) {
return self.clean(self.text(c));
}
for &c in kids {
if c.kind == "defun_header"
&& let Some(n) = self.field_of(c, "function_name")
{
return self.clean(self.text(n));
}
}
let mut at_kids: Vec<VItem>;
let mut cur_kids = kids;
for step in 0..16 {
let next = Self::field_in(cur_kids, "declarator").or_else(|| {
cur_kids.iter().copied().find(|c| {
let k = c.kind;
k.ends_with("declarator")
|| is_identifier(k)
|| matches!(
k,
"signature"
| "type_head"
| "call_expression"
| "where_expression"
| "typed_expression"
| "type_name"
| "function_clause"
| "function_command"
| "macro_command"
| "argument_list"
| "argument"
| "parametrized_type_expression"
)
})
});
match next {
Some(c) if is_identifier(c.kind) => return self.clean(self.text(c)),
Some(c) if step + 1 < 16 => {
at_kids = self.children_of(c);
cur_kids = &at_kids;
}
_ => break,
}
}
String::new()
}
fn push(
&mut self,
kind: SymbolKind,
label: &str,
name: String,
item: VItem,
depth: u32,
first: &mut Option<String>,
) {
if self.out.symbols.len() >= MAX_SYMBOLS {
return;
}
if first.is_none() {
*first = Some(if name.is_empty() {
label.to_string()
} else {
format!("{label} {name}")
});
}
let (s, e) = (item.start, item.end);
let (start_line, end_line) = (self.line(s), self.line(e.saturating_sub(1).max(s)));
self.out.symbols.push(Symbol {
kind,
name,
start_line,
end_line,
depth,
});
}
fn import(&mut self, item: VItem) {
if self.out.imports.len() < MAX_IMPORTS {
let t = self.clean(self.text(item));
self.out.imports.push(t);
}
}
fn single_scope(&self, elements: &[VItem]) -> Option<usize> {
let mut found = None;
for (i, &e) in elements.iter().enumerate() {
match rule(self.lang, e.kind) {
Rule::Sym(_, _, Cont::Scope) if found.is_none() => found = Some(i),
Rule::Skip | Rule::Import => {}
_ => return None,
}
}
found
}
fn scope_inner(&mut self, item: VItem, anchors: &mut Vec<(usize, usize, String)>) -> bool {
let Rule::Sym(k, label, _) = rule(self.lang, item.kind) else {
return false;
};
let kids = self.children_of(item);
let base = self.out.symbols.len();
let name = self.name(item, &kids);
self.push(k, label, name, item, 0, &mut None);
let body = Self::field_in(&kids, "body").unwrap_or(item);
let mut inner = Vec::new();
self.flatten_children(body, 1, &mut inner);
let mut found = Vec::new();
for (j, &e) in inner.iter().enumerate() {
let before = self.out.symbols.len();
let mut first = None;
self.walk(e, false, 1, 1, &mut first);
if self.out.symbols.len() > before
&& let Some(title) = first
{
found.push((self.anchor_start(&inner, j), e.end, title));
}
}
if found.is_empty() {
self.out.symbols.truncate(base);
return false;
}
anchors.extend(found);
true
}
fn walk(
&mut self,
item: VItem,
in_type: bool,
budget: u32,
depth: u32,
first: &mut Option<String>,
) {
if depth >= MAX_DEPTH {
return;
}
let kind = item.kind;
match rule(self.lang, kind) {
Rule::Sym(k, label, cont) => {
let kids = self.children_of(item);
let needs_body = self.lang.is_c_family()
&& matches!(
kind,
"struct_specifier" | "class_specifier" | "enum_specifier"
);
if needs_body && Self::field_in(&kids, "body").is_none() {
return;
}
let (k, label) = if k == SymbolKind::Function && in_type {
(SymbolKind::Method, "method")
} else {
(k, label)
};
let name = self.name(item, &kids);
self.push(k, label, name, item, depth, first);
if !matches!(cont, Cont::No) {
for c in kids {
self.walk(c, matches!(cont, Cont::Type), 1, depth + 1, first);
}
}
}
Rule::Wrap | Rule::Flat => {
for c in self.children_of(item) {
self.walk(c, in_type, budget, depth + 1, first);
}
}
Rule::Import => self.import(item),
Rule::Special(sp) => self.special(sp, item, depth, first),
Rule::Skip => {
if budget > 0 {
for c in self.children_of(item) {
self.walk(c, in_type, budget - 1, depth + 1, first);
}
}
}
}
}
fn special(&mut self, sp: Sp, item: VItem, depth: u32, first: &mut Option<String>) {
match sp {
Sp::GoImport => self.go_imports(item, 0),
Sp::ExCall => self.ex_call(item, depth, first),
Sp::RAssign => {
let kids = self.children_of(item);
let lhs = Self::field_in(&kids, "lhs");
let rhs = Self::field_in(&kids, "rhs");
if let (Some(l), Some(r)) = (lhs, rhs)
&& r.kind == "function_definition"
&& l.kind == "identifier"
{
let name = self.clean(self.text(l));
self.push(SymbolKind::Function, "function", name, item, depth, first);
}
}
Sp::GoType => {
for c in self.children_of(item) {
if !matches!(c.kind, "type_spec" | "type_alias") {
continue;
}
let ckids = self.children_of(c);
let shape = Self::field_in(&ckids, "type").map(|t| t.kind);
let (k, label) = match shape {
Some("struct_type") => (SymbolKind::Struct, "struct"),
Some("interface_type") => (SymbolKind::Interface, "interface"),
_ => (SymbolKind::Type, "type"),
};
let name = self.name(c, &ckids);
self.push(k, label, name, c, depth, first);
}
}
Sp::JsVar => {
for c in self.children_of(item) {
if c.kind != "variable_declarator" {
continue;
}
let ckids = self.children_of(c);
let (k, label) = match Self::field_in(&ckids, "value").map(|v| v.kind) {
Some(
"arrow_function"
| "function_expression"
| "function"
| "generator_function",
) => (SymbolKind::Function, "function"),
Some("class") => (SymbolKind::Class, "class"),
_ => continue,
};
let name = self.name(c, &ckids);
self.push(k, label, name, c, depth, first);
}
}
Sp::CDecl => {
let kids = self.children_of(item);
let Some(t) = Self::field_in(&kids, "type") else {
return;
};
let (k, label) = match t.kind {
"struct_specifier" => (SymbolKind::Struct, "struct"),
"class_specifier" => (SymbolKind::Class, "class"),
"enum_specifier" => (SymbolKind::Enum, "enum"),
_ => return,
};
let tkids = self.children_of(t);
if Self::field_in(&tkids, "body").is_none() {
return;
}
let mut name = Self::field_in(&tkids, "name")
.map_or(String::new(), |c| self.clean(self.text(c)));
if name.is_empty() {
name = Self::field_in(&kids, "declarator")
.map_or(String::new(), |c| self.clean(self.text(c)));
}
self.push(k, label, name, item, depth, first);
}
}
}
fn ex_call(&mut self, item: VItem, depth: u32, first: &mut Option<String>) {
let kids = self.children_of(item);
let Some(t) = Self::field_in(&kids, "target") else {
return;
};
if t.kind != "identifier" {
return;
}
let word = self.text(t).to_string();
let args = kids.iter().copied().find(|c| c.kind == "arguments");
let first_arg = args.and_then(|a| {
self.children_of(a)
.into_iter()
.find(|c| c.kind != "comment")
});
let (kind, label, container) = match word.as_str() {
"import" | "alias" | "use" | "require" => return self.import(item),
"defmodule" => (SymbolKind::Module, "module", true),
"defprotocol" => (SymbolKind::Interface, "protocol", true),
"defimpl" => (SymbolKind::Module, "impl", true),
"def" | "defp" | "defmacro" | "defmacrop" => {
if depth > 0 {
(SymbolKind::Method, "method", false)
} else {
(SymbolKind::Function, "function", false)
}
}
_ => return,
};
let mut at = first_arg;
for _ in 0..8 {
match at {
Some(a) if a.kind == "binary_operator" => at = self.field_of(a, "left"),
Some(a) if a.kind == "call" => at = self.field_of(a, "target"),
_ => break,
}
}
let name = at.map(|a| self.clean(self.text(a))).unwrap_or_default();
self.push(kind, label, name, item, depth, first);
if container {
for c in kids.into_iter().filter(|c| c.kind == "do_block") {
for d in self.children_of(c) {
self.walk(d, true, 1, depth + 1, first);
}
}
}
}
fn go_imports(&mut self, item: VItem, depth: u32) {
for c in self.children_of(item) {
match c.kind {
"import_spec" => self.import(c),
"import_spec_list" if depth < 2 => self.go_imports(c, depth + 1),
_ => {}
}
}
}
}
fn is_identifier(kind: &str) -> bool {
matches!(
kind,
"identifier"
| "simple_identifier"
| "field_identifier"
| "qualified_identifier"
| "type_identifier"
| "value_name"
| "module_name"
| "type_constructor"
| "class_name"
| "module_type_name"
| "moduleName"
| "function_name"
| "simple_name"
| "atom"
| "unquoted_argument"
| "lower_case_identifier"
| "method_identifier"
| "destructor_name"
| "operator_name"
)
}