1use std::collections::HashMap;
11
12use crate::compile::{CompileOptions, start};
13use crate::parse::{Exports, Parser, Program, PropValue, merge_exports};
14use crate::pp::{Diagnostic, Severity, SourceFiles};
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct DocPlace {
19 pub file: String,
21 pub line: u32,
23}
24
25#[derive(Debug, Clone)]
27pub struct DocMember {
28 pub name: String,
30 pub declaration: String,
33 pub comment: String,
35 pub place: DocPlace,
37 pub is_method: bool,
39 pub stages: Vec<String>,
43}
44
45#[derive(Debug, Clone)]
47pub struct DocObject {
48 pub name: String,
50 pub is_class: bool,
52 pub superclasses: Vec<String>,
54 pub place: DocPlace,
56 pub comment: String,
58 pub modified_in: Vec<DocPlace>,
60 pub members: Vec<DocMember>,
63 pub from_library: bool,
65 pub values: Vec<(String, String)>,
71}
72
73impl DocObject {
74 pub fn value(&self, prop: &str) -> Option<&str> {
76 self.values
77 .iter()
78 .find(|(name, _)| name == prop)
79 .map(|(_, value)| value.as_str())
80 }
81}
82
83#[derive(Debug, Clone)]
85pub struct DocFunction {
86 pub name: String,
88 pub declaration: String,
90 pub comment: String,
92 pub place: DocPlace,
94 pub from_library: bool,
96}
97
98#[derive(Debug, Clone)]
100pub struct DocVerb {
101 pub action: String,
103 pub words: String,
105 pub place: DocPlace,
107}
108
109#[derive(Debug, Clone)]
112pub struct DocMessage {
113 pub id: String,
115 pub text: String,
117 pub place: DocPlace,
119}
120
121#[derive(Debug, Clone)]
123pub struct DocMacro {
124 pub name: String,
126 pub params: String,
128 pub expansion: String,
130 pub comment: String,
132 pub place: DocPlace,
134}
135
136#[derive(Debug, Clone)]
139pub struct DocTemplate {
140 pub class: String,
142 pub text: String,
145 pub place: DocPlace,
147}
148
149#[derive(Debug, Clone)]
151pub struct DocEnum {
152 pub names: Vec<String>,
154 pub is_token: bool,
156 pub comment: String,
158 pub place: DocPlace,
160}
161
162#[derive(Debug, Clone)]
164pub struct DocFile {
165 pub name: String,
167 pub lines: Vec<String>,
169 pub from_library: bool,
171}
172
173#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct DocUse {
178 pub name: String,
180 pub place: DocPlace,
182 pub columns: (u32, u32),
184}
185
186#[derive(Debug, Default)]
188pub struct Documented {
189 pub uses: Vec<DocUse>,
193 pub objects: Vec<DocObject>,
195 pub anonymous: Vec<DocObject>,
198 pub functions: Vec<DocFunction>,
200 pub verbs: Vec<DocVerb>,
202 pub messages: Vec<DocMessage>,
204 pub macros: Vec<DocMacro>,
206 pub templates: Vec<DocTemplate>,
208 pub enums: Vec<DocEnum>,
210 pub files: Vec<DocFile>,
212 pub diagnostics: Vec<Diagnostic>,
214}
215
216pub fn document(
218 files: &mut dyn SourceFiles,
219 sources: &[&str],
220 options: &CompileOptions,
221) -> Documented {
222 let mut files = crate::builtin::WithBuiltIns::for_sources(files, sources);
223 let files: &mut dyn SourceFiles = &mut files;
224 let mut documented = Documented::default();
225
226 let mut exports = Vec::new();
228 for source in sources {
229 let mut pp = match start(files, source, options) {
230 Ok(pp) => pp,
231 Err(diagnostic) => {
232 documented.diagnostics.push(diagnostic);
233 return documented;
234 }
235 };
236 let prog = Parser::new(&mut pp, true, Exports::default()).parse_top();
237 let errors: Vec<Diagnostic> = pp
238 .take_diagnostics()
239 .into_iter()
240 .filter(|d| d.severity != Severity::Warning)
241 .collect();
242 if !errors.is_empty() {
243 documented.diagnostics.extend(errors);
244 return documented;
245 }
246 exports.push(prog.exports());
247 }
248 let known = crate::parse::Program::knowing(merge_exports(exports));
250
251 let mut reading = Reading::default();
253 for (index, source) in sources.iter().enumerate() {
254 let from_library = options.from_library.get(index) == Some(&true);
255 let mut pp = match start(files, source, options) {
256 Ok(pp) => pp,
257 Err(diagnostic) => {
258 return reading.stopped(vec![diagnostic]);
259 }
260 };
261 let mut parser = Parser::with_program(&mut pp, false, known.clone());
262 parser.set_record_uses(!from_library);
263 let prog = parser.parse_top();
264 let errors: Vec<Diagnostic> = pp
265 .take_diagnostics()
266 .into_iter()
267 .filter(|d| d.severity != Severity::Warning)
268 .collect();
269 if !errors.is_empty() {
270 return reading.stopped(errors);
271 }
272 let names: Vec<String> = pp.file_names();
273 reading.add(&prog, &names, from_library, files);
274 }
275 reading.finish(files)
276}
277
278#[derive(Default)]
282pub(crate) struct Reading {
283 texts: HashMap<String, Vec<String>>,
285 by_name: HashMap<String, usize>,
287 order: Vec<(String, bool)>,
290 documented: Documented,
291}
292
293impl Reading {
294 pub(crate) fn add(
297 &mut self,
298 prog: &Program,
299 names: &[String],
300 from_library: bool,
301 files: &mut dyn SourceFiles,
302 ) {
303 for name in names {
304 if !self.order.iter().any(|(seen, _)| seen == name) {
305 self.order.push((name.clone(), from_library));
306 }
307 }
308 let mut seen: std::collections::HashSet<(usize, u32, (u32, u32))> =
311 std::collections::HashSet::new();
312 for used in &prog.uses {
313 let Some(file) = names.get(used.file) else {
314 continue;
315 };
316 let built_in = file.starts_with(crate::builtin::ROOT);
317 let english = crate::english::is_english(file);
318 if built_in || english || !seen.insert((used.file, used.line, used.columns)) {
319 continue;
320 }
321 self.documented.uses.push(DocUse {
322 name: String::from_utf8_lossy(&used.name).into_owned(),
323 place: DocPlace {
324 file: file.clone(),
325 line: used.line,
326 },
327 columns: used.columns,
328 });
329 }
330 collect_functions(
331 prog,
332 names,
333 from_library,
334 files,
335 &mut self.texts,
336 &mut self.documented.functions,
337 );
338 collect(
339 prog,
340 names,
341 from_library,
342 files,
343 &mut self.texts,
344 &mut self.by_name,
345 &mut self.documented,
346 );
347 }
348
349 pub(crate) fn stopped(mut self, problems: Vec<Diagnostic>) -> Documented {
351 self.documented.diagnostics.extend(problems);
352 self.documented
353 }
354
355 pub(crate) fn finish(self, files: &mut dyn SourceFiles) -> Documented {
358 let Reading {
359 mut texts,
360 order,
361 mut documented,
362 ..
363 } = self;
364 for (name, from_library) in order {
365 let lines = match texts.remove(&name) {
366 Some(lines) => lines,
367 None => read_lines(files, &name),
368 };
369 if lines.is_empty() {
372 continue;
373 }
374 scan_verbs(&name, &lines, &mut documented.verbs);
375 scan_messages(&name, &lines, &mut documented.messages);
376 scan_macros(&name, &lines, &mut documented.macros);
377 scan_templates(&name, &lines, &mut documented.templates);
378 scan_enums(&name, &lines, &mut documented.enums);
379 documented.files.push(DocFile {
380 name,
381 lines,
382 from_library,
383 });
384 }
385 documented
386 }
387}
388
389fn read_lines(files: &mut dyn SourceFiles, name: &str) -> Vec<String> {
391 files
392 .read(name)
393 .map(|bytes| {
394 String::from_utf8_lossy(&bytes)
395 .replace("\r\n", "\n")
396 .split('\n')
397 .map(str::to_owned)
398 .collect()
399 })
400 .unwrap_or_default()
401}
402
403fn collect_functions(
405 prog: &Program,
406 file_names: &[String],
407 from_library: bool,
408 files: &mut dyn SourceFiles,
409 texts: &mut HashMap<String, Vec<String>>,
410 functions: &mut Vec<DocFunction>,
411) {
412 for func in &prog.funcs {
413 if func.is_extern || func.is_mm_base {
414 continue;
415 }
416 let Some(body) = func.body else {
417 continue;
418 };
419 let Some((file, brace)) = prog.bodies.get(body).and_then(|(body, _)| body.start) else {
420 continue;
421 };
422 let name = String::from_utf8_lossy(&func.name).into_owned();
423 if name.is_empty() || !name.starts_with(|c: char| c.is_ascii_alphabetic()) {
426 continue;
427 }
428 let file_name = file_names.get(file).cloned().unwrap_or_default();
429 let lines = texts
430 .entry(file_name.clone())
431 .or_insert_with(|| read_lines(files, &file_name));
432 let start = start_of(lines, brace, &name);
433 let at = functions.iter().position(|f| f.name == name);
434 let function = DocFunction {
435 declaration: declaration(lines, start, start),
436 comment: comment_above(lines, start),
437 place: DocPlace {
438 file: file_name,
439 line: start,
440 },
441 from_library,
442 name,
443 };
444 match at {
446 Some(at) => functions[at] = function,
447 None => functions.push(function),
448 }
449 }
450}
451
452pub(crate) fn scan_verbs(file: &str, lines: &[String], verbs: &mut Vec<DocVerb>) {
456 for (index, line) in lines.iter().enumerate() {
457 let rest = line
458 .strip_prefix("modify ")
459 .or_else(|| line.strip_prefix("replace "))
460 .unwrap_or(line);
461 let Some(rest) = rest.strip_prefix("verb ") else {
462 continue;
463 };
464 let mut words = rest.split_whitespace();
466 let Some(name) = words.next() else {
467 continue;
468 };
469 let name = name.trim_end_matches(':');
470 let mut action = name.to_owned();
471 let mut text = String::new();
472 let mut taken = rest[rest.find(name).unwrap_or(0) + name.len()..]
473 .trim()
474 .to_owned();
475 if let Some(after) = taken.strip_prefix("for ") {
476 let after = after.trim_start();
477 let end = after.find(char::is_whitespace).unwrap_or(after.len());
478 action = after[..end].trim_end_matches(':').to_owned();
479 taken = after[end..].trim().to_owned();
480 }
481 let mut next = index + 1;
483 loop {
484 if !text.is_empty() {
485 text.push(' ');
486 }
487 text.push_str(&taken);
488 if let Some(at) = rule_colon(&text) {
489 text.truncate(at);
490 break;
491 }
492 match lines.get(next) {
493 Some(line) if next < index + 12 => {
494 taken = line.trim().to_owned();
495 next += 1;
496 }
497 _ => break,
498 }
499 }
500 let text = match text.trim_start().strip_prefix('[') {
502 Some(rest) => rest
503 .split_once(']')
504 .map_or(rest, |(_, after)| after)
505 .to_owned(),
506 None => text,
507 };
508 verbs.push(DocVerb {
509 action,
510 words: text.split_whitespace().collect::<Vec<_>>().join(" "),
511 place: DocPlace {
512 file: file.to_owned(),
513 line: index as u32 + 1,
514 },
515 });
516 }
517}
518
519pub(crate) fn scan_macros(file: &str, lines: &[String], macros: &mut Vec<DocMacro>) {
522 for (index, line) in lines.iter().enumerate() {
523 let Some(rest) = line.trim_start().strip_prefix("#define") else {
524 continue;
525 };
526 let rest = rest.trim_start();
527 let end = rest
528 .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
529 .unwrap_or(rest.len());
530 let name = &rest[..end];
531 if name.is_empty() {
532 continue;
533 }
534 let mut after = &rest[end..];
536 let mut params = String::new();
537 if after.starts_with('(')
538 && let Some(close) = after.find(')')
539 {
540 params = after[..=close].to_owned();
541 after = &after[close + 1..];
542 }
543 let mut expansion = after.trim().to_owned();
544 let mut next = index + 1;
545 while expansion.ends_with('\\') && next < lines.len() {
546 expansion.pop();
547 expansion.push(' ');
548 expansion.push_str(lines[next].trim());
549 next += 1;
550 }
551 let expansion = expansion.split_whitespace().collect::<Vec<_>>().join(" ");
552 macros.push(DocMacro {
553 name: name.to_owned(),
554 params,
555 expansion: if expansion.chars().count() > 200 {
556 expansion.chars().take(197).collect::<String>() + "..."
557 } else {
558 expansion
559 },
560 comment: comment_above(lines, index as u32 + 1),
561 place: DocPlace {
562 file: file.to_owned(),
563 line: index as u32 + 1,
564 },
565 });
566 }
567}
568
569pub(crate) fn scan_templates(file: &str, lines: &[String], templates: &mut Vec<DocTemplate>) {
572 for (index, line) in lines.iter().enumerate() {
573 let mut words = line.split_whitespace();
574 let (Some(class), Some("template")) = (words.next(), words.next()) else {
575 continue;
576 };
577 if !class.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
578 continue;
579 }
580 let mut text = line.trim().to_owned();
581 let mut next = index + 1;
582 while !text.ends_with(';') && next < lines.len() && next < index + 8 {
583 text.push(' ');
584 text.push_str(lines[next].trim());
585 next += 1;
586 }
587 templates.push(DocTemplate {
588 class: class.to_owned(),
589 text: text.split_whitespace().collect::<Vec<_>>().join(" "),
590 place: DocPlace {
591 file: file.to_owned(),
592 line: index as u32 + 1,
593 },
594 });
595 }
596}
597
598pub(crate) fn scan_enums(file: &str, lines: &[String], enums: &mut Vec<DocEnum>) {
601 for (index, line) in lines.iter().enumerate() {
602 let Some(rest) = line.strip_prefix("enum ") else {
603 continue;
604 };
605 let mut text = rest.trim().to_owned();
606 let mut next = index + 1;
607 while !text.contains(';') && next < lines.len() && next < index + 20 {
608 text.push(' ');
609 text.push_str(lines[next].trim());
610 next += 1;
611 }
612 let text = text.split(';').next().unwrap_or_default().trim();
613 let (is_token, text) = match text.strip_prefix("token ") {
614 Some(rest) => (true, rest),
615 None => (false, text),
616 };
617 let names: Vec<String> = text
618 .split(',')
619 .map(|n| n.trim().to_owned())
620 .filter(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
621 .collect();
622 if names.is_empty() {
623 continue;
624 }
625 enums.push(DocEnum {
626 names,
627 is_token,
628 comment: comment_above(lines, index as u32 + 1),
629 place: DocPlace {
630 file: file.to_owned(),
631 line: index as u32 + 1,
632 },
633 });
634 }
635}
636
637fn rule_colon(text: &str) -> Option<usize> {
639 let mut quote: Option<char> = None;
640 let mut escaped = false;
641 for (at, c) in text.char_indices() {
642 if let Some(q) = quote {
643 if escaped {
644 escaped = false;
645 } else if c == '\\' {
646 escaped = true;
647 } else if c == q {
648 quote = None;
649 }
650 continue;
651 }
652 match c {
653 '\'' | '"' => quote = Some(c),
654 ':' => return Some(at),
655 _ => {}
656 }
657 }
658 None
659}
660
661pub(crate) fn scan_messages(file: &str, lines: &[String], messages: &mut Vec<DocMessage>) {
664 for (index, line) in lines.iter().enumerate() {
665 let code = line.trim_start();
666 if code.starts_with("//") || code.starts_with('*') || code.starts_with("/*") {
667 continue;
668 }
669 for marker in ["msgText(", "showMsg("] {
670 let mut from = 0;
671 while let Some(at) = line[from..].find(marker) {
672 let start = from + at + marker.len();
673 from = start;
674 let before = line[..start - marker.len()].chars().next_back();
676 if before.is_some_and(|c| c.is_ascii_alphanumeric() || c == '_') {
677 continue;
678 }
679 let Some(comma) = line[start..].find(',') else {
680 continue;
681 };
682 let id = line[start..start + comma].trim();
683 if id.is_empty() || id.contains(['\'', '"', '(', ')', '.']) {
685 continue;
686 }
687 let mut text = line[start + comma + 1..].trim().to_owned();
688 let mut next = index + 1;
689 while (text.is_empty() || unfinished(&text))
692 && next < lines.len()
693 && next < index + 20
694 {
695 if !text.is_empty() {
696 text.push(' ');
697 }
698 text.push_str(lines[next].trim());
699 next += 1;
700 }
701 let text = message_text(&text);
702 if text.is_empty() && !id.contains(' ') {
705 continue;
706 }
707 messages.push(DocMessage {
708 id: id.to_owned(),
709 text,
710 place: DocPlace {
711 file: file.to_owned(),
712 line: index as u32 + 1,
713 },
714 });
715 }
716 }
717 }
718}
719
720fn message_text(text: &str) -> String {
722 let text = text.trim_start();
723 let Some(q) = text.chars().next().filter(|c| matches!(c, '\'' | '"')) else {
724 return String::new();
725 };
726 let mut out = String::new();
727 let mut escaped = false;
728 for c in text[1..].chars() {
729 if escaped {
730 out.push(c);
731 escaped = false;
732 } else if c == '\\' {
733 escaped = true;
734 } else if c == q {
735 break;
736 } else {
737 out.push(c);
738 }
739 }
740 out.split_whitespace().collect::<Vec<_>>().join(" ")
741}
742
743fn collect(
745 prog: &Program,
746 file_names: &[String],
747 from_library: bool,
748 files: &mut dyn SourceFiles,
749 texts: &mut HashMap<String, Vec<String>>,
750 by_name: &mut HashMap<String, usize>,
751 documented: &mut Documented,
752) {
753 let Documented {
754 objects, anonymous, ..
755 } = documented;
756 let names_by_id: HashMap<u32, String> = prog
758 .objs
759 .iter()
760 .map(|o| (o.id, String::from_utf8_lossy(&o.name).into_owned()))
761 .collect();
762 for name in file_names {
764 if !texts.contains_key(name) {
765 texts.insert(name.clone(), split_lines(files, name));
766 }
767 }
768 let texts: &HashMap<String, Vec<String>> = texts;
769 let none: Vec<String> = Vec::new();
770 let lines_of = |file: usize| -> (&str, &Vec<String>) {
771 let name = file_names.get(file).map_or("", String::as_str);
772 (name, texts.get(name).unwrap_or(&none))
773 };
774
775 for (index, def) in prog.objdefs.iter().enumerate() {
776 let Some(sym) = def.sym else {
777 continue;
778 };
779 if prog.src_group_defs.contains(&index) {
781 continue;
782 }
783 let name = String::from_utf8_lossy(&prog.objs[sym].name).into_owned();
784 let unnamed = name == ".anon" && !def.is_class && !def.is_modify;
789 if (!unnamed && (name.is_empty() || name.starts_with('.')))
790 || name.starts_with(' ')
791 || name.contains('(')
792 || prog.objs[sym].is_grammar_rule
793 {
794 continue;
795 }
796 let (file, lines) = lines_of(def.file);
797 let place = DocPlace {
798 file: file.to_owned(),
799 line: def.line,
800 };
801 let members: Vec<DocMember> = def
802 .props
803 .iter()
804 .filter(|prop| !prop.overwritable && !matches!(prop.value, PropValue::VocabList))
805 .filter_map(|prop| {
806 let prop_name =
807 String::from_utf8_lossy(&prog.props.get(prop.prop)?.name).into_owned();
808 let (prop_file, prop_lines) = if prop.file == def.file {
809 (file, lines)
810 } else {
811 lines_of(prop.file)
812 };
813 if crate::english::is_english(prop_file) {
818 return Some(DocMember {
819 declaration: prop_name.clone(),
820 comment: String::new(),
821 place: DocPlace {
822 file: prop_file.to_owned(),
823 line: prop.line,
824 },
825 is_method: matches!(prop.value, PropValue::Method(_)),
826 name: prop_name,
827 stages: Vec::new(),
828 });
829 }
830 let start = start_of(prop_lines, prop.line, &prop_name);
833 Some(DocMember {
834 declaration: declaration(prop_lines, start, prop.line),
835 comment: comment_above(prop_lines, start),
836 place: DocPlace {
837 file: prop_file.to_owned(),
838 line: start,
839 },
840 is_method: matches!(prop.value, PropValue::Method(_)),
841 name: prop_name,
842 stages: Vec::new(),
843 })
844 })
845 .collect();
846 let members = handlers(members, texts);
847 let values: Vec<(String, String)> = def
848 .props
849 .iter()
850 .filter_map(|prop| {
851 let PropValue::Expr(expr) = &prop.value else {
852 return None;
853 };
854 let prop_name =
855 String::from_utf8_lossy(&prog.props.get(prop.prop)?.name).into_owned();
856 Some((prop_name, written_value(expr, &names_by_id)?))
857 })
858 .collect();
859 if unnamed {
860 anonymous.push(DocObject {
861 name: String::new(),
862 is_class: false,
863 superclasses: def
864 .superclasses
865 .iter()
866 .map(|s| String::from_utf8_lossy(s).into_owned())
867 .collect(),
868 comment: written_comment(file, lines, def.line),
869 place,
870 modified_in: Vec::new(),
871 members,
872 from_library,
873 values,
874 });
875 continue;
876 }
877
878 match by_name.get(&name).copied() {
879 Some(at) if def.is_modify => {
882 let object = &mut objects[at];
883 object.modified_in.push(place);
884 for member in members {
885 match object.members.iter().position(|m| m.name == member.name) {
886 Some(i) => object.members[i] = member,
887 None => object.members.push(member),
888 }
889 }
890 for (prop, value) in values {
891 object.values.retain(|(have, _)| *have != prop);
892 object.values.push((prop, value));
893 }
894 }
895 None if def.is_modify => {}
898 _ => {
900 let object = DocObject {
901 name: name.clone(),
902 is_class: def.is_class,
903 superclasses: def
904 .superclasses
905 .iter()
906 .map(|s| String::from_utf8_lossy(s).into_owned())
907 .collect(),
908 comment: written_comment(file, lines, def.line),
909 place,
910 modified_in: Vec::new(),
911 members,
912 from_library,
913 values,
914 };
915 match by_name.get(&name) {
916 Some(&at) => objects[at] = object,
917 None => {
918 by_name.insert(name, objects.len());
919 objects.push(object);
920 }
921 }
922 }
923 }
924 }
925}
926
927fn written_comment(file: &str, lines: &[String], line: u32) -> String {
930 if crate::english::is_english(file) {
931 String::new()
932 } else {
933 comment_above(lines, line)
934 }
935}
936
937fn split_lines(files: &mut dyn SourceFiles, name: &str) -> Vec<String> {
939 files
940 .read(name)
941 .map(|bytes| {
942 String::from_utf8_lossy(&bytes)
943 .replace("\r\n", "\n")
944 .split('\n')
945 .map(str::to_owned)
946 .collect()
947 })
948 .unwrap_or_default()
949}
950
951fn written_value(expr: &crate::ast::Expr, names_by_id: &HashMap<u32, String>) -> Option<String> {
956 use crate::ast::Expr;
957 match expr {
958 Expr::Sym(name) => Some(String::from_utf8_lossy(name).into_owned()),
959 Expr::DStr(bytes) => Some(format!("\"{}\"", String::from_utf8_lossy(bytes))),
960 Expr::Const(c) => written_constant(&c.value, names_by_id),
961 Expr::List(items) => {
962 let items: Option<Vec<String>> = items
963 .iter()
964 .map(|item| written_value(item, names_by_id))
965 .collect();
966 Some(format!("[{}]", items?.join(", ")))
967 }
968 _ => None,
969 }
970}
971
972fn written_constant(
974 value: &crate::ast::Value,
975 names_by_id: &HashMap<u32, String>,
976) -> Option<String> {
977 use crate::ast::Value;
978 match value {
979 Value::Nil => Some("nil".to_owned()),
980 Value::True => Some("true".to_owned()),
981 Value::Int(n) => Some(n.to_string()),
982 Value::SStr(bytes) => Some(format!("'{}'", String::from_utf8_lossy(bytes))),
983 Value::Obj(id) => names_by_id.get(id).filter(|n| !n.is_empty()).cloned(),
984 Value::List(items) => {
985 let items: Option<Vec<String>> = items
986 .iter()
987 .map(|item| written_constant(&item.value, names_by_id))
988 .collect();
989 Some(format!("[{}]", items?.join(", ")))
990 }
991 _ => None,
992 }
993}
994
995const STAGES: [&str; 6] = ["verify", "check", "action", "report", "preCond", "remap"];
998
999fn handler_stage(name: &str) -> Option<(&'static str, &'static str, &str)> {
1002 for stage in STAGES {
1003 let Some(rest) = name.strip_prefix(stage) else {
1004 continue;
1005 };
1006 for (role, mark) in [("dobj", "Dobj"), ("iobj", "Iobj"), ("aobj", "Aobj")] {
1007 if let Some(action) = rest.strip_prefix(mark)
1008 && action.starts_with(|c: char| c.is_ascii_uppercase())
1009 {
1010 return Some((stage, role, action));
1011 }
1012 }
1013 }
1014 None
1015}
1016
1017fn handlers(members: Vec<DocMember>, texts: &HashMap<String, Vec<String>>) -> Vec<DocMember> {
1021 let mut out: Vec<DocMember> = Vec::new();
1022 for member in members {
1023 let Some((stage, role, action)) = handler_stage(&member.name) else {
1024 out.push(member);
1025 continue;
1026 };
1027 let name = format!("{role} {action}");
1028 if let Some(handler) = out.iter_mut().find(|m| m.name == name) {
1029 handler.stages.push(stage.to_owned());
1030 if member.place.line < handler.place.line && member.place.file == handler.place.file {
1031 handler.place.line = member.place.line;
1032 }
1033 continue;
1034 }
1035 out.push(DocMember {
1036 name,
1037 declaration: String::new(),
1038 comment: String::new(),
1039 place: member.place,
1040 is_method: true,
1041 stages: vec![stage.to_owned()],
1042 });
1043 }
1044 for member in out.iter_mut().filter(|m| !m.stages.is_empty()) {
1047 let english = crate::english::is_english(&member.place.file);
1049 let Some(lines) = texts.get(&member.place.file).filter(|_| !english) else {
1050 if member.declaration.is_empty() {
1051 member.declaration = member.name.clone();
1052 }
1053 continue;
1054 };
1055 let (role, action) = member.name.split_once(' ').unwrap_or_default();
1056 let mut at = member.place.line as usize;
1057 while at > 0 {
1058 let line = lines.get(at - 1).map(String::as_str).unwrap_or_default();
1059 let words: Vec<&str> = line.split_whitespace().collect();
1060 if words.len() >= 2 && words[0] == role && words[1] == action {
1061 member.place.line = at as u32;
1062 member.declaration = line.trim().to_owned();
1063 member.comment = comment_above(lines, at as u32);
1064 break;
1065 }
1066 at -= 1;
1067 }
1068 if member.declaration.is_empty() {
1069 member.declaration = member.name.clone();
1070 }
1071 }
1072 out
1073}
1074
1075fn start_of(lines: &[String], end: u32, name: &str) -> u32 {
1080 let mut at = end as usize;
1081 let mut looked = 0;
1082 while at > 0 && looked < 200 {
1083 let line = lines
1084 .get(at - 1)
1085 .map(|l| l.trim_start())
1086 .unwrap_or_default();
1087 if let Some(rest) = line.strip_prefix(name) {
1088 let rest = rest.trim_start();
1089 if rest.is_empty() || rest.starts_with(['=', '(', ':', '{']) {
1090 return at as u32;
1091 }
1092 }
1093 at -= 1;
1094 looked += 1;
1095 }
1096 end
1097}
1098
1099fn body_brace(text: &str) -> Option<usize> {
1101 let mut quote: Option<char> = None;
1102 let mut escaped = false;
1103 for (at, c) in text.char_indices() {
1104 if let Some(q) = quote {
1105 if escaped {
1106 escaped = false;
1107 } else if c == '\\' {
1108 escaped = true;
1109 } else if c == q {
1110 quote = None;
1111 }
1112 continue;
1113 }
1114 match c {
1115 '\'' | '"' => quote = Some(c),
1116 '{' => return Some(at),
1117 _ => {}
1118 }
1119 }
1120 None
1121}
1122
1123fn unfinished(text: &str) -> bool {
1126 let mut depth = 0;
1127 let mut quote: Option<char> = None;
1128 let mut escaped = false;
1129 for c in text.chars() {
1130 if let Some(q) = quote {
1131 if escaped {
1132 escaped = false;
1133 } else if c == '\\' {
1134 escaped = true;
1135 } else if c == q {
1136 quote = None;
1137 }
1138 continue;
1139 }
1140 match c {
1141 '\'' | '"' => quote = Some(c),
1142 '(' => depth += 1,
1143 ')' => depth -= 1,
1144 _ => {}
1145 }
1146 }
1147 depth > 0 || quote.is_some()
1148}
1149
1150fn declaration(lines: &[String], start: u32, end: u32) -> String {
1154 let mut text = String::new();
1155 let mut line = start;
1156 while line <= end.max(start) || (unfinished(&text) && line < start + 40) {
1160 let Some(part) = lines.get((line as usize).wrapping_sub(1)) else {
1161 break;
1162 };
1163 if !text.is_empty() {
1164 text.push(' ');
1165 }
1166 text.push_str(part.trim());
1167 if body_brace(&text).is_some() {
1168 break;
1169 }
1170 line += 1;
1171 }
1172 let text = match body_brace(&text) {
1173 Some(at) if at > 0 => text[..at].trim_end().to_owned(),
1174 _ => text,
1175 };
1176 let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
1177 let text = text.trim_end_matches(';').trim_end().to_owned();
1178 if text.chars().count() > 120 {
1179 text.chars().take(117).collect::<String>() + "..."
1180 } else {
1181 text
1182 }
1183}
1184
1185pub fn comment_above(lines: &[String], line: u32) -> String {
1190 let mut at = line as usize;
1191 let mut blank = 0;
1194 let mut above = || -> Option<&str> {
1195 at = at.checked_sub(1)?;
1196 lines.get(at.checked_sub(1)?).map(String::as_str)
1197 };
1198 let mut text = loop {
1199 let Some(line) = above() else {
1200 return String::new();
1201 };
1202 if line.trim().is_empty() {
1203 blank += 1;
1204 if blank > 1 {
1205 return String::new();
1206 }
1207 continue;
1208 }
1209 break line.trim().to_owned();
1210 };
1211 let mut taken: Vec<String> = Vec::new();
1212 if text.ends_with("*/") {
1213 loop {
1215 let opens = text.contains("/*");
1216 taken.push(text.clone());
1217 if opens {
1218 break;
1219 }
1220 match above() {
1221 Some(line) => text = line.trim().to_owned(),
1222 None => break,
1223 }
1224 }
1225 } else if text.starts_with("//") {
1226 loop {
1227 taken.push(text.clone());
1228 match above() {
1229 Some(line) if line.trim().starts_with("//") => text = line.trim().to_owned(),
1230 _ => break,
1231 }
1232 }
1233 } else {
1234 return String::new();
1235 }
1236 taken.reverse();
1237 clean(&taken)
1238}
1239
1240fn clean(lines: &[String]) -> String {
1243 let mut out: Vec<String> = Vec::new();
1244 for line in lines {
1245 let mut text = line.as_str();
1246 text = text.trim_start_matches("/*").trim_start_matches("//");
1247 text = text.trim_end_matches("*/");
1248 let text = text.trim().trim_start_matches('*').trim();
1249 let is_rule = !text.is_empty()
1250 && text
1251 .chars()
1252 .all(|c| matches!(c, '-' | '=' | '*' | '/' | '~' | '_' | ' '));
1253 if is_rule {
1254 continue;
1255 }
1256 out.push(text.to_owned());
1257 }
1258 let mut paragraphs: Vec<String> = Vec::new();
1260 let mut current = String::new();
1261 for line in out {
1262 if line.is_empty() {
1263 if !current.is_empty() {
1264 paragraphs.push(std::mem::take(&mut current));
1265 }
1266 } else {
1267 if !current.is_empty() {
1268 current.push(' ');
1269 }
1270 current.push_str(&line);
1271 }
1272 }
1273 if !current.is_empty() {
1274 paragraphs.push(current);
1275 }
1276 paragraphs.join("\n\n")
1277}