Skip to main content

hexicon_compiler/
docs.rs

1//! What a program's sources say of themselves, for its reference
2//! documentation: each named class and object, where it is defined and
3//! modified, what it is built on, its properties and methods, and the
4//! comments written above each. `hexicon doc` makes pages of it.
5//!
6//! The sources are read as a build reads them, twice, and nothing is
7//! generated. The lexer leaves comments out, so they are read again
8//! from the source text, above the line each definition starts on.
9
10use 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/// A place in a source file.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct DocPlace {
19    /// The file, as the build names it.
20    pub file: String,
21    /// Its line, counting from 1.
22    pub line: u32,
23}
24
25/// A property or method of a class or object.
26#[derive(Debug, Clone)]
27pub struct DocMember {
28    /// The property's name.
29    pub name: String,
30    /// The line that defines it, as the source has it, without its
31    /// leading space: `isLit = nil`, `makeOn(stat)`.
32    pub declaration: String,
33    /// The comment above it, without its comment marks.
34    pub comment: String,
35    /// Where it is defined.
36    pub place: DocPlace,
37    /// Its value is code.
38    pub is_method: bool,
39    /// It is a handler, `dobj Take { ... }`: these are the stages it
40    /// gives (`verify`, `action`), and its name is the handler's
41    /// (`dobj Take`). Empty for any other member.
42    pub stages: Vec<String>,
43}
44
45/// A class or a named object.
46#[derive(Debug, Clone)]
47pub struct DocObject {
48    /// Its name in the source.
49    pub name: String,
50    /// It is a class, not an object.
51    pub is_class: bool,
52    /// What it is built on, first first.
53    pub superclasses: Vec<String>,
54    /// Where it is defined.
55    pub place: DocPlace,
56    /// The comment above its definition, without its comment marks.
57    pub comment: String,
58    /// Where `modify` adds to it.
59    pub modified_in: Vec<DocPlace>,
60    /// Its own properties and methods, those `modify` adds among them,
61    /// in the order they are first defined.
62    pub members: Vec<DocMember>,
63    /// It is defined in a library's source, not the game's.
64    pub from_library: bool,
65    /// The properties it gives a value written out whole, by name, each
66    /// value as the source would write it: a string (`'Grab the
67    /// satchel'`), an object's name, `nil`, `true`, or a number. Those its
68    /// template gives are among them; `location`, for one written with
69    /// `+`, is the name of what it is in.
70    pub values: Vec<(String, String)>,
71}
72
73impl DocObject {
74    /// The value it gives a property, as the source would write it.
75    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/// A function.
84#[derive(Debug, Clone)]
85pub struct DocFunction {
86    /// Its name.
87    pub name: String,
88    /// The line that declares it: its name and parameters.
89    pub declaration: String,
90    /// The comment above it, without its comment marks.
91    pub comment: String,
92    /// Where it is defined.
93    pub place: DocPlace,
94    /// It is defined in a library's source, not the game's.
95    pub from_library: bool,
96}
97
98/// A rule of the grammar for an action: `verb Toll 'toll' singleDobj`.
99#[derive(Debug, Clone)]
100pub struct DocVerb {
101    /// The action it is for: its own name, or the one after `for`.
102    pub action: String,
103    /// What the player types, as the rule says it, up to its colon.
104    pub words: String,
105    /// Where it is defined.
106    pub place: DocPlace,
107}
108
109/// A message a game can give text of its own for: the id of a
110/// `msgText()` or a `showMsg()`, and its text.
111#[derive(Debug, Clone)]
112pub struct DocMessage {
113    /// Its id: `cannot take`.
114    pub id: String,
115    /// Its text, as the source has it, without its quotes.
116    pub text: String,
117    /// Where it is.
118    pub place: DocPlace,
119}
120
121/// A macro: `#define TWICE(x) ((x) * 2)`.
122#[derive(Debug, Clone)]
123pub struct DocMacro {
124    /// Its name.
125    pub name: String,
126    /// Its parameters, in their parentheses, if it has any: `(x)`.
127    pub params: String,
128    /// What it stands for, its lines joined.
129    pub expansion: String,
130    /// The comment above it, without its comment marks.
131    pub comment: String,
132    /// Where it is defined.
133    pub place: DocPlace,
134}
135
136/// A template, which says what values written without names stand for:
137/// `Room template 'roomTitle' "desc"?;`.
138#[derive(Debug, Clone)]
139pub struct DocTemplate {
140    /// The class it is for, or `object` for any.
141    pub class: String,
142    /// What it says, as the source has it: the class, `template`, and its
143    /// items.
144    pub text: String,
145    /// Where it is defined.
146    pub place: DocPlace,
147}
148
149/// The values of an enumeration, as one `enum` declares them.
150#[derive(Debug, Clone)]
151pub struct DocEnum {
152    /// The values, in order.
153    pub names: Vec<String>,
154    /// It declares kinds of token (`enum token`).
155    pub is_token: bool,
156    /// The comment above it, without its comment marks.
157    pub comment: String,
158    /// Where it is declared.
159    pub place: DocPlace,
160}
161
162/// A source file, and its text.
163#[derive(Debug, Clone)]
164pub struct DocFile {
165    /// The file, as the build names it.
166    pub name: String,
167    /// Its lines.
168    pub lines: Vec<String>,
169    /// It is a library's, not the game's.
170    pub from_library: bool,
171}
172
173/// A name used in code, in a source of the game's own: a class's, an
174/// object's, a property's, a function's, or anything else that is not a
175/// local's. Each place a name is written is one, its definition's too.
176#[derive(Debug, Clone, PartialEq, Eq)]
177pub struct DocUse {
178    /// The name.
179    pub name: String,
180    /// Where it is.
181    pub place: DocPlace,
182    /// The bytes of its line it is, from the first to past the last.
183    pub columns: (u32, u32),
184}
185
186/// What [`document`] found.
187#[derive(Debug, Default)]
188pub struct Documented {
189    /// Where the names are used in the game's own sources, in the order
190    /// they are read; not in an English source, whose places are not in
191    /// its own words.
192    pub uses: Vec<DocUse>,
193    /// The classes and named objects, in the order they are defined.
194    pub objects: Vec<DocObject>,
195    /// The objects with no name (`+ Choice 'Grab the root' ->ledge;`),
196    /// in the order they are defined, each with an empty name.
197    pub anonymous: Vec<DocObject>,
198    /// The functions, in the order they are defined.
199    pub functions: Vec<DocFunction>,
200    /// The rules of the actions' grammar, in the order they are defined.
201    pub verbs: Vec<DocVerb>,
202    /// The messages, in the order they are defined.
203    pub messages: Vec<DocMessage>,
204    /// The macros, in the order they are defined.
205    pub macros: Vec<DocMacro>,
206    /// The templates, in the order they are defined.
207    pub templates: Vec<DocTemplate>,
208    /// The enumerations, in the order they are declared.
209    pub enums: Vec<DocEnum>,
210    /// The source files read, in the order they were first read.
211    pub files: Vec<DocFile>,
212    /// What stopped the reading, if anything did.
213    pub diagnostics: Vec<Diagnostic>,
214}
215
216/// Read a program's sources, as a build would, and say what they define.
217pub 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    // The first reading: what each source makes known.
227    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    // What every source knows on its second reading, made once.
249    let known = crate::parse::Program::knowing(merge_exports(exports));
250
251    // The second reading, knowing what all of them define.
252    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/// What a second reading of a program's sources finds, gathered as each
279/// source is read: by [`document`], and by a build that documents the
280/// program as it compiles it ([`crate::compile_and_document`]).
281#[derive(Default)]
282pub(crate) struct Reading {
283    /// The files' lines, as they are read.
284    texts: HashMap<String, Vec<String>>,
285    /// Where each named class and object is among those found.
286    by_name: HashMap<String, usize>,
287    /// The files, in the order they were first read, each with whether
288    /// it is a library's.
289    order: Vec<(String, bool)>,
290    documented: Documented,
291}
292
293impl Reading {
294    /// Gather what a source defines, from its program as its second
295    /// reading parsed it, and the names of the files it read.
296    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        // A name read twice (the parser read it, put it back, and read
309        // it again) is used once.
310        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    /// What was found before these problems stopped the reading.
350    pub(crate) fn stopped(mut self, problems: Vec<Diagnostic>) -> Documented {
351        self.documented.diagnostics.extend(problems);
352        self.documented
353    }
354
355    /// What was found, all the sources read: with what is found in their
356    /// files' text, and the files.
357    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            // Files that are only part of the build, with nothing in them
370            // the game or a library wrote, are left out.
371            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
389/// A file's lines, or none if it cannot be read.
390fn 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
403/// Add the functions one source defines to `functions`.
404fn 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        // The functions the compiler makes have names no source writes,
424        // and a name that starts with `_` is the system library's own.
425        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        // A function defined again (`replace`, `modify`) is the later one.
445        match at {
446            Some(at) => functions[at] = function,
447            None => functions.push(function),
448        }
449    }
450}
451
452/// The rules of the actions' grammar in a file: each a line that starts
453/// with `verb`, `modify verb`, or `replace verb`, to the colon that ends
454/// what the player types.
455pub(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        // The rule's name, and what it is for.
465        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        // On to the colon that ends the words, outside a string.
482        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        // A rule's badness, `[badness 500]`, is not what the player types.
501        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
519/// The macros a file defines: each `#define`, its name, its parameters,
520/// and what it stands for, on to the lines a backslash continues it onto.
521pub(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        // Parameters touch the name: `TWICE(x)`.
535        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
569/// The templates a file defines: each line that starts with a class's
570/// name (or `object`) and `template`, on to the semicolon that ends it.
571pub(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
598/// The enumerations a file declares: each line that starts `enum`, and
599/// its values, to the semicolon.
600pub(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
637/// Where a grammar rule's words end: its first colon outside a string.
638fn 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
661/// The messages in a file: each `msgText(id, ...)` and `showMsg(id,
662/// ...)`, its id, and its text, read on while its string is open.
663pub(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                // The marker as a name of its own, not the end of another.
675                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                // An id is words, not code: no quotes, no calls.
684                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                // The text can start on the next line, and run on while
690                // its string is open.
691                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                // A one-word "id" with no text written in place is a
703                // variable, in the code that shows messages, not an id.
704                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
720/// A message's text: what its first string says, without its quotes.
721fn 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
743/// Add what one source defines to `objects`.
744fn 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    // Each object's name, by its number, for a value that is an object.
757    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    // Each file's lines are read once, and lent to what needs them.
763    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        // An object the compiler made for a source file is no author's.
780        if prog.src_group_defs.contains(&index) {
781            continue;
782        }
783        let name = String::from_utf8_lossy(&prog.objs[sym].name).into_owned();
784        // An anonymous object (the compiler calls each `.anon`), kept
785        // apart; and, left out, those the compiler made, and the
786        // grammar's productions and the classes of their rules
787        // (`nounList(terminal)`), which the actions' rules stand for.
788        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                // An English source's lines here are those of the Hexicon
814                // it becomes, which its places are not in: its sentence
815                // is where the property is, and there is no line of it
816                // to quote, so its name stands for it.
817                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                // The line the compiler notes is where the value ends; the
831                // property is defined where its name starts it.
832                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            // A modify, of what is defined before it: its members go to
880            // the object it modifies.
881            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            // A modify of what this program has no definition of (a
896            // built-in class's): nothing to say yet.
897            None if def.is_modify => {}
898            // A definition, or a replace of one: this one is the object.
899            _ => {
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
927/// The comment above a line of a file: none in an English source, whose
928/// lines `collect` has are those of the Hexicon it becomes, not its own.
929fn 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
937/// A file's lines, as `collect` reads them; none if it cannot be read.
938fn 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
951/// A property's value as the source would write it, if it is written out
952/// whole: a string, single-quoted or double-quoted (which is what a
953/// property that prints says), an object (by its name, or its number's),
954/// `nil`, `true`, a whole number, or a list of those (`[a, b]`).
955fn 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
972/// A constant as the source would write it, as [`written_value`] says.
973fn 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
995/// The stages of a handler, which the compiler makes properties of
996/// their own: `verifyDobjTake` is `dobj Take`'s `verify()`.
997const STAGES: [&str; 6] = ["verify", "check", "action", "report", "preCond", "remap"];
998
999/// A property that is a stage of a handler: the stage, the role
1000/// (`dobj`), and the action.
1001fn 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
1017/// The members, with the stages of each handler gathered into one,
1018/// named for the handler (`dobj Take`), declared and commented where
1019/// the handler is written, as `texts` has the files' lines.
1020fn 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    // Each handler is declared where its first line is: the line, at or
1045    // above its first stage, that names it.
1046    for member in out.iter_mut().filter(|m| !m.stages.is_empty()) {
1047        // (An English source's lines here are not its own: see `collect`.)
1048        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
1075/// The line a property's definition starts on: the line at or above
1076/// `end` that starts with its name, followed by what can follow a
1077/// property's name (`=`, `(`, `:`, or nothing). `end` itself if none is
1078/// found within a long property's length.
1079fn 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
1099/// Where a method's body starts: the first brace outside a string.
1100fn 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
1123/// Whether a piece of code stops short: a parenthesis or a string it
1124/// opens is still open.
1125fn 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
1150/// What defines a property, as a line: from where it starts to where its
1151/// value ends, its lines joined, without a method's body, and cut short
1152/// if it is long.
1153fn declaration(lines: &[String], start: u32, end: u32) -> String {
1154    let mut text = String::new();
1155    let mut line = start;
1156    // To where the value ends, and on while a parenthesis or a string it
1157    // opens is still open: a message's text runs on after the line the
1158    // compiler notes.
1159    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
1185/// The comment written just above a line, if there is one: a block
1186/// comment ending there, or `//` lines, with at most one blank line
1187/// between it and the line. Its comment marks are taken off, and so are
1188/// lines that are only rules (`----`, `****`).
1189pub fn comment_above(lines: &[String], line: u32) -> String {
1190    let mut at = line as usize;
1191    // `at` counts from 1, so the line above is `at - 1`, at index
1192    // `at - 2`.
1193    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        // A block comment: up to the line that opens it.
1214        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
1240/// A comment's lines without their marks: paragraphs kept apart by a
1241/// blank line.
1242fn 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    // Lines into paragraphs.
1259    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}