hexicon-compiler 0.1.0

The Hexicon compiler: source text to a program image
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
//! What a program's sources say of themselves, for its reference
//! documentation: each named class and object, where it is defined and
//! modified, what it is built on, its properties and methods, and the
//! comments written above each. `hexicon doc` makes pages of it.
//!
//! The sources are read as a build reads them, twice, and nothing is
//! generated. The lexer leaves comments out, so they are read again
//! from the source text, above the line each definition starts on.

use std::collections::HashMap;

use crate::compile::{CompileOptions, start};
use crate::parse::{Exports, Parser, Program, PropValue, merge_exports};
use crate::pp::{Diagnostic, Severity, SourceFiles};

/// A place in a source file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DocPlace {
    /// The file, as the build names it.
    pub file: String,
    /// Its line, counting from 1.
    pub line: u32,
}

/// A property or method of a class or object.
#[derive(Debug, Clone)]
pub struct DocMember {
    /// The property's name.
    pub name: String,
    /// The line that defines it, as the source has it, without its
    /// leading space: `isLit = nil`, `makeOn(stat)`.
    pub declaration: String,
    /// The comment above it, without its comment marks.
    pub comment: String,
    /// Where it is defined.
    pub place: DocPlace,
    /// Its value is code.
    pub is_method: bool,
    /// It is a handler, `dobj Take { ... }`: these are the stages it
    /// gives (`verify`, `action`), and its name is the handler's
    /// (`dobj Take`). Empty for any other member.
    pub stages: Vec<String>,
}

/// A class or a named object.
#[derive(Debug, Clone)]
pub struct DocObject {
    /// Its name in the source.
    pub name: String,
    /// It is a class, not an object.
    pub is_class: bool,
    /// What it is built on, first first.
    pub superclasses: Vec<String>,
    /// Where it is defined.
    pub place: DocPlace,
    /// The comment above its definition, without its comment marks.
    pub comment: String,
    /// Where `modify` adds to it.
    pub modified_in: Vec<DocPlace>,
    /// Its own properties and methods, those `modify` adds among them,
    /// in the order they are first defined.
    pub members: Vec<DocMember>,
    /// It is defined in a library's source, not the game's.
    pub from_library: bool,
    /// The properties it gives a value written out whole, by name, each
    /// value as the source would write it: a string (`'Grab the
    /// satchel'`), an object's name, `nil`, `true`, or a number. Those its
    /// template gives are among them; `location`, for one written with
    /// `+`, is the name of what it is in.
    pub values: Vec<(String, String)>,
}

impl DocObject {
    /// The value it gives a property, as the source would write it.
    pub fn value(&self, prop: &str) -> Option<&str> {
        self.values
            .iter()
            .find(|(name, _)| name == prop)
            .map(|(_, value)| value.as_str())
    }
}

/// A function.
#[derive(Debug, Clone)]
pub struct DocFunction {
    /// Its name.
    pub name: String,
    /// The line that declares it: its name and parameters.
    pub declaration: String,
    /// The comment above it, without its comment marks.
    pub comment: String,
    /// Where it is defined.
    pub place: DocPlace,
    /// It is defined in a library's source, not the game's.
    pub from_library: bool,
}

/// A rule of the grammar for an action: `verb Toll 'toll' singleDobj`.
#[derive(Debug, Clone)]
pub struct DocVerb {
    /// The action it is for: its own name, or the one after `for`.
    pub action: String,
    /// What the player types, as the rule says it, up to its colon.
    pub words: String,
    /// Where it is defined.
    pub place: DocPlace,
}

/// A message a game can give text of its own for: the id of a
/// `msgText()` or a `showMsg()`, and its text.
#[derive(Debug, Clone)]
pub struct DocMessage {
    /// Its id: `cannot take`.
    pub id: String,
    /// Its text, as the source has it, without its quotes.
    pub text: String,
    /// Where it is.
    pub place: DocPlace,
}

/// A macro: `#define TWICE(x) ((x) * 2)`.
#[derive(Debug, Clone)]
pub struct DocMacro {
    /// Its name.
    pub name: String,
    /// Its parameters, in their parentheses, if it has any: `(x)`.
    pub params: String,
    /// What it stands for, its lines joined.
    pub expansion: String,
    /// The comment above it, without its comment marks.
    pub comment: String,
    /// Where it is defined.
    pub place: DocPlace,
}

/// A template, which says what values written without names stand for:
/// `Room template 'roomTitle' "desc"?;`.
#[derive(Debug, Clone)]
pub struct DocTemplate {
    /// The class it is for, or `object` for any.
    pub class: String,
    /// What it says, as the source has it: the class, `template`, and its
    /// items.
    pub text: String,
    /// Where it is defined.
    pub place: DocPlace,
}

/// The values of an enumeration, as one `enum` declares them.
#[derive(Debug, Clone)]
pub struct DocEnum {
    /// The values, in order.
    pub names: Vec<String>,
    /// It declares kinds of token (`enum token`).
    pub is_token: bool,
    /// The comment above it, without its comment marks.
    pub comment: String,
    /// Where it is declared.
    pub place: DocPlace,
}

/// A source file, and its text.
#[derive(Debug, Clone)]
pub struct DocFile {
    /// The file, as the build names it.
    pub name: String,
    /// Its lines.
    pub lines: Vec<String>,
    /// It is a library's, not the game's.
    pub from_library: bool,
}

/// A name used in code, in a source of the game's own: a class's, an
/// object's, a property's, a function's, or anything else that is not a
/// local's. Each place a name is written is one, its definition's too.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DocUse {
    /// The name.
    pub name: String,
    /// Where it is.
    pub place: DocPlace,
    /// The bytes of its line it is, from the first to past the last.
    pub columns: (u32, u32),
}

/// What [`document`] found.
#[derive(Debug, Default)]
pub struct Documented {
    /// Where the names are used in the game's own sources, in the order
    /// they are read; not in an English source, whose places are not in
    /// its own words.
    pub uses: Vec<DocUse>,
    /// The classes and named objects, in the order they are defined.
    pub objects: Vec<DocObject>,
    /// The objects with no name (`+ Choice 'Grab the root' ->ledge;`),
    /// in the order they are defined, each with an empty name.
    pub anonymous: Vec<DocObject>,
    /// The functions, in the order they are defined.
    pub functions: Vec<DocFunction>,
    /// The rules of the actions' grammar, in the order they are defined.
    pub verbs: Vec<DocVerb>,
    /// The messages, in the order they are defined.
    pub messages: Vec<DocMessage>,
    /// The macros, in the order they are defined.
    pub macros: Vec<DocMacro>,
    /// The templates, in the order they are defined.
    pub templates: Vec<DocTemplate>,
    /// The enumerations, in the order they are declared.
    pub enums: Vec<DocEnum>,
    /// The source files read, in the order they were first read.
    pub files: Vec<DocFile>,
    /// What stopped the reading, if anything did.
    pub diagnostics: Vec<Diagnostic>,
}

/// Read a program's sources, as a build would, and say what they define.
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();

    // The first reading: what each source makes known.
    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());
    }
    // What every source knows on its second reading, made once.
    let known = crate::parse::Program::knowing(merge_exports(exports));

    // The second reading, knowing what all of them define.
    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)
}

/// What a second reading of a program's sources finds, gathered as each
/// source is read: by [`document`], and by a build that documents the
/// program as it compiles it ([`crate::compile_and_document`]).
#[derive(Default)]
pub(crate) struct Reading {
    /// The files' lines, as they are read.
    texts: HashMap<String, Vec<String>>,
    /// Where each named class and object is among those found.
    by_name: HashMap<String, usize>,
    /// The files, in the order they were first read, each with whether
    /// it is a library's.
    order: Vec<(String, bool)>,
    documented: Documented,
}

impl Reading {
    /// Gather what a source defines, from its program as its second
    /// reading parsed it, and the names of the files it read.
    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));
            }
        }
        // A name read twice (the parser read it, put it back, and read
        // it again) is used once.
        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,
        );
    }

    /// What was found before these problems stopped the reading.
    pub(crate) fn stopped(mut self, problems: Vec<Diagnostic>) -> Documented {
        self.documented.diagnostics.extend(problems);
        self.documented
    }

    /// What was found, all the sources read: with what is found in their
    /// files' text, and the files.
    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),
            };
            // Files that are only part of the build, with nothing in them
            // the game or a library wrote, are left out.
            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
    }
}

/// A file's lines, or none if it cannot be read.
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()
}

/// Add the functions one source defines to `functions`.
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();
        // The functions the compiler makes have names no source writes,
        // and a name that starts with `_` is the system library's own.
        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,
        };
        // A function defined again (`replace`, `modify`) is the later one.
        match at {
            Some(at) => functions[at] = function,
            None => functions.push(function),
        }
    }
}

/// The rules of the actions' grammar in a file: each a line that starts
/// with `verb`, `modify verb`, or `replace verb`, to the colon that ends
/// what the player types.
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;
        };
        // The rule's name, and what it is for.
        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();
        }
        // On to the colon that ends the words, outside a string.
        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,
            }
        }
        // A rule's badness, `[badness 500]`, is not what the player types.
        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,
            },
        });
    }
}

/// The macros a file defines: each `#define`, its name, its parameters,
/// and what it stands for, on to the lines a backslash continues it onto.
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;
        }
        // Parameters touch the name: `TWICE(x)`.
        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,
            },
        });
    }
}

/// The templates a file defines: each line that starts with a class's
/// name (or `object`) and `template`, on to the semicolon that ends it.
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,
            },
        });
    }
}

/// The enumerations a file declares: each line that starts `enum`, and
/// its values, to the semicolon.
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,
            },
        });
    }
}

/// Where a grammar rule's words end: its first colon outside a string.
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
}

/// The messages in a file: each `msgText(id, ...)` and `showMsg(id,
/// ...)`, its id, and its text, read on while its string is open.
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;
                // The marker as a name of its own, not the end of another.
                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();
                // An id is words, not code: no quotes, no calls.
                if id.is_empty() || id.contains(['\'', '"', '(', ')', '.']) {
                    continue;
                }
                let mut text = line[start + comma + 1..].trim().to_owned();
                let mut next = index + 1;
                // The text can start on the next line, and run on while
                // its string is open.
                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);
                // A one-word "id" with no text written in place is a
                // variable, in the code that shows messages, not an id.
                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,
                    },
                });
            }
        }
    }
}

/// A message's text: what its first string says, without its quotes.
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(" ")
}

/// Add what one source defines to `objects`.
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;
    // Each object's name, by its number, for a value that is an object.
    let names_by_id: HashMap<u32, String> = prog
        .objs
        .iter()
        .map(|o| (o.id, String::from_utf8_lossy(&o.name).into_owned()))
        .collect();
    // Each file's lines are read once, and lent to what needs them.
    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;
        };
        // An object the compiler made for a source file is no author's.
        if prog.src_group_defs.contains(&index) {
            continue;
        }
        let name = String::from_utf8_lossy(&prog.objs[sym].name).into_owned();
        // An anonymous object (the compiler calls each `.anon`), kept
        // apart; and, left out, those the compiler made, and the
        // grammar's productions and the classes of their rules
        // (`nounList(terminal)`), which the actions' rules stand for.
        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)
                };
                // An English source's lines here are those of the Hexicon
                // it becomes, which its places are not in: its sentence
                // is where the property is, and there is no line of it
                // to quote, so its name stands for it.
                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(),
                    });
                }
                // The line the compiler notes is where the value ends; the
                // property is defined where its name starts it.
                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() {
            // A modify, of what is defined before it: its members go to
            // the object it modifies.
            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));
                }
            }
            // A modify of what this program has no definition of (a
            // built-in class's): nothing to say yet.
            None if def.is_modify => {}
            // A definition, or a replace of one: this one is the object.
            _ => {
                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);
                    }
                }
            }
        }
    }
}

/// The comment above a line of a file: none in an English source, whose
/// lines `collect` has are those of the Hexicon it becomes, not its own.
fn written_comment(file: &str, lines: &[String], line: u32) -> String {
    if crate::english::is_english(file) {
        String::new()
    } else {
        comment_above(lines, line)
    }
}

/// A file's lines, as `collect` reads them; none if it cannot be read.
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()
}

/// A property's value as the source would write it, if it is written out
/// whole: a string, single-quoted or double-quoted (which is what a
/// property that prints says), an object (by its name, or its number's),
/// `nil`, `true`, a whole number, or a list of those (`[a, b]`).
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,
    }
}

/// A constant as the source would write it, as [`written_value`] says.
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,
    }
}

/// The stages of a handler, which the compiler makes properties of
/// their own: `verifyDobjTake` is `dobj Take`'s `verify()`.
const STAGES: [&str; 6] = ["verify", "check", "action", "report", "preCond", "remap"];

/// A property that is a stage of a handler: the stage, the role
/// (`dobj`), and the action.
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
}

/// The members, with the stages of each handler gathered into one,
/// named for the handler (`dobj Take`), declared and commented where
/// the handler is written, as `texts` has the files' lines.
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()],
        });
    }
    // Each handler is declared where its first line is: the line, at or
    // above its first stage, that names it.
    for member in out.iter_mut().filter(|m| !m.stages.is_empty()) {
        // (An English source's lines here are not its own: see `collect`.)
        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
}

/// The line a property's definition starts on: the line at or above
/// `end` that starts with its name, followed by what can follow a
/// property's name (`=`, `(`, `:`, or nothing). `end` itself if none is
/// found within a long property's length.
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
}

/// Where a method's body starts: the first brace outside a string.
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
}

/// Whether a piece of code stops short: a parenthesis or a string it
/// opens is still open.
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()
}

/// What defines a property, as a line: from where it starts to where its
/// value ends, its lines joined, without a method's body, and cut short
/// if it is long.
fn declaration(lines: &[String], start: u32, end: u32) -> String {
    let mut text = String::new();
    let mut line = start;
    // To where the value ends, and on while a parenthesis or a string it
    // opens is still open: a message's text runs on after the line the
    // compiler notes.
    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
    }
}

/// The comment written just above a line, if there is one: a block
/// comment ending there, or `//` lines, with at most one blank line
/// between it and the line. Its comment marks are taken off, and so are
/// lines that are only rules (`----`, `****`).
pub fn comment_above(lines: &[String], line: u32) -> String {
    let mut at = line as usize;
    // `at` counts from 1, so the line above is `at - 1`, at index
    // `at - 2`.
    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("*/") {
        // A block comment: up to the line that opens it.
        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)
}

/// A comment's lines without their marks: paragraphs kept apart by a
/// blank line.
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());
    }
    // Lines into paragraphs.
    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")
}