use std::collections::HashMap;
use crate::compile::{CompileOptions, start};
use crate::parse::{Exports, Parser, Program, PropValue, merge_exports};
use crate::pp::{Diagnostic, Severity, SourceFiles};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DocPlace {
pub file: String,
pub line: u32,
}
#[derive(Debug, Clone)]
pub struct DocMember {
pub name: String,
pub declaration: String,
pub comment: String,
pub place: DocPlace,
pub is_method: bool,
pub stages: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct DocObject {
pub name: String,
pub is_class: bool,
pub superclasses: Vec<String>,
pub place: DocPlace,
pub comment: String,
pub modified_in: Vec<DocPlace>,
pub members: Vec<DocMember>,
pub from_library: bool,
pub values: Vec<(String, String)>,
}
impl DocObject {
pub fn value(&self, prop: &str) -> Option<&str> {
self.values
.iter()
.find(|(name, _)| name == prop)
.map(|(_, value)| value.as_str())
}
}
#[derive(Debug, Clone)]
pub struct DocFunction {
pub name: String,
pub declaration: String,
pub comment: String,
pub place: DocPlace,
pub from_library: bool,
}
#[derive(Debug, Clone)]
pub struct DocVerb {
pub action: String,
pub words: String,
pub place: DocPlace,
}
#[derive(Debug, Clone)]
pub struct DocMessage {
pub id: String,
pub text: String,
pub place: DocPlace,
}
#[derive(Debug, Clone)]
pub struct DocMacro {
pub name: String,
pub params: String,
pub expansion: String,
pub comment: String,
pub place: DocPlace,
}
#[derive(Debug, Clone)]
pub struct DocTemplate {
pub class: String,
pub text: String,
pub place: DocPlace,
}
#[derive(Debug, Clone)]
pub struct DocEnum {
pub names: Vec<String>,
pub is_token: bool,
pub comment: String,
pub place: DocPlace,
}
#[derive(Debug, Clone)]
pub struct DocFile {
pub name: String,
pub lines: Vec<String>,
pub from_library: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DocUse {
pub name: String,
pub place: DocPlace,
pub columns: (u32, u32),
}
#[derive(Debug, Default)]
pub struct Documented {
pub uses: Vec<DocUse>,
pub objects: Vec<DocObject>,
pub anonymous: Vec<DocObject>,
pub functions: Vec<DocFunction>,
pub verbs: Vec<DocVerb>,
pub messages: Vec<DocMessage>,
pub macros: Vec<DocMacro>,
pub templates: Vec<DocTemplate>,
pub enums: Vec<DocEnum>,
pub files: Vec<DocFile>,
pub diagnostics: Vec<Diagnostic>,
}
pub fn document(
files: &mut dyn SourceFiles,
sources: &[&str],
options: &CompileOptions,
) -> Documented {
let mut files = crate::builtin::WithBuiltIns::for_sources(files, sources);
let files: &mut dyn SourceFiles = &mut files;
let mut documented = Documented::default();
let mut exports = Vec::new();
for source in sources {
let mut pp = match start(files, source, options) {
Ok(pp) => pp,
Err(diagnostic) => {
documented.diagnostics.push(diagnostic);
return documented;
}
};
let prog = Parser::new(&mut pp, true, Exports::default()).parse_top();
let errors: Vec<Diagnostic> = pp
.take_diagnostics()
.into_iter()
.filter(|d| d.severity != Severity::Warning)
.collect();
if !errors.is_empty() {
documented.diagnostics.extend(errors);
return documented;
}
exports.push(prog.exports());
}
let known = crate::parse::Program::knowing(merge_exports(exports));
let mut reading = Reading::default();
for (index, source) in sources.iter().enumerate() {
let from_library = options.from_library.get(index) == Some(&true);
let mut pp = match start(files, source, options) {
Ok(pp) => pp,
Err(diagnostic) => {
return reading.stopped(vec![diagnostic]);
}
};
let mut parser = Parser::with_program(&mut pp, false, known.clone());
parser.set_record_uses(!from_library);
let prog = parser.parse_top();
let errors: Vec<Diagnostic> = pp
.take_diagnostics()
.into_iter()
.filter(|d| d.severity != Severity::Warning)
.collect();
if !errors.is_empty() {
return reading.stopped(errors);
}
let names: Vec<String> = pp.file_names();
reading.add(&prog, &names, from_library, files);
}
reading.finish(files)
}
#[derive(Default)]
pub(crate) struct Reading {
texts: HashMap<String, Vec<String>>,
by_name: HashMap<String, usize>,
order: Vec<(String, bool)>,
documented: Documented,
}
impl Reading {
pub(crate) fn add(
&mut self,
prog: &Program,
names: &[String],
from_library: bool,
files: &mut dyn SourceFiles,
) {
for name in names {
if !self.order.iter().any(|(seen, _)| seen == name) {
self.order.push((name.clone(), from_library));
}
}
let mut seen: std::collections::HashSet<(usize, u32, (u32, u32))> =
std::collections::HashSet::new();
for used in &prog.uses {
let Some(file) = names.get(used.file) else {
continue;
};
let built_in = file.starts_with(crate::builtin::ROOT);
let english = crate::english::is_english(file);
if built_in || english || !seen.insert((used.file, used.line, used.columns)) {
continue;
}
self.documented.uses.push(DocUse {
name: String::from_utf8_lossy(&used.name).into_owned(),
place: DocPlace {
file: file.clone(),
line: used.line,
},
columns: used.columns,
});
}
collect_functions(
prog,
names,
from_library,
files,
&mut self.texts,
&mut self.documented.functions,
);
collect(
prog,
names,
from_library,
files,
&mut self.texts,
&mut self.by_name,
&mut self.documented,
);
}
pub(crate) fn stopped(mut self, problems: Vec<Diagnostic>) -> Documented {
self.documented.diagnostics.extend(problems);
self.documented
}
pub(crate) fn finish(self, files: &mut dyn SourceFiles) -> Documented {
let Reading {
mut texts,
order,
mut documented,
..
} = self;
for (name, from_library) in order {
let lines = match texts.remove(&name) {
Some(lines) => lines,
None => read_lines(files, &name),
};
if lines.is_empty() {
continue;
}
scan_verbs(&name, &lines, &mut documented.verbs);
scan_messages(&name, &lines, &mut documented.messages);
scan_macros(&name, &lines, &mut documented.macros);
scan_templates(&name, &lines, &mut documented.templates);
scan_enums(&name, &lines, &mut documented.enums);
documented.files.push(DocFile {
name,
lines,
from_library,
});
}
documented
}
}
fn read_lines(files: &mut dyn SourceFiles, name: &str) -> Vec<String> {
files
.read(name)
.map(|bytes| {
String::from_utf8_lossy(&bytes)
.replace("\r\n", "\n")
.split('\n')
.map(str::to_owned)
.collect()
})
.unwrap_or_default()
}
fn collect_functions(
prog: &Program,
file_names: &[String],
from_library: bool,
files: &mut dyn SourceFiles,
texts: &mut HashMap<String, Vec<String>>,
functions: &mut Vec<DocFunction>,
) {
for func in &prog.funcs {
if func.is_extern || func.is_mm_base {
continue;
}
let Some(body) = func.body else {
continue;
};
let Some((file, brace)) = prog.bodies.get(body).and_then(|(body, _)| body.start) else {
continue;
};
let name = String::from_utf8_lossy(&func.name).into_owned();
if name.is_empty() || !name.starts_with(|c: char| c.is_ascii_alphabetic()) {
continue;
}
let file_name = file_names.get(file).cloned().unwrap_or_default();
let lines = texts
.entry(file_name.clone())
.or_insert_with(|| read_lines(files, &file_name));
let start = start_of(lines, brace, &name);
let at = functions.iter().position(|f| f.name == name);
let function = DocFunction {
declaration: declaration(lines, start, start),
comment: comment_above(lines, start),
place: DocPlace {
file: file_name,
line: start,
},
from_library,
name,
};
match at {
Some(at) => functions[at] = function,
None => functions.push(function),
}
}
}
pub(crate) fn scan_verbs(file: &str, lines: &[String], verbs: &mut Vec<DocVerb>) {
for (index, line) in lines.iter().enumerate() {
let rest = line
.strip_prefix("modify ")
.or_else(|| line.strip_prefix("replace "))
.unwrap_or(line);
let Some(rest) = rest.strip_prefix("verb ") else {
continue;
};
let mut words = rest.split_whitespace();
let Some(name) = words.next() else {
continue;
};
let name = name.trim_end_matches(':');
let mut action = name.to_owned();
let mut text = String::new();
let mut taken = rest[rest.find(name).unwrap_or(0) + name.len()..]
.trim()
.to_owned();
if let Some(after) = taken.strip_prefix("for ") {
let after = after.trim_start();
let end = after.find(char::is_whitespace).unwrap_or(after.len());
action = after[..end].trim_end_matches(':').to_owned();
taken = after[end..].trim().to_owned();
}
let mut next = index + 1;
loop {
if !text.is_empty() {
text.push(' ');
}
text.push_str(&taken);
if let Some(at) = rule_colon(&text) {
text.truncate(at);
break;
}
match lines.get(next) {
Some(line) if next < index + 12 => {
taken = line.trim().to_owned();
next += 1;
}
_ => break,
}
}
let text = match text.trim_start().strip_prefix('[') {
Some(rest) => rest
.split_once(']')
.map_or(rest, |(_, after)| after)
.to_owned(),
None => text,
};
verbs.push(DocVerb {
action,
words: text.split_whitespace().collect::<Vec<_>>().join(" "),
place: DocPlace {
file: file.to_owned(),
line: index as u32 + 1,
},
});
}
}
pub(crate) fn scan_macros(file: &str, lines: &[String], macros: &mut Vec<DocMacro>) {
for (index, line) in lines.iter().enumerate() {
let Some(rest) = line.trim_start().strip_prefix("#define") else {
continue;
};
let rest = rest.trim_start();
let end = rest
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
.unwrap_or(rest.len());
let name = &rest[..end];
if name.is_empty() {
continue;
}
let mut after = &rest[end..];
let mut params = String::new();
if after.starts_with('(')
&& let Some(close) = after.find(')')
{
params = after[..=close].to_owned();
after = &after[close + 1..];
}
let mut expansion = after.trim().to_owned();
let mut next = index + 1;
while expansion.ends_with('\\') && next < lines.len() {
expansion.pop();
expansion.push(' ');
expansion.push_str(lines[next].trim());
next += 1;
}
let expansion = expansion.split_whitespace().collect::<Vec<_>>().join(" ");
macros.push(DocMacro {
name: name.to_owned(),
params,
expansion: if expansion.chars().count() > 200 {
expansion.chars().take(197).collect::<String>() + "..."
} else {
expansion
},
comment: comment_above(lines, index as u32 + 1),
place: DocPlace {
file: file.to_owned(),
line: index as u32 + 1,
},
});
}
}
pub(crate) fn scan_templates(file: &str, lines: &[String], templates: &mut Vec<DocTemplate>) {
for (index, line) in lines.iter().enumerate() {
let mut words = line.split_whitespace();
let (Some(class), Some("template")) = (words.next(), words.next()) else {
continue;
};
if !class.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
continue;
}
let mut text = line.trim().to_owned();
let mut next = index + 1;
while !text.ends_with(';') && next < lines.len() && next < index + 8 {
text.push(' ');
text.push_str(lines[next].trim());
next += 1;
}
templates.push(DocTemplate {
class: class.to_owned(),
text: text.split_whitespace().collect::<Vec<_>>().join(" "),
place: DocPlace {
file: file.to_owned(),
line: index as u32 + 1,
},
});
}
}
pub(crate) fn scan_enums(file: &str, lines: &[String], enums: &mut Vec<DocEnum>) {
for (index, line) in lines.iter().enumerate() {
let Some(rest) = line.strip_prefix("enum ") else {
continue;
};
let mut text = rest.trim().to_owned();
let mut next = index + 1;
while !text.contains(';') && next < lines.len() && next < index + 20 {
text.push(' ');
text.push_str(lines[next].trim());
next += 1;
}
let text = text.split(';').next().unwrap_or_default().trim();
let (is_token, text) = match text.strip_prefix("token ") {
Some(rest) => (true, rest),
None => (false, text),
};
let names: Vec<String> = text
.split(',')
.map(|n| n.trim().to_owned())
.filter(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
.collect();
if names.is_empty() {
continue;
}
enums.push(DocEnum {
names,
is_token,
comment: comment_above(lines, index as u32 + 1),
place: DocPlace {
file: file.to_owned(),
line: index as u32 + 1,
},
});
}
}
fn rule_colon(text: &str) -> Option<usize> {
let mut quote: Option<char> = None;
let mut escaped = false;
for (at, c) in text.char_indices() {
if let Some(q) = quote {
if escaped {
escaped = false;
} else if c == '\\' {
escaped = true;
} else if c == q {
quote = None;
}
continue;
}
match c {
'\'' | '"' => quote = Some(c),
':' => return Some(at),
_ => {}
}
}
None
}
pub(crate) fn scan_messages(file: &str, lines: &[String], messages: &mut Vec<DocMessage>) {
for (index, line) in lines.iter().enumerate() {
let code = line.trim_start();
if code.starts_with("//") || code.starts_with('*') || code.starts_with("/*") {
continue;
}
for marker in ["msgText(", "showMsg("] {
let mut from = 0;
while let Some(at) = line[from..].find(marker) {
let start = from + at + marker.len();
from = start;
let before = line[..start - marker.len()].chars().next_back();
if before.is_some_and(|c| c.is_ascii_alphanumeric() || c == '_') {
continue;
}
let Some(comma) = line[start..].find(',') else {
continue;
};
let id = line[start..start + comma].trim();
if id.is_empty() || id.contains(['\'', '"', '(', ')', '.']) {
continue;
}
let mut text = line[start + comma + 1..].trim().to_owned();
let mut next = index + 1;
while (text.is_empty() || unfinished(&text))
&& next < lines.len()
&& next < index + 20
{
if !text.is_empty() {
text.push(' ');
}
text.push_str(lines[next].trim());
next += 1;
}
let text = message_text(&text);
if text.is_empty() && !id.contains(' ') {
continue;
}
messages.push(DocMessage {
id: id.to_owned(),
text,
place: DocPlace {
file: file.to_owned(),
line: index as u32 + 1,
},
});
}
}
}
}
fn message_text(text: &str) -> String {
let text = text.trim_start();
let Some(q) = text.chars().next().filter(|c| matches!(c, '\'' | '"')) else {
return String::new();
};
let mut out = String::new();
let mut escaped = false;
for c in text[1..].chars() {
if escaped {
out.push(c);
escaped = false;
} else if c == '\\' {
escaped = true;
} else if c == q {
break;
} else {
out.push(c);
}
}
out.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn collect(
prog: &Program,
file_names: &[String],
from_library: bool,
files: &mut dyn SourceFiles,
texts: &mut HashMap<String, Vec<String>>,
by_name: &mut HashMap<String, usize>,
documented: &mut Documented,
) {
let Documented {
objects, anonymous, ..
} = documented;
let names_by_id: HashMap<u32, String> = prog
.objs
.iter()
.map(|o| (o.id, String::from_utf8_lossy(&o.name).into_owned()))
.collect();
for name in file_names {
if !texts.contains_key(name) {
texts.insert(name.clone(), split_lines(files, name));
}
}
let texts: &HashMap<String, Vec<String>> = texts;
let none: Vec<String> = Vec::new();
let lines_of = |file: usize| -> (&str, &Vec<String>) {
let name = file_names.get(file).map_or("", String::as_str);
(name, texts.get(name).unwrap_or(&none))
};
for (index, def) in prog.objdefs.iter().enumerate() {
let Some(sym) = def.sym else {
continue;
};
if prog.src_group_defs.contains(&index) {
continue;
}
let name = String::from_utf8_lossy(&prog.objs[sym].name).into_owned();
let unnamed = name == ".anon" && !def.is_class && !def.is_modify;
if (!unnamed && (name.is_empty() || name.starts_with('.')))
|| name.starts_with(' ')
|| name.contains('(')
|| prog.objs[sym].is_grammar_rule
{
continue;
}
let (file, lines) = lines_of(def.file);
let place = DocPlace {
file: file.to_owned(),
line: def.line,
};
let members: Vec<DocMember> = def
.props
.iter()
.filter(|prop| !prop.overwritable && !matches!(prop.value, PropValue::VocabList))
.filter_map(|prop| {
let prop_name =
String::from_utf8_lossy(&prog.props.get(prop.prop)?.name).into_owned();
let (prop_file, prop_lines) = if prop.file == def.file {
(file, lines)
} else {
lines_of(prop.file)
};
if crate::english::is_english(prop_file) {
return Some(DocMember {
declaration: prop_name.clone(),
comment: String::new(),
place: DocPlace {
file: prop_file.to_owned(),
line: prop.line,
},
is_method: matches!(prop.value, PropValue::Method(_)),
name: prop_name,
stages: Vec::new(),
});
}
let start = start_of(prop_lines, prop.line, &prop_name);
Some(DocMember {
declaration: declaration(prop_lines, start, prop.line),
comment: comment_above(prop_lines, start),
place: DocPlace {
file: prop_file.to_owned(),
line: start,
},
is_method: matches!(prop.value, PropValue::Method(_)),
name: prop_name,
stages: Vec::new(),
})
})
.collect();
let members = handlers(members, texts);
let values: Vec<(String, String)> = def
.props
.iter()
.filter_map(|prop| {
let PropValue::Expr(expr) = &prop.value else {
return None;
};
let prop_name =
String::from_utf8_lossy(&prog.props.get(prop.prop)?.name).into_owned();
Some((prop_name, written_value(expr, &names_by_id)?))
})
.collect();
if unnamed {
anonymous.push(DocObject {
name: String::new(),
is_class: false,
superclasses: def
.superclasses
.iter()
.map(|s| String::from_utf8_lossy(s).into_owned())
.collect(),
comment: written_comment(file, lines, def.line),
place,
modified_in: Vec::new(),
members,
from_library,
values,
});
continue;
}
match by_name.get(&name).copied() {
Some(at) if def.is_modify => {
let object = &mut objects[at];
object.modified_in.push(place);
for member in members {
match object.members.iter().position(|m| m.name == member.name) {
Some(i) => object.members[i] = member,
None => object.members.push(member),
}
}
for (prop, value) in values {
object.values.retain(|(have, _)| *have != prop);
object.values.push((prop, value));
}
}
None if def.is_modify => {}
_ => {
let object = DocObject {
name: name.clone(),
is_class: def.is_class,
superclasses: def
.superclasses
.iter()
.map(|s| String::from_utf8_lossy(s).into_owned())
.collect(),
comment: written_comment(file, lines, def.line),
place,
modified_in: Vec::new(),
members,
from_library,
values,
};
match by_name.get(&name) {
Some(&at) => objects[at] = object,
None => {
by_name.insert(name, objects.len());
objects.push(object);
}
}
}
}
}
}
fn written_comment(file: &str, lines: &[String], line: u32) -> String {
if crate::english::is_english(file) {
String::new()
} else {
comment_above(lines, line)
}
}
fn split_lines(files: &mut dyn SourceFiles, name: &str) -> Vec<String> {
files
.read(name)
.map(|bytes| {
String::from_utf8_lossy(&bytes)
.replace("\r\n", "\n")
.split('\n')
.map(str::to_owned)
.collect()
})
.unwrap_or_default()
}
fn written_value(expr: &crate::ast::Expr, names_by_id: &HashMap<u32, String>) -> Option<String> {
use crate::ast::Expr;
match expr {
Expr::Sym(name) => Some(String::from_utf8_lossy(name).into_owned()),
Expr::DStr(bytes) => Some(format!("\"{}\"", String::from_utf8_lossy(bytes))),
Expr::Const(c) => written_constant(&c.value, names_by_id),
Expr::List(items) => {
let items: Option<Vec<String>> = items
.iter()
.map(|item| written_value(item, names_by_id))
.collect();
Some(format!("[{}]", items?.join(", ")))
}
_ => None,
}
}
fn written_constant(
value: &crate::ast::Value,
names_by_id: &HashMap<u32, String>,
) -> Option<String> {
use crate::ast::Value;
match value {
Value::Nil => Some("nil".to_owned()),
Value::True => Some("true".to_owned()),
Value::Int(n) => Some(n.to_string()),
Value::SStr(bytes) => Some(format!("'{}'", String::from_utf8_lossy(bytes))),
Value::Obj(id) => names_by_id.get(id).filter(|n| !n.is_empty()).cloned(),
Value::List(items) => {
let items: Option<Vec<String>> = items
.iter()
.map(|item| written_constant(&item.value, names_by_id))
.collect();
Some(format!("[{}]", items?.join(", ")))
}
_ => None,
}
}
const STAGES: [&str; 6] = ["verify", "check", "action", "report", "preCond", "remap"];
fn handler_stage(name: &str) -> Option<(&'static str, &'static str, &str)> {
for stage in STAGES {
let Some(rest) = name.strip_prefix(stage) else {
continue;
};
for (role, mark) in [("dobj", "Dobj"), ("iobj", "Iobj"), ("aobj", "Aobj")] {
if let Some(action) = rest.strip_prefix(mark)
&& action.starts_with(|c: char| c.is_ascii_uppercase())
{
return Some((stage, role, action));
}
}
}
None
}
fn handlers(members: Vec<DocMember>, texts: &HashMap<String, Vec<String>>) -> Vec<DocMember> {
let mut out: Vec<DocMember> = Vec::new();
for member in members {
let Some((stage, role, action)) = handler_stage(&member.name) else {
out.push(member);
continue;
};
let name = format!("{role} {action}");
if let Some(handler) = out.iter_mut().find(|m| m.name == name) {
handler.stages.push(stage.to_owned());
if member.place.line < handler.place.line && member.place.file == handler.place.file {
handler.place.line = member.place.line;
}
continue;
}
out.push(DocMember {
name,
declaration: String::new(),
comment: String::new(),
place: member.place,
is_method: true,
stages: vec![stage.to_owned()],
});
}
for member in out.iter_mut().filter(|m| !m.stages.is_empty()) {
let english = crate::english::is_english(&member.place.file);
let Some(lines) = texts.get(&member.place.file).filter(|_| !english) else {
if member.declaration.is_empty() {
member.declaration = member.name.clone();
}
continue;
};
let (role, action) = member.name.split_once(' ').unwrap_or_default();
let mut at = member.place.line as usize;
while at > 0 {
let line = lines.get(at - 1).map(String::as_str).unwrap_or_default();
let words: Vec<&str> = line.split_whitespace().collect();
if words.len() >= 2 && words[0] == role && words[1] == action {
member.place.line = at as u32;
member.declaration = line.trim().to_owned();
member.comment = comment_above(lines, at as u32);
break;
}
at -= 1;
}
if member.declaration.is_empty() {
member.declaration = member.name.clone();
}
}
out
}
fn start_of(lines: &[String], end: u32, name: &str) -> u32 {
let mut at = end as usize;
let mut looked = 0;
while at > 0 && looked < 200 {
let line = lines
.get(at - 1)
.map(|l| l.trim_start())
.unwrap_or_default();
if let Some(rest) = line.strip_prefix(name) {
let rest = rest.trim_start();
if rest.is_empty() || rest.starts_with(['=', '(', ':', '{']) {
return at as u32;
}
}
at -= 1;
looked += 1;
}
end
}
fn body_brace(text: &str) -> Option<usize> {
let mut quote: Option<char> = None;
let mut escaped = false;
for (at, c) in text.char_indices() {
if let Some(q) = quote {
if escaped {
escaped = false;
} else if c == '\\' {
escaped = true;
} else if c == q {
quote = None;
}
continue;
}
match c {
'\'' | '"' => quote = Some(c),
'{' => return Some(at),
_ => {}
}
}
None
}
fn unfinished(text: &str) -> bool {
let mut depth = 0;
let mut quote: Option<char> = None;
let mut escaped = false;
for c in text.chars() {
if let Some(q) = quote {
if escaped {
escaped = false;
} else if c == '\\' {
escaped = true;
} else if c == q {
quote = None;
}
continue;
}
match c {
'\'' | '"' => quote = Some(c),
'(' => depth += 1,
')' => depth -= 1,
_ => {}
}
}
depth > 0 || quote.is_some()
}
fn declaration(lines: &[String], start: u32, end: u32) -> String {
let mut text = String::new();
let mut line = start;
while line <= end.max(start) || (unfinished(&text) && line < start + 40) {
let Some(part) = lines.get((line as usize).wrapping_sub(1)) else {
break;
};
if !text.is_empty() {
text.push(' ');
}
text.push_str(part.trim());
if body_brace(&text).is_some() {
break;
}
line += 1;
}
let text = match body_brace(&text) {
Some(at) if at > 0 => text[..at].trim_end().to_owned(),
_ => text,
};
let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
let text = text.trim_end_matches(';').trim_end().to_owned();
if text.chars().count() > 120 {
text.chars().take(117).collect::<String>() + "..."
} else {
text
}
}
pub fn comment_above(lines: &[String], line: u32) -> String {
let mut at = line as usize;
let mut blank = 0;
let mut above = || -> Option<&str> {
at = at.checked_sub(1)?;
lines.get(at.checked_sub(1)?).map(String::as_str)
};
let mut text = loop {
let Some(line) = above() else {
return String::new();
};
if line.trim().is_empty() {
blank += 1;
if blank > 1 {
return String::new();
}
continue;
}
break line.trim().to_owned();
};
let mut taken: Vec<String> = Vec::new();
if text.ends_with("*/") {
loop {
let opens = text.contains("/*");
taken.push(text.clone());
if opens {
break;
}
match above() {
Some(line) => text = line.trim().to_owned(),
None => break,
}
}
} else if text.starts_with("//") {
loop {
taken.push(text.clone());
match above() {
Some(line) if line.trim().starts_with("//") => text = line.trim().to_owned(),
_ => break,
}
}
} else {
return String::new();
}
taken.reverse();
clean(&taken)
}
fn clean(lines: &[String]) -> String {
let mut out: Vec<String> = Vec::new();
for line in lines {
let mut text = line.as_str();
text = text.trim_start_matches("/*").trim_start_matches("//");
text = text.trim_end_matches("*/");
let text = text.trim().trim_start_matches('*').trim();
let is_rule = !text.is_empty()
&& text
.chars()
.all(|c| matches!(c, '-' | '=' | '*' | '/' | '~' | '_' | ' '));
if is_rule {
continue;
}
out.push(text.to_owned());
}
let mut paragraphs: Vec<String> = Vec::new();
let mut current = String::new();
for line in out {
if line.is_empty() {
if !current.is_empty() {
paragraphs.push(std::mem::take(&mut current));
}
} else {
if !current.is_empty() {
current.push(' ');
}
current.push_str(&line);
}
}
if !current.is_empty() {
paragraphs.push(current);
}
paragraphs.join("\n\n")
}