use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use hexicon_compiler::pp::SourceFiles;
use hexicon_compiler::{
DocObject, DocPlace, Documented, Project, ProjectError, document, read_project,
};
use crate::preprocess::DiskFiles;
const STYLE: &str = include_str!("doc.css");
const SEARCH: &str = include_str!("doc-search.js");
pub(crate) fn run(args: &[&str], usage: &str) -> ExitCode {
let mut project_args: Vec<String> = Vec::new();
let mut out: Option<&str> = None;
let mut library: Option<&str> = None;
let mut defines: Vec<(String, String)> = Vec::new();
let mut manifest_named = false;
let mut rest = args;
while let Some((first, tail)) = rest.split_first() {
match (*first, tail) {
("-f" | "--library-path", [value, tail @ ..]) => {
manifest_named |= *first == "-f";
project_args.push((*first).to_owned());
project_args.push((*value).to_owned());
rest = tail;
}
("-o", [dir, tail @ ..]) => {
out = Some(dir);
rest = tail;
}
("--library", [name, tail @ ..]) => {
library = Some(name);
rest = tail;
}
("-D", [define, tail @ ..]) => {
let (name, value) = define.split_once('=').unwrap_or((define, "1"));
defines.push((name.to_owned(), value.to_owned()));
rest = tail;
}
_ => {
eprint!("{usage}");
return ExitCode::from(2);
}
}
}
if library.is_some() && manifest_named {
eprintln!(
"hexicon doc: a reference is of a game (-f) or of a library (--library), not both"
);
eprint!("{usage}");
return ExitCode::from(2);
}
let out = PathBuf::from(out.unwrap_or("reference"));
let (title, documented, game) = match library {
Some(name) => match library_reference(name, &project_args, &defines, usage) {
Ok((title, documented)) => (title, documented, false),
Err(code) => return code,
},
None => {
for (name, value) in &defines {
project_args.push("-D".to_owned());
project_args.push(format!("{name}={value}"));
}
let project = match read(&mut DiskFiles, &project_args, usage) {
Ok(project) => project,
Err(code) => return code,
};
let sources: Vec<&str> = project.sources.iter().map(String::as_str).collect();
let documented = document(&mut DiskFiles, &sources, &project.options);
(project_title(&project_args), documented, true)
}
};
if !documented.diagnostics.is_empty() {
for d in &documented.diagnostics {
eprintln!("{}({}): {}", d.file, d.line, d.message);
}
eprintln!("hexicon doc: the sources could not be read");
return ExitCode::from(2);
}
match write_pages(&out, &title, &documented, game) {
Ok(count) => {
println!("Wrote the reference, {count} pages, in {}.", out.display());
ExitCode::SUCCESS
}
Err(error) => {
eprintln!("hexicon doc: {}: {error}", out.display());
ExitCode::FAILURE
}
}
}
fn read(
files: &mut dyn SourceFiles,
project_args: &[String],
usage: &str,
) -> Result<Project, ExitCode> {
read_project(files, project_args, &crate::build::default_paths()).map_err(|e| said(e, usage))
}
pub(crate) fn said(error: ProjectError, usage: &str) -> ExitCode {
match error {
ProjectError::Usage(problem) => {
if !problem.is_empty() {
eprintln!("hexicon: {problem}");
}
eprint!("{usage}");
ExitCode::from(2)
}
ProjectError::Failed(lines) => {
for line in lines {
eprintln!("{line}");
}
ExitCode::FAILURE
}
}
}
const LIBRARY_DOC: &str = "<hexicon doc>";
const LIBRARY_DOC_SOURCE: &str = "<hexicon doc>/library.hxn";
fn library_reference(
name: &str,
project_args: &[String],
defines: &[(String, String)],
usage: &str,
) -> Result<(String, Documented), ExitCode> {
let mut defines = defines.to_vec();
if !defines.iter().any(|(n, _)| n == "LANGUAGE") {
defines.push(("LANGUAGE".to_owned(), "english".to_owned()));
}
let project = read_library(name, &[], project_args, &defines, usage)?;
let Some(manifest) = project.libraries.first() else {
eprintln!("hexicon doc: no library \"{name}\" was found");
return Err(ExitCode::FAILURE);
};
let folder = manifest
.rfind(['/', '\\'])
.map_or(String::new(), |at| manifest[..at].to_owned());
let extensions = extensions_of(&folder);
let mut project = read_library(name, &extensions, project_args, &defines, usage)?;
if project
.sources
.last()
.map(|s| s.replace('\\', "/"))
.as_deref()
== Some(LIBRARY_DOC_SOURCE)
{
project.sources.pop();
project.options.module_names.pop();
project.options.from_library.pop();
}
let title = read_file(manifest)
.and_then(|text| manifest_name(&text))
.unwrap_or_else(|| name.to_owned());
let sources: Vec<&str> = project.sources.iter().map(String::as_str).collect();
let documented = document(&mut DiskFiles, &sources, &project.options);
Ok((title, documented))
}
fn read_library(
name: &str,
extensions: &[String],
project_args: &[String],
defines: &[(String, String)],
usage: &str,
) -> Result<Project, ExitCode> {
let toml = |s: &str| format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""));
let include: Vec<String> = extensions.iter().map(|e| toml(e)).collect();
let mut manifest = format!(
"[game]\nsources = [\"library\"]\nlibraries = [{{ name = {}, include = [{}] }}]\n\n[defines]\n",
toml(name),
include.join(", ")
);
for (name, value) in defines {
let _ = writeln!(manifest, "{name} = {}", toml(value));
}
let mut files = WithManifest {
manifest: manifest.into_bytes(),
};
let mut args = project_args.to_vec();
args.push("-f".to_owned());
args.push(format!("{LIBRARY_DOC}/hexicon.toml"));
match read_project(&mut files, &args, &crate::build::default_paths()) {
Ok(project) => Ok(project),
Err(ProjectError::Failed(lines)) if lines.iter().any(|l| l.contains(LIBRARY_DOC)) => {
eprintln!(
"hexicon doc: there is no library \"{name}\": a library is looked for along \
--library-path and HEXICON_LIB, and then among those built in"
);
Err(ExitCode::FAILURE)
}
Err(error) => Err(said(error, usage)),
}
}
struct WithManifest {
manifest: Vec<u8>,
}
impl SourceFiles for WithManifest {
fn read(&mut self, name: &str) -> Option<Vec<u8>> {
match name.replace('\\', "/").as_str() {
n if n == format!("{LIBRARY_DOC}/hexicon.toml") => Some(self.manifest.clone()),
n if n == LIBRARY_DOC_SOURCE => Some(Vec::new()),
_ => DiskFiles.read(name),
}
}
fn exists(&mut self, name: &str) -> bool {
let n = name.replace('\\', "/");
n == format!("{LIBRARY_DOC}/hexicon.toml")
|| n == LIBRARY_DOC_SOURCE
|| DiskFiles.exists(name)
}
fn decode(&mut self, charset: &str, bytes: &[u8]) -> Option<Vec<u8>> {
DiskFiles.decode(charset, bytes)
}
}
fn extensions_of(folder: &str) -> Vec<String> {
let dir = format!("{folder}/extensions");
let paths: Vec<String> = if folder.starts_with(hexicon_compiler::builtin::ROOT) {
hexicon_compiler::builtin::files_in(&dir)
} else {
std::fs::read_dir(&dir)
.map(|entries| {
entries
.filter_map(Result::ok)
.map(|e| e.path().to_string_lossy().into_owned())
.collect()
})
.unwrap_or_default()
};
let mut names: Vec<String> = paths
.iter()
.filter_map(|path| {
let file = path.rsplit(['/', '\\']).next()?;
if let Some(stem) = file.strip_suffix(".hxn") {
Some(format!("extensions/{stem}"))
} else {
file.ends_with(".t").then(|| format!("extensions/{file}"))
}
})
.collect();
names.sort();
names
}
fn read_file(path: &str) -> Option<String> {
let bytes = match hexicon_compiler::builtin::file(path) {
Some(bytes) => bytes.to_vec(),
None => std::fs::read(path).ok()?,
};
String::from_utf8(bytes).ok()
}
fn manifest_name(text: &str) -> Option<String> {
text.lines()
.find_map(|line| line.trim().strip_prefix("name").map(str::trim))
.and_then(|rest| rest.strip_prefix('='))
.map(|value| value.trim().trim_matches('"').to_owned())
}
fn project_title(project_args: &[String]) -> String {
let manifest = project_args
.iter()
.position(|a| a == "-f")
.and_then(|at| project_args.get(at + 1))
.map_or_else(|| PathBuf::from("hexicon.toml"), PathBuf::from);
let manifest = if manifest.is_dir() {
manifest.join("hexicon.toml")
} else {
manifest
};
std::fs::read_to_string(manifest)
.ok()
.and_then(|text| manifest_name(&text))
.unwrap_or_else(|| "A game".to_owned())
}
fn write_pages(
out: &Path,
title: &str,
documented: &Documented,
game: bool,
) -> std::io::Result<usize> {
std::fs::create_dir_all(out.join("objects"))?;
std::fs::create_dir_all(out.join("files"))?;
std::fs::write(out.join("reference.css"), STYLE)?;
std::fs::write(out.join("search.js"), SEARCH)?;
std::fs::write(
out.join("search-index.js"),
Site::new(documented, game).search_index(),
)?;
let site = Site::new(documented, game);
let mut count = 0;
for (name, page) in [
("index.html", site.index(title)),
("files.html", site.files_index(title)),
("extensions.html", site.extensions_index(title)),
("functions.html", site.functions_index(title)),
("actions.html", site.actions_index(title)),
("messages.html", site.messages_index(title)),
("macros.html", site.macros_index(title)),
("search.html", site.search_page(title)),
] {
std::fs::write(out.join(name), page)?;
count += 1;
}
if !site.moments.is_empty() {
std::fs::write(out.join("choices.html"), site.choices_index(title))?;
count += 1;
}
for object in &documented.objects {
let page = site.object_page(title, object);
std::fs::write(out.join("objects").join(&site.pages[&object.name]), page)?;
count += 1;
}
for file in &documented.files {
let page = site.file_page(title, file);
std::fs::write(out.join("files").join(&site.file_pages[&file.name]), page)?;
count += 1;
}
Ok(count)
}
struct Site<'a> {
documented: &'a Documented,
by_name: HashMap<&'a str, &'a DocObject>,
file_pages: HashMap<String, String>,
pages: HashMap<String, String>,
children: HashMap<&'a str, Vec<&'a str>>,
game: bool,
owners: Vec<Option<(&'a str, Option<&'a str>)>>,
messages_of: HashMap<&'a str, Vec<usize>>,
moments: Vec<(&'a DocObject, Vec<&'a DocObject>)>,
thing_choices: Vec<(&'a DocObject, Vec<&'a DocObject>)>,
}
impl<'a> Site<'a> {
fn new(documented: &'a Documented, game: bool) -> Self {
let objects = &documented.objects;
let mut by_name = HashMap::new();
let mut pages = HashMap::new();
let mut taken: HashSet<String> = HashSet::new();
let mut children: HashMap<&str, Vec<&str>> = HashMap::new();
for object in objects {
by_name.insert(object.name.as_str(), object);
let mut page = format!("{}.html", object.name);
let mut n = 2;
while !taken.insert(page.to_lowercase()) {
page = format!("{}~{n}.html", object.name);
n += 1;
}
pages.insert(object.name.clone(), page);
for parent in &object.superclasses {
children
.entry(parent.as_str())
.or_default()
.push(object.name.as_str());
}
}
for list in children.values_mut() {
list.sort_by_key(|name| name.to_lowercase());
}
let mut file_pages = HashMap::new();
let mut taken_files: HashSet<String> = HashSet::new();
for file in &documented.files {
let base: String = shown_file(&file.name)
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '.' || c == '_' {
c
} else {
'-'
}
})
.collect();
let mut page = format!("{base}.html");
let mut n = 2;
while !taken_files.insert(page.to_lowercase()) {
page = format!("{base}~{n}.html");
n += 1;
}
file_pages.insert(file.name.clone(), page);
}
let owners: Vec<_> = documented
.messages
.iter()
.map(|m| owner(documented, &m.place))
.collect();
let mut messages_of: HashMap<&str, Vec<usize>> = HashMap::new();
for (n, owner) in owners.iter().enumerate() {
if let Some((object, _)) = owner {
messages_of.entry(object).or_default().push(n);
}
}
let is_kind = |object: &DocObject, kind: &str| {
let mut seen = HashSet::new();
let mut todo: Vec<&str> = object.superclasses.iter().map(String::as_str).collect();
while let Some(name) = todo.pop() {
if name == kind {
return true;
}
if seen.insert(name)
&& let Some(parent) = by_name.get(name)
{
todo.extend(parent.superclasses.iter().map(String::as_str));
}
}
false
};
let choices: Vec<&DocObject> = documented
.objects
.iter()
.chain(&documented.anonymous)
.filter(|o| !o.is_class && is_kind(o, "Choice"))
.collect();
let mut thing_choices: Vec<(&DocObject, Vec<&DocObject>)> = Vec::new();
for choice in &choices {
let Some(owner) = choice
.value("location")
.and_then(|l| by_name.get(l).copied())
else {
continue;
};
if is_kind(owner, "ChoiceMoment") {
continue;
}
match thing_choices.iter_mut().find(|(t, _)| t.name == owner.name) {
Some((_, list)) => list.push(choice),
None => thing_choices.push((owner, vec![choice])),
}
}
let moments = documented
.objects
.iter()
.filter(|o| !o.is_class && !o.from_library && is_kind(o, "ChoiceMoment"))
.map(|moment| {
let mut own: Vec<&DocObject> = choices
.iter()
.copied()
.filter(|c| c.value("location") == Some(moment.name.as_str()))
.collect();
own.sort_by_key(|c| (c.place.file.clone(), c.place.line));
(moment, own)
})
.collect();
Self {
documented,
by_name,
file_pages,
pages,
children,
game,
owners,
messages_of,
moments,
thing_choices,
}
}
fn place(&self, at: &DocPlace, root: &str) -> String {
let shown = format!(
"<span class=\"file\">{}</span>, line {}",
html(&shown_file(&at.file)),
at.line
);
match self.file_pages.get(&at.file) {
Some(page) => format!(
"<a class=\"place\" href=\"{root}files/{}#L{}\">{shown}</a>",
attr(page),
at.line
),
None => shown,
}
}
fn where_defined(&self, object: &DocObject) -> String {
let mut text = format!(
"Defined in {}{}",
self.place(&object.place, "../"),
if object.from_library {
""
} else {
", the game's own"
}
);
if !object.modified_in.is_empty() {
let places: Vec<String> = object
.modified_in
.iter()
.map(|at| self.place(at, "../"))
.collect();
let _ = write!(text, "; modified in {}", places.join(", "));
}
text.push('.');
text
}
fn files_index(&self, title: &str) -> String {
let mut body = String::new();
let lede = if self.game {
"The source files the game is built from, its own and its libraries', and what each defines."
} else {
"The source files of the library, its extensions among them, and of the libraries it is built on, and what each defines."
};
let _ = write!(body, "<h1>Files</h1>\n<p class=\"lede\">{lede}</p>\n");
for (heading, library) in [("The game's", false), ("The libraries'", true)] {
let files: Vec<_> = self
.documented
.files
.iter()
.filter(|f| f.from_library == library)
.collect();
if files.is_empty() {
continue;
}
let _ = writeln!(body, "<h2>{heading}</h2>\n<dl class=\"index\">");
for file in files {
let mut defined: Vec<&str> = self
.documented
.objects
.iter()
.filter(|o| o.place.file == file.name)
.map(|o| o.name.as_str())
.collect();
defined.sort_by_key(|n| n.to_lowercase());
let links: Vec<String> = defined.iter().map(|n| self.link(n, true)).collect();
let functions = self
.documented
.functions
.iter()
.filter(|f| f.place.file == file.name)
.count();
let mut what = links.join(", ");
if functions > 0 {
if !what.is_empty() {
what.push_str("; ");
}
let _ = write!(
what,
"{functions} function{}",
if functions == 1 { "" } else { "s" }
);
}
let _ = writeln!(
body,
"<dt><a href=\"files/{}\">{}</a> <span class=\"from\">{} lines</span></dt><dd>{}</dd>",
attr(&self.file_pages[&file.name]),
html(&shown_file(&file.name)),
file.lines.len(),
what
);
}
body.push_str("</dl>\n");
}
self.page(&format!("Files: {title}"), "", &body)
}
fn functions_index(&self, title: &str) -> String {
let mut functions: Vec<_> = self.documented.functions.iter().collect();
functions.sort_by_key(|f| (f.name.to_lowercase(), f.name.clone()));
let mut body = String::from("<h1>Functions</h1>\n");
for function in functions {
let _ = write!(
body,
"<div class=\"member\" id=\"{}\">\n<h3><code>{}</code></h3>\n\
<p class=\"where\">{}{}</p>\n{}</div>\n",
attr(&function.name),
html(&function.declaration),
self.place(&function.place, ""),
if function.from_library {
""
} else {
", the game's own"
},
paragraphs(&function.comment)
);
}
self.page(&format!("Functions: {title}"), "", &body)
}
fn actions_index(&self, title: &str) -> String {
let mut actions: Vec<&DocObject> = self
.documented
.objects
.iter()
.filter(|o| o.name != "Action" && self.ancestors(o).iter().any(|(_, a)| a == "Action"))
.collect();
actions.sort_by_key(|o| (o.name.to_lowercase(), o.name.clone()));
let mut body = String::from(
"<h1>Actions</h1>\n<p class=\"lede\">Every action, and the rules of the \
grammar that say the words for it.</p>\n<dl class=\"index\">\n",
);
for action in actions {
let verbs: Vec<String> = self
.documented
.verbs
.iter()
.filter(|v| v.action == action.name)
.map(|v| {
format!(
"<code>{}</code> <span class=\"from\">({})</span>",
html(&v.words),
self.place(&v.place, "")
)
})
.collect();
let _ = writeln!(
body,
"<dt>{}</dt><dd>{}{}</dd>",
self.link(&action.name, true),
html(&summary(&action.comment)),
if verbs.is_empty() {
String::new()
} else {
format!("<br>{}", verbs.join("<br>"))
}
);
}
body.push_str("</dl>\n");
self.page(&format!("Actions: {title}"), "", &body)
}
fn sorted_messages(&self) -> Vec<&'a hexicon_compiler::DocMessage> {
let mut messages: Vec<_> = self.documented.messages.iter().collect();
messages.sort_by_key(|m| (m.id.to_lowercase(), m.place.file.clone(), m.place.line));
messages
}
fn messages_index(&self, title: &str) -> String {
let messages = self.sorted_messages();
let mut body = format!(
"<h1>Messages</h1>\n<p class=\"lede\">{}</p>\n\
<table class=\"messages\">\n<tr><th>Id</th><th>Text</th><th>Of</th><th>Where</th></tr>\n",
if self.game {
"The messages Hexad and the game show by an id, which a game can give text of \
its own for, with the text they have."
} else {
"The messages the library shows by an id, which a game can give text of its \
own for, with the text they have."
}
);
for (n, message) in messages.iter().enumerate() {
let _ = writeln!(
body,
"<tr id=\"m{n}\"><td><code>{}</code></td><td>{}</td><td>{}</td><td>{}</td></tr>",
html(&message.id),
message_text(message),
self.owner_link(message, "objects/"),
self.place(&message.place, "")
);
}
body.push_str("</table>\n");
self.page(&format!("Messages: {title}"), "", &body)
}
fn page(&self, title: &str, root: &str, body: &str) -> String {
page(title, root, body, !self.moments.is_empty())
}
fn choice_problems(&self) -> Vec<String> {
let is_moment = |name: &str| self.moments.iter().any(|(m, _)| m.name == name);
let mut problems = Vec::new();
for (moment, choices) in &self.moments {
for choice in choices {
if let Some(to) = choice.value("leadsTo")
&& to != "nil"
&& !is_moment(to)
{
problems.push(format!(
"{}: the choice \"{}\" leads to {to}, which is no choice moment",
moment.name,
label_of(choice)
));
}
}
}
let in_room = |moment: &DocObject| self.is_room_moment(moment);
for (moment, _) in self.moments.iter().filter(|(m, _)| !in_room(m)) {
let led_to = self.moments.iter().any(|(_, choices)| {
choices
.iter()
.any(|c| c.value("leadsTo") == Some(moment.name.as_str()))
});
if !led_to && !self.named_in_code(moment) {
problems.push(format!(
"{}: no choice leads to it, and the game's code does not name it, so it \
never begins",
moment.name
));
}
}
let mut ends: HashSet<&str> = HashSet::new();
loop {
let before = ends.len();
for (moment, choices) in &self.moments {
if ends.contains(moment.name.as_str()) {
continue;
}
let way_out = in_room(moment)
|| moment.value("allowCommands") == Some("true")
|| choices
.iter()
.all(|c| c.value("leadsTo").is_none() && c.value("isOnce") != Some("nil"))
|| choices.iter().any(|c| match c.value("leadsTo") {
Some("nil") => true,
Some(to) => ends.contains(to),
None => false,
});
if way_out {
ends.insert(moment.name.as_str());
}
}
if ends.len() == before {
break;
}
}
problems.extend(self.dead_ends());
for (moment, _) in self.moments.iter().filter(|(m, _)| !in_room(m)) {
if !ends.contains(moment.name.as_str()) {
problems.push(format!(
"{}: it has no way out: no choice ends it or leads to a moment that ends, \
and it allows no commands",
moment.name
));
}
}
problems
}
fn dead_ends(&self) -> Vec<String> {
const EXITS: [&str; 16] = [
"north",
"south",
"east",
"west",
"northeast",
"northwest",
"southeast",
"southwest",
"up",
"down",
"in",
"out",
"port",
"starboard",
"fore",
"aft",
];
let objects = &self.documented.objects;
let choice_game = objects.iter().any(|o| {
!o.is_class
&& self.is_a(o, "Story")
&& (o.value("choiceGame") == Some("true") || o.value("choicesOnly") == Some("true"))
});
if !choice_game {
return Vec::new();
}
let mut out = Vec::new();
for room in objects
.iter()
.filter(|o| !o.is_class && !o.from_library && self.is_a(o, "Room"))
{
let exits = EXITS.iter().any(|d| {
room.value(d)
.is_some_and(|v| v != "nil" && !v.starts_with(['\'', '"']))
});
let moment = self.moments.iter().any(|(m, choices)| {
!choices.is_empty() && m.value("location") == Some(room.name.as_str())
});
let things = self
.thing_choices
.iter()
.any(|(thing, _)| thing.value("location") == Some(room.name.as_str()));
if !exits && !moment && !things {
out.push(format!(
"{}: in a choice game, a room with no exits and no choices: a player who \
reaches it has nothing to choose, unless the game ends there (an exit \
that is code is not seen)",
room.name
));
}
}
out
}
fn is_room_moment(&self, moment: &DocObject) -> bool {
self.is_a(moment, "RoomMoment")
}
fn is_a(&self, object: &DocObject, class: &str) -> bool {
let mut todo: Vec<&str> = object.superclasses.iter().map(String::as_str).collect();
let mut seen = HashSet::new();
while let Some(name) = todo.pop() {
if name == class {
return true;
}
if seen.insert(name)
&& let Some(parent) = self.by_name.get(name)
{
todo.extend(parent.superclasses.iter().map(String::as_str));
}
}
false
}
fn named_in_code(&self, moment: &DocObject) -> bool {
self.documented.files.iter().any(|file| {
file.lines.iter().enumerate().any(|(i, line)| {
let trimmed = line.trim_start();
if trimmed.starts_with("//")
|| trimmed.starts_with('*')
|| trimmed.starts_with("/*")
|| trimmed.starts_with(&format!("{}:", moment.name))
|| (file.name == moment.place.file && i + 1 == moment.place.line as usize)
{
return false;
}
has_name(line, &moment.name) && !line.contains(&format!("->{}", moment.name))
})
})
}
fn choices_index(&self, title: &str) -> String {
let mut body = String::from(
"<h1>Choices</h1>\n<p class=\"lede\">The game's choice moments, each with its \
choices, where each leads, and what leads to it: a map of its choices, read \
without playing them.</p>\n",
);
let problems = self.choice_problems();
if !problems.is_empty() {
body.push_str("<h2>Problems</h2>\n<ul>\n");
for problem in &problems {
let _ = writeln!(body, "<li>{}</li>", html(problem));
}
body.push_str("</ul>\n");
}
let mut led_from: HashMap<&str, Vec<String>> = HashMap::new();
for (moment, choices) in &self.moments {
for choice in choices {
if let Some(to) = choice.value("leadsTo").filter(|v| *v != "nil") {
led_from.entry(to).or_default().push(format!(
"<a href=\"#{}\">{}</a>: {}",
attr(&moment.name),
html(&moment.name),
html(&label_of(choice))
));
}
}
}
for (moment, choices) in &self.moments {
let _ = writeln!(
body,
"<div class=\"moment\" id=\"{}\">\n<h2>{}</h2>\n<p class=\"where\">{}</p>",
attr(&moment.name),
self.link(&moment.name, true),
self.place(&moment.place, "")
);
let about = summary(&moment.comment);
if !about.is_empty() {
let _ = writeln!(body, "<p>{}</p>", html(&about));
}
let mut notes = Vec::new();
let room_note;
if self.is_room_moment(moment) {
room_note = format!(
"the moment of {}, with its exits as choices after these",
moment.value("location").unwrap_or("its room")
);
notes.push(room_note.as_str());
}
if moment.value("allowCommands") == Some("true") {
notes.push("a command ends it");
}
if moment.value("takesTurn") == Some("nil") {
notes.push("choosing takes no turn");
}
if !notes.is_empty() {
let _ = writeln!(body, "<p class=\"from\">In it, {}.</p>", notes.join("; "));
}
let from = led_from.get(moment.name.as_str());
let begun = if self.is_room_moment(moment) {
"being there begins it."
} else {
"nothing here; the game's code begins it."
};
let _ = writeln!(
body,
"<p class=\"from\">Led to from: {}</p>",
from.map_or_else(|| begun.to_owned(), |f| format!("{}.", f.join("; ")))
);
if choices.is_empty() {
body.push_str("<p>It has no choices.</p>\n</div>\n");
continue;
}
body.push_str(
"<table class=\"messages\">\n<tr><th>Choice</th><th>Leads to</th>\
<th>When</th><th>Where</th></tr>\n",
);
for choice in choices {
let command = self.is_a(choice, "ActionChoice").then(|| {
["action", "dobj", "iobj"]
.iter()
.filter_map(|p| choice.value(p))
.collect::<Vec<_>>()
.join(" ")
});
let leads = match choice.value("leadsTo") {
_ if command.is_some() => format!(
"<span class=\"from\">the command</span> <code>{}</code>",
html(command.as_deref().unwrap_or_default())
),
Some("nil") => "<span class=\"from\">ends the moment</span>".to_owned(),
Some(to) if self.moments.iter().any(|(m, _)| m.name == to) => {
format!("<a href=\"#{}\">{}</a>", attr(to), html(to))
}
Some(to) => self.link(to, true),
None => "<span class=\"from\">back to this moment</span>".to_owned(),
};
let mut when: Vec<String> = Vec::new();
if let Some(m) = choice.members.iter().find(|m| m.name == "isAvailable") {
when.push(format!("<code>{}</code>", html(&m.declaration)));
}
if command.is_some() {
when.push(
"<span class=\"from\">while the command would be allowed</span>".to_owned(),
);
} else if choice.value("isOnce") == Some("nil") {
when.push("<span class=\"from\">as often as chosen</span>".to_owned());
}
let _ = writeln!(
body,
"<tr><td>{}</td><td>{leads}</td><td>{}</td><td>{}</td></tr>",
html(&label_of(choice)),
when.join("<br>"),
self.place(&choice.place, "")
);
}
body.push_str("</table>\n</div>\n");
}
if !self.thing_choices.is_empty() {
body.push_str(
"<h2>Things' choices</h2>
<p>Listed by a room's moment, after its own, where the thing can be acted on.</p>
<table class=\"messages\">
<tr><th>Thing</th><th>Choice</th><th>Does</th><th>Where</th></tr>
",
);
for (thing, choices) in &self.thing_choices {
for choice in choices {
let does = if self.is_a(choice, "ActionChoice") {
let mut words: Vec<&str> = choice.value("action").into_iter().collect();
words.push(choice.value("dobj").unwrap_or(thing.name.as_str()));
words.extend(choice.value("iobj"));
format!(
"<span class=\"from\">the command</span> <code>{}</code>",
html(&words.join(" "))
)
} else {
String::new()
};
let _ = writeln!(
body,
"<tr><td>{}</td><td>{}</td><td>{does}</td><td>{}</td></tr>",
self.link(&thing.name, true),
html(&label_of(choice)),
self.place(&choice.place, "")
);
}
}
body.push_str(
"</table>
",
);
}
self.page(&format!("Choices: {title}"), "", &body)
}
fn extensions_index(&self, title: &str) -> String {
let mut body = String::from("<h1>Extensions</h1>\n");
let extensions: Vec<_> = self
.documented
.files
.iter()
.filter(|f| f.from_library && extension_name(&f.name).is_some())
.collect();
let lede = if self.game {
"The extensions of its libraries the game is built with: sources a game adds by \
naming them in its manifest, after its library's name."
} else {
"The library's extensions: sources a game adds by naming them in its manifest, \
as <code>libraries = [{ name = \"hexad\", include = [\"extensions/rules\"] }]</code> \
adds the rules extension."
};
let _ = writeln!(body, "<p class=\"lede\">{lede}</p>");
if extensions.is_empty() {
body.push_str("<p>The game is built with none.</p>\n");
return self.page(&format!("Extensions: {title}"), "", &body);
}
body.push_str("<dl class=\"index\">\n");
for file in extensions {
let name = extension_name(&file.name).unwrap_or_default();
let mut defined: Vec<&str> = self
.documented
.objects
.iter()
.filter(|o| o.place.file == file.name)
.map(|o| o.name.as_str())
.collect();
defined.sort_by_key(|n| n.to_lowercase());
let links: Vec<String> = defined.iter().map(|n| self.link(n, true)).collect();
let about = summary(&file_comment(&file.lines));
let mut what = html(&about);
if !links.is_empty() {
if !what.is_empty() {
what.push(' ');
}
let _ = write!(what, "Defines {}.", links.join(", "));
}
let _ = writeln!(
body,
"<dt><a href=\"files/{}\"><code>{}</code></a></dt><dd>{what}</dd>",
attr(&self.file_pages[&file.name]),
html(&name)
);
}
body.push_str("</dl>\n");
self.page(&format!("Extensions: {title}"), "", &body)
}
fn macros_index(&self, title: &str) -> String {
let mut macros: Vec<_> = self.documented.macros.iter().collect();
macros.sort_by_key(|m| (m.name.to_lowercase(), m.name.clone()));
let mut body = String::from(
"<h1>Macros and enumerations</h1>\n<p class=\"lede\">The macros the sources \
define, and the values of their enumerations.</p>\n<h2>Macros</h2>\n",
);
let mut seen: HashSet<&str> = HashSet::new();
for m in macros {
let id = if seen.insert(m.name.as_str()) {
format!(" id=\"{}\"", attr(&m.name))
} else {
String::new()
};
let _ = write!(
body,
"<div class=\"member\"{id}>\n<h3><code>{}{}</code></h3>\n\
<p class=\"where\">{}</p>\n<p><code>{}</code></p>\n{}</div>\n",
html(&m.name),
html(&m.params),
self.place(&m.place, ""),
html(&m.expansion),
paragraphs(&m.comment)
);
}
body.push_str("<h2>Enumerations</h2>\n");
for e in &self.documented.enums {
let ids: String = e
.names
.iter()
.map(|n| format!("<code id=\"e-{}\">{}</code>", attr(n), html(n)))
.collect::<Vec<_>>()
.join(", ");
let _ = write!(
body,
"<div class=\"member\">\n<p>{}{ids}</p>\n<p class=\"where\">{}</p>\n{}</div>\n",
if e.is_token { "Kinds of token: " } else { "" },
self.place(&e.place, ""),
paragraphs(&e.comment)
);
}
self.page(&format!("Macros: {title}"), "", &body)
}
fn search_page(&self, title: &str) -> String {
let body = "<h1>Search</h1>\n<p><input id=\"query\" type=\"search\" \
placeholder=\"A name: Thing, isLit, dobj Take, cannot take\" \
autofocus></p>\n<p id=\"count\" class=\"where\"></p>\n\
<ul id=\"results\" class=\"results\"></ul>\n\
<script src=\"search-index.js\"></script>\n<script src=\"search.js\"></script>\n";
self.page(&format!("Search: {title}"), "", body)
}
fn search_index(&self) -> String {
let mut entries: Vec<[String; 4]> = Vec::new();
for object in &self.documented.objects {
let page = format!("objects/{}", self.pages[&object.name]);
entries.push([
object.name.clone(),
if object.is_class { "class" } else { "object" }.to_owned(),
summary(&object.comment),
page.clone(),
]);
for member in &object.members {
let kind = match Kind::of(member) {
Kind::Property => "property",
Kind::Method => "method",
Kind::Handler => "handler",
};
entries.push([
member.name.clone(),
kind.to_owned(),
object.name.clone(),
format!("{page}#{}", anchor(&member.name)),
]);
}
}
for function in &self.documented.functions {
entries.push([
function.name.clone(),
"function".to_owned(),
summary(&function.comment),
format!("functions.html#{}", function.name),
]);
}
for (n, message) in self.sorted_messages().iter().enumerate() {
entries.push([
message.id.clone(),
"message".to_owned(),
message.text.chars().take(80).collect(),
format!("messages.html#m{n}"),
]);
}
let mut seen: HashSet<&str> = HashSet::new();
for m in &self.documented.macros {
if seen.insert(m.name.as_str()) {
entries.push([
m.name.clone(),
"macro".to_owned(),
summary(&m.comment),
format!("macros.html#{}", m.name),
]);
}
}
for e in &self.documented.enums {
for name in &e.names {
entries.push([
name.clone(),
"enum".to_owned(),
String::new(),
format!("macros.html#e-{name}"),
]);
}
}
for file in &self.documented.files {
entries.push([
shown_file(&file.name),
"file".to_owned(),
String::new(),
format!("files/{}", self.file_pages[&file.name]),
]);
}
let mut out = String::from("var SEARCH = [\n");
for entry in entries {
let fields: Vec<String> = entry.iter().map(|f| js_string(f)).collect();
let _ = writeln!(out, "[{}],", fields.join(","));
}
out.push_str("];\n");
out
}
fn file_page(&self, title: &str, file: &hexicon_compiler::DocFile) -> String {
let mut body = String::new();
let _ = writeln!(
body,
"<h1><span class=\"file\">{}</span></h1>\n<p class=\"where\">{} lines, {}.</p>",
html(&shown_file(&file.name)),
file.lines.len(),
if file.from_library {
"a library's"
} else {
"the game's own"
}
);
body.push_str("<pre class=\"source\">");
for (index, line) in file.lines.iter().enumerate() {
let n = index + 1;
let _ = writeln!(
body,
"<span class=\"line\" id=\"L{n}\"><a class=\"n\" href=\"#L{n}\">{n}</a>{}</span>",
html(line)
);
}
body.push_str("</pre>\n");
self.page(
&format!("{}: {title}", shown_file(&file.name)),
"../",
&body,
)
}
fn link(&self, name: &str, from_index: bool) -> String {
match self.pages.get(name) {
Some(page) => {
let prefix = if from_index { "objects/" } else { "" };
format!("<a href=\"{prefix}{}\">{}</a>", attr(page), html(name))
}
None => html(name),
}
}
fn index(&self, title: &str) -> String {
let mut objects: Vec<&&DocObject> = self.by_name.values().collect();
objects.sort_by_key(|o| (o.name.to_lowercase(), o.name.clone()));
let mut body = String::new();
let lede = if self.game {
"The reference: every class and object the game's sources define, its libraries' \
among them."
} else {
"The reference: every class and object the library defines, its extensions' and \
the libraries' it is built on among them."
};
let _ = write!(
body,
"<h1>{}</h1>\n<p class=\"lede\">{lede}</p>\n",
html(title)
);
for (heading, classes) in [("Classes", true), ("Objects", false)] {
let _ = write!(body, "<h2>{heading}</h2>\n<dl class=\"index\">\n");
for object in objects.iter().filter(|o| o.is_class == classes) {
let _ = writeln!(
body,
"<dt>{}</dt><dd>{}</dd>",
self.link(&object.name, true),
html(&summary(&object.comment))
);
}
body.push_str("</dl>\n");
}
self.page(&format!("{title}: reference"), "", &body)
}
fn object_page(&self, title: &str, object: &DocObject) -> String {
let mut body = String::new();
let kind = if object.is_class { "class" } else { "object" };
let _ = writeln!(
body,
"<p class=\"crumbs\"><a href=\"../index.html\">{}</a></p>",
html(title)
);
let _ = writeln!(
body,
"<h1>{} <span class=\"kind\">{kind}</span></h1>",
html(&object.name)
);
let supers: Vec<String> = object
.superclasses
.iter()
.map(|s| self.link(s, false))
.collect();
let _ = writeln!(
body,
"<p class=\"decl\"><code>{}{}: {}</code></p>",
if object.is_class { "class " } else { "" },
html(&object.name),
if supers.is_empty() {
"object".to_owned()
} else {
supers.join(", ")
}
);
let _ = writeln!(
body,
"<p class=\"where\">{}</p>",
self.where_defined(object)
);
body.push_str(¶graphs(&object.comment));
let templates: Vec<String> = self
.documented
.templates
.iter()
.filter(|t| t.class == object.name)
.map(|t| {
format!(
"<li><code>{}</code> <span class=\"from\">({})</span></li>",
html(&t.text),
self.place(&t.place, "../")
)
})
.collect();
if !templates.is_empty() {
let _ = write!(
body,
"<h2>Templates</h2>\n<p>What values written without names stand for, in an \
object of the class:</p>\n<ul>\n{}</ul>\n",
templates.join("\n")
);
}
let ancestors = self.ancestors(object);
if !ancestors.is_empty() {
body.push_str("<h2>Built on</h2>\n<ul class=\"tree\">\n");
for (depth, name) in &ancestors {
let _ = writeln!(
body,
"<li style=\"margin-left: {}em\">{}</li>",
*depth as f64 * 1.5,
self.link(name, false)
);
}
body.push_str("</ul>\n");
}
if let Some(kids) = self.children.get(object.name.as_str()) {
body.push_str("<h2>Built on it</h2>\n");
for (label, classes) in [("Classes", true), ("Objects", false)] {
let links: Vec<String> = kids
.iter()
.filter(|k| self.by_name.get(**k).is_some_and(|o| o.is_class == classes))
.map(|k| self.link(k, false))
.collect();
if !links.is_empty() {
let _ = writeln!(
body,
"<p class=\"kids\"><span class=\"from\">{label}:</span> {}</p>",
links.join(", ")
);
}
}
}
for (heading, kind) in [
("Properties", Kind::Property),
("Methods", Kind::Method),
("Handlers", Kind::Handler),
] {
let mut members: Vec<_> = object
.members
.iter()
.filter(|m| Kind::of(m) == kind)
.collect();
if members.is_empty() {
continue;
}
members.sort_by_key(|m| m.name.to_lowercase());
let _ = writeln!(body, "<h2>{heading}</h2>");
for member in members {
body.push_str(&self.member(member));
}
}
if let Some(own) = self.messages_of.get(object.name.as_str()) {
let mut own: Vec<&hexicon_compiler::DocMessage> =
own.iter().map(|&n| &self.documented.messages[n]).collect();
own.sort_by_key(|m| (m.id.to_lowercase(), m.place.line));
let _ = write!(
body,
"<h2>Messages</h2>\n<p>The messages it shows by an id, which a game can give \
text of its own for:</p>\n<table class=\"messages\">\n<tr><th>Id</th>\
<th>Text</th><th>In</th><th>Where</th></tr>\n"
);
for message in own {
let member = self
.owner_of(message)
.and_then(|(_, member)| member)
.map_or_else(String::new, |m| {
format!(
"<a href=\"#{}\"><code>{}</code></a>",
attr(&anchor(m)),
html(m)
)
});
let _ = writeln!(
body,
"<tr><td><code>{}</code></td><td>{}</td><td>{member}</td><td>{}</td></tr>",
html(&message.id),
message_text(message),
self.place(&message.place, "../")
);
}
body.push_str("</table>\n");
}
let mut seen: HashSet<&str> = object.members.iter().map(|m| m.name.as_str()).collect();
let mut inherited = String::new();
for (_, name) in &ancestors {
let Some(ancestor) = self.by_name.get(name.as_str()) else {
continue;
};
let page = &self.pages[&ancestor.name];
if object.is_class {
let mut members: Vec<_> = ancestor
.members
.iter()
.filter(|m| seen.insert(m.name.as_str()))
.collect();
if members.is_empty() {
continue;
}
members.sort_by_key(|m| (Kind::of(m) == Kind::Handler, m.name.to_lowercase()));
let _ = writeln!(
inherited,
"<details class=\"inherited\">\n<summary>From {} <span class=\"from\">({} {})</span></summary>",
self.link(&ancestor.name, false),
members.len(),
if members.len() == 1 {
"member"
} else {
"members"
}
);
for member in members {
inherited.push_str(&self.member(member));
}
inherited.push_str("</details>\n");
continue;
}
let mut lines: Vec<String> = Vec::new();
for handlers in [false, true] {
let mut names: Vec<&str> = ancestor
.members
.iter()
.filter(|m| (Kind::of(m) == Kind::Handler) == handlers)
.map(|m| m.name.as_str())
.filter(|n| seen.insert(n))
.collect();
if names.is_empty() {
continue;
}
names.sort_by_key(|n| n.to_lowercase());
let links: Vec<String> = names
.iter()
.map(|n| {
format!(
"<a href=\"{}#{}\">{}</a>",
attr(page),
attr(&anchor(n)),
html(n)
)
})
.collect();
lines.push(format!(
"<span class=\"from\">{}</span> {}",
if handlers {
"Handlers:"
} else {
"Properties and methods:"
},
links.join(", ")
));
}
if lines.is_empty() {
continue;
}
let _ = writeln!(
inherited,
"<h3>From {}</h3>\n<p class=\"inherited\">{}</p>",
self.link(&ancestor.name, false),
lines.join("<br>\n")
);
}
if !inherited.is_empty() {
body.push_str("<h2>Inherited</h2>\n");
body.push_str(&inherited);
}
self.page(&format!("{}: {title}", object.name), "../", &body)
}
fn owner_of(
&self,
message: &hexicon_compiler::DocMessage,
) -> Option<(&'a str, Option<&'a str>)> {
let at = self
.documented
.messages
.iter()
.position(|m| std::ptr::eq(m, message))?;
self.owners[at]
}
fn owner_link(&self, message: &hexicon_compiler::DocMessage, prefix: &str) -> String {
let Some((object, member)) = self.owner_of(message) else {
return String::new();
};
let Some(page) = self.pages.get(object) else {
return html(object);
};
match member {
Some(member) => format!(
"<a href=\"{prefix}{}#{}\">{}.{}</a>",
attr(page),
attr(&anchor(member)),
html(object),
html(member)
),
None => format!("<a href=\"{prefix}{}\">{}</a>", attr(page), html(object)),
}
}
fn member(&self, member: &hexicon_compiler::DocMember) -> String {
let stages = if member.stages.is_empty() {
String::new()
} else {
format!(
"<p class=\"stages\">Stages: {}</p>\n",
html(&member.stages.join(", "))
)
};
format!(
"<div class=\"member\" id=\"{}\">\n<h3><code>{}</code></h3>\n\
<p class=\"where\">{}</p>\n{stages}{}</div>\n",
attr(&anchor(&member.name)),
html(&member.declaration),
self.place(&member.place, "../"),
paragraphs(&member.comment)
)
}
fn ancestors(&self, object: &DocObject) -> Vec<(usize, String)> {
let mut out = Vec::new();
let mut seen = HashSet::new();
self.walk(object, 0, &mut seen, &mut out);
out
}
fn walk(
&self,
object: &DocObject,
depth: usize,
seen: &mut HashSet<String>,
out: &mut Vec<(usize, String)>,
) {
for parent in &object.superclasses {
if !seen.insert(parent.clone()) {
continue;
}
out.push((depth, parent.clone()));
if let Some(next) = self.by_name.get(parent.as_str()) {
self.walk(next, depth + 1, seen, out);
}
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
Property,
Method,
Handler,
}
impl Kind {
fn of(member: &hexicon_compiler::DocMember) -> Self {
if !member.stages.is_empty() {
Self::Handler
} else if member.is_method {
Self::Method
} else {
Self::Property
}
}
}
fn anchor(name: &str) -> String {
name.replace(' ', "-")
}
fn shown_file(file: &str) -> String {
shown_from(file, std::env::current_dir().ok().as_deref())
}
fn shown_from(file: &str, here: Option<&std::path::Path>) -> String {
let file = file.replace('\\', "/");
if let Some(rest) = file.strip_prefix("<hexicon>/") {
return rest.to_owned();
}
if let Some(here) = here {
if let Some(rest) = within(&file, here) {
return rest;
}
if let Ok(resolved) = std::fs::canonicalize(&file) {
let resolved = resolved.to_string_lossy().replace('\\', "/");
if let Some(rest) = std::fs::canonicalize(here)
.ok()
.and_then(|here| within(&resolved, &here))
{
return rest;
}
}
}
match file.rfind("/lib/") {
Some(at) => file[at + 5..].to_owned(),
None => file,
}
}
fn within(file: &str, folder: &std::path::Path) -> Option<String> {
let folder = folder.to_string_lossy().replace('\\', "/");
let folder = folder.trim_end_matches('/');
file.strip_prefix(&format!("{folder}/")).map(str::to_owned)
}
pub(crate) fn choice_problems(project_args: &[String]) -> Vec<String> {
let Ok(project) = read_project(&mut DiskFiles, project_args, &crate::build::default_paths())
else {
return Vec::new();
};
let has_choices = project.sources.iter().any(|s| {
let s = s.replace('\\', "/");
s.ends_with("/extensions/choices.hxn")
});
if !has_choices {
return Vec::new();
}
let sources: Vec<&str> = project.sources.iter().map(String::as_str).collect();
let documented = document(&mut DiskFiles, &sources, &project.options);
if !documented.diagnostics.is_empty() {
return Vec::new();
}
Site::new(&documented, true).choice_problems()
}
#[derive(Default)]
pub(crate) struct TestPlaces {
pub(crate) scenarios: Vec<(String, DocPlace, Vec<DocPlace>)>,
pub(crate) objects: HashMap<String, DocPlace>,
pub(crate) choices: Vec<(String, String, DocPlace)>,
pub(crate) problems: Vec<(String, Option<DocPlace>)>,
}
pub(crate) fn test_places(project_args: &[String]) -> TestPlaces {
let Ok(project) = read_project(&mut DiskFiles, project_args, &crate::build::default_paths())
else {
return TestPlaces::default();
};
let sources: Vec<&str> = project.sources.iter().map(String::as_str).collect();
let documented = document(&mut DiskFiles, &sources, &project.options);
if !documented.diagnostics.is_empty() {
return TestPlaces::default();
}
let site = Site::new(&documented, true);
let all = || documented.objects.iter().chain(&documented.anonymous);
let unquoted = |value: &str| {
let value = value.trim();
let inner = value
.strip_prefix('\'')
.and_then(|v| v.strip_suffix('\''))
.or_else(|| value.strip_prefix('"').and_then(|v| v.strip_suffix('"')))
.unwrap_or(value);
inner.replace("\\'", "'").replace("\\\"", "\"")
};
let mut places = TestPlaces::default();
for object in all().filter(|o| !o.is_class) {
let name = if site.is_a(object, "Walkthrough") {
object.value("walkthroughName")
} else if site.is_a(object, "Scenario") {
object.value("scenarioName")
} else {
None
};
if let Some(name) = name {
let mut steps: Vec<DocPlace> = if object.name.is_empty() {
Vec::new()
} else {
all()
.filter(|o| {
!o.is_class
&& site.is_a(o, "ScenarioStep")
&& o.value("location") == Some(object.name.as_str())
})
.map(|o| o.place.clone())
.collect()
};
steps.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line)));
places
.scenarios
.push((unquoted(name), object.place.clone(), steps));
}
}
for object in documented.objects.iter().filter(|o| !o.is_class) {
places
.objects
.entry(object.name.clone())
.or_insert_with(|| object.place.clone());
}
for (owner, choices) in site.moments.iter().chain(&site.thing_choices) {
for choice in choices {
places
.choices
.push((owner.name.clone(), label_of(choice), choice.place.clone()));
}
}
let has_choices = project
.sources
.iter()
.any(|s| s.replace('\\', "/").ends_with("/extensions/choices.hxn"));
if has_choices {
places.problems = site
.choice_problems()
.into_iter()
.map(|problem| {
let place = problem
.split_once(':')
.and_then(|(name, _)| places.objects.get(name))
.cloned();
(problem, place)
})
.collect();
}
places
}
fn has_name(line: &str, name: &str) -> bool {
let is_word = |c: char| c.is_alphanumeric() || c == '_';
line.match_indices(name).any(|(at, _)| {
!line[..at].chars().next_back().is_some_and(is_word)
&& !line[at + name.len()..].chars().next().is_some_and(is_word)
})
}
fn label_of(choice: &DocObject) -> String {
choice
.value("label")
.map(|l| l.trim_matches('\'').to_owned())
.unwrap_or_default()
}
fn message_text(message: &hexicon_compiler::DocMessage) -> String {
if message.text.is_empty() {
"<span class=\"from\">(made by the code)</span>".to_owned()
} else {
html(&message.text)
}
}
fn owner<'a>(documented: &'a Documented, at: &DocPlace) -> Option<(&'a str, Option<&'a str>)> {
let lines = &documented.files.iter().find(|f| f.name == at.file)?.lines;
let start_of = |line: u32| {
(1..=line).rev().find(|&n| {
lines
.get(n as usize - 1)
.and_then(|l| l.chars().next())
.is_some_and(|c| c.is_alphabetic() || c == '+' || c == '_')
})
};
let start = start_of(at.line)?;
let object = documented.objects.iter().find(|object| {
std::iter::once(&object.place)
.chain(&object.modified_in)
.any(|p| p.file == at.file && start_of(p.line) == Some(start))
})?;
let member = object
.members
.iter()
.filter(|m| m.place.file == at.file && m.place.line >= start && m.place.line <= at.line)
.max_by_key(|m| m.place.line)
.map(|m| m.name.as_str());
Some((object.name.as_str(), member))
}
fn extension_name(file: &str) -> Option<String> {
let shown = shown_file(file);
let at = shown.find("extensions/")?;
if at > 0 && !shown[..at].ends_with('/') {
return None;
}
let name = &shown[at..];
Some(name.strip_suffix(".hxn").unwrap_or(name).to_owned())
}
fn file_comment(lines: &[String]) -> String {
let mut text: Vec<String> = Vec::new();
let mut inside = false;
let mut title = String::new();
for line in lines.iter().take(60) {
let trimmed = line.trim();
if !inside {
if trimmed.starts_with("/*") && !trimmed.contains("*/") {
inside = true;
}
continue;
}
if trimmed.starts_with("*/") || trimmed.ends_with("*/") && !trimmed.starts_with('*') {
break;
}
let words = trimmed
.trim_start_matches(['*', '.', '-', ' ', '\t'])
.trim();
let lower = words.to_lowercase();
let count = words.split_whitespace().count();
let sentence = words.ends_with('.');
let is_title = (lower.contains("extension") && count <= 6 && !sentence)
|| (lower.contains("version") && count <= 6 && !sentence)
|| (lower.ends_with("module") && count <= 4)
|| lower.starts_with("revised:")
|| lower.starts_with("hexad - ")
|| (count == 1 && (lower.ends_with(".hxn") || lower.ends_with(".t")));
if words.is_empty()
&& trimmed.trim_matches(['*', '-', '.', ' ']).is_empty()
&& trimmed.len() > 2
{
continue;
}
if is_title {
if title.is_empty() && lower.contains("extension") {
title = words.to_owned();
}
continue;
}
text.push(words.to_owned());
}
let joined: Vec<String> = text
.split(String::is_empty)
.filter(|p| !p.is_empty())
.map(|p| p.join(" "))
.collect();
if joined.is_empty() {
title
} else {
joined.join("\n\n")
}
}
fn paragraphs(comment: &str) -> String {
comment
.split("\n\n")
.filter(|p| !p.trim().is_empty())
.map(|p| format!("<p>{}</p>\n", html(p)))
.collect()
}
fn summary(comment: &str) -> String {
let first = comment.split("\n\n").next().unwrap_or_default();
let end = first
.match_indices(". ")
.map(|(at, _)| at + 1)
.next()
.unwrap_or(first.len());
let mut text: String = first[..end].to_owned();
if text.chars().count() > 200 {
text = text.chars().take(197).collect::<String>() + "...";
}
text
}
fn page(title: &str, root: &str, body: &str, choices: bool) -> String {
let choices = if choices {
format!("<a href=\"{root}choices.html\">Choices</a> ")
} else {
String::new()
};
format!(
"<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n\
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
<title>{}</title>\n<link rel=\"stylesheet\" href=\"{root}reference.css\">\n\
</head>\n<body>\n<nav class=\"bar\"><a href=\"{root}index.html\">Classes and \
objects</a> <a href=\"{root}files.html\">Files</a> <a href=\"{root}extensions.html\">\
Extensions</a> <a href=\"{root}functions.html\">\
Functions</a> <a href=\"{root}actions.html\">Actions</a> <a \
href=\"{root}messages.html\">Messages</a> <a href=\"{root}macros.html\">Macros</a> {choices}\
<form class=\"search\" action=\"{root}search.html\"><input name=\"q\" \
type=\"search\" placeholder=\"Search\" aria-label=\"Search\"></form></nav>\n\
<main>\n{body}</main>\n</body>\n</html>\n",
html(title)
)
}
fn js_string(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 2);
out.push('"');
for c in text.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'<' => out.push_str("\\u003c"),
c if (c as u32) < 0x20 => {
let _ = write!(out, "\\u{:04x}", c as u32);
}
c => out.push(c),
}
}
out.push('"');
out
}
fn html(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
_ => out.push(c),
}
}
out
}
fn attr(text: &str) -> String {
html(text).replace(' ', "%20")
}
#[cfg(test)]
mod tests {
use super::{Site, extension_name, file_comment, library_reference, shown_from};
#[test]
fn a_library_is_documented_with_its_extensions_and_no_game() {
let (title, documented) =
library_reference("hexad", &[], &[], "").unwrap_or_else(|_| panic!("no reference"));
assert_eq!(title, "Hexad");
assert!(
documented.diagnostics.is_empty(),
"{:?}",
documented.diagnostics
);
let names: Vec<&str> = documented.objects.iter().map(|o| o.name.as_str()).collect();
for name in ["Thing", "RuleBook", "Exception"] {
assert!(names.contains(&name), "{name}");
}
assert!(documented.files.iter().all(|f| f.from_library));
assert!(
!documented
.files
.iter()
.any(|f| f.name.contains("<hexicon doc>"))
);
let site = Site::new(&documented, false);
let extensions = site.extensions_index(&title);
assert!(extensions.contains("<code>extensions/rules</code>"));
assert!(
site.index(&title)
.contains("every class and object the library defines")
);
}
#[test]
fn a_class_has_what_it_inherits_in_full_and_an_object_by_name() {
use hexicon_compiler::{DocMember, DocObject, DocPlace};
let place = |line| DocPlace {
file: "lib.hxn".to_owned(),
line,
};
let member = |name: &str, comment: &str, line| DocMember {
name: name.to_owned(),
declaration: format!("{name} = nil"),
comment: comment.to_owned(),
place: place(line),
is_method: false,
stages: Vec::new(),
};
let object = |name: &str, is_class, superclasses: &[&str], members| DocObject {
name: name.to_owned(),
is_class,
superclasses: superclasses.iter().map(|s| (*s).to_owned()).collect(),
place: place(1),
comment: String::new(),
modified_in: Vec::new(),
members,
from_library: true,
values: Vec::new(),
};
let documented = hexicon_compiler::Documented {
objects: vec![
object(
"Base",
true,
&[],
vec![
member("isLit", "Whether it gives light.", 2),
member("weight", "How heavy it is.", 3),
],
),
object(
"Lamp",
true,
&["Base"],
vec![member("weight", "A lamp's.", 9)],
),
object("lamp", false, &["Lamp"], Vec::new()),
],
..Default::default()
};
let site = Site::new(&documented, true);
let class = site.object_page("A game", &documented.objects[1]);
assert!(class.contains("<details class=\"inherited\">"));
assert!(class.contains("(1 member)"));
assert!(class.contains("Whether it gives light."));
assert!(!class.contains("How heavy it is."));
let instance = site.object_page("A game", &documented.objects[2]);
assert!(!instance.contains("<details"));
assert!(!instance.contains("Whether it gives light."));
assert!(instance.contains("Base.html#isLit"));
}
#[test]
fn a_message_is_on_the_page_of_the_object_it_is_written_in() {
use hexicon_compiler::{DocFile, DocMember, DocMessage, DocObject, DocPlace};
let text = [
"class Lamp: object", " lit = nil", " dimMsg = msgText(lamp dim, 'The lamp dims. ')", ";", "modify Lamp", " // A comment, at the members' margin.", " brightMsg = msgText(lamp bright, 'It shines. ')", ";", "lampHelp()", "{", " showMsg(lamp help, 'Rub it. ');", "}", "action Polish: IAction", " execAction(cmd) { showMsg(polished, 'Done. '); }", ";", ];
let place = |line| DocPlace {
file: "lamp.hxn".to_owned(),
line,
};
let member = |name: &str, line| DocMember {
name: name.to_owned(),
declaration: name.to_owned(),
comment: String::new(),
place: place(line),
is_method: false,
stages: Vec::new(),
};
let message = |id: &str, line| DocMessage {
id: id.to_owned(),
text: "text".to_owned(),
place: place(line),
};
let documented = hexicon_compiler::Documented {
objects: vec![DocObject {
name: "Lamp".to_owned(),
is_class: true,
superclasses: Vec::new(),
place: place(1),
comment: String::new(),
modified_in: vec![place(7)],
members: vec![
member("lit", 2),
member("dimMsg", 3),
member("brightMsg", 7),
],
from_library: true,
values: Vec::new(),
}],
messages: vec![
message("lamp dim", 3),
message("lamp bright", 7),
message("lamp help", 11),
message("polished", 14),
],
files: vec![DocFile {
name: "lamp.hxn".to_owned(),
lines: text.iter().map(|s| (*s).to_owned()).collect(),
from_library: true,
}],
..Default::default()
};
let owners: Vec<_> = documented
.messages
.iter()
.map(|m| super::owner(&documented, &m.place))
.collect();
assert_eq!(
owners,
[
Some(("Lamp", Some("dimMsg"))),
Some(("Lamp", Some("brightMsg"))),
None,
None
]
);
let site = Site::new(&documented, true);
let page = site.object_page("A game", &documented.objects[0]);
assert!(page.contains("<h2>Messages</h2>"));
assert!(page.contains("<code>lamp bright</code>"));
assert!(page.contains("href=\"#brightMsg\""));
assert!(!page.contains("lamp help"));
let index = site.messages_index("A game");
assert!(index.contains("objects/Lamp.html#dimMsg\">Lamp.dimMsg</a>"));
}
#[test]
fn what_is_wrong_with_the_choices_is_found_by_reading_them() {
use hexicon_compiler::{DocFile, DocObject, DocPlace};
let object = |name: &str, superclasses: &[&str], line, values: &[(&str, &str)]| DocObject {
name: name.to_owned(),
is_class: matches!(name, "ChoiceMoment" | "Choice" | "RoomMoment"),
superclasses: superclasses.iter().map(|s| (*s).to_owned()).collect(),
place: DocPlace {
file: "game.hxn".to_owned(),
line,
},
comment: String::new(),
modified_in: Vec::new(),
members: Vec::new(),
from_library: false,
values: values
.iter()
.map(|(p, v)| ((*p).to_owned(), (*v).to_owned()))
.collect(),
};
let lines = [
"snap: ChoiceMoment", "+ Choice 'Grab it' ->sway;", "sway: ChoiceMoment", "+ Choice 'Crawl' ->nil;", "trap: ChoiceMoment", "+ Choice 'Pace' isOnce = nil;", "// trap is never begun.", "+ Choice 'Leave' ->hall;", "bell() { snap.begin(); }", ];
let documented = hexicon_compiler::Documented {
objects: vec![
object("ChoiceMoment", &["object"], 1, &[]),
object("Choice", &["object"], 1, &[]),
object("snap", &["ChoiceMoment"], 1, &[]),
object("sway", &["ChoiceMoment"], 3, &[]),
object("trap", &["ChoiceMoment"], 5, &[]),
object("RoomMoment", &["ChoiceMoment"], 1, &[]),
object("hallMoment", &["RoomMoment"], 9, &[("location", "hall")]),
],
anonymous: vec![
object(
"",
&["Choice"],
2,
&[
("label", "'Grab it'"),
("leadsTo", "sway"),
("location", "snap"),
],
),
object(
"",
&["Choice"],
4,
&[
("label", "'Crawl'"),
("leadsTo", "nil"),
("location", "sway"),
],
),
object(
"",
&["Choice"],
6,
&[("label", "'Pace'"), ("isOnce", "nil"), ("location", "trap")],
),
object(
"",
&["Choice"],
8,
&[
("label", "'Leave'"),
("leadsTo", "hall"),
("location", "sway"),
],
),
],
files: vec![DocFile {
name: "game.hxn".to_owned(),
lines: lines.iter().map(|s| (*s).to_owned()).collect(),
from_library: false,
}],
..Default::default()
};
let problems = Site::new(&documented, true).choice_problems();
assert_eq!(
problems,
[
"sway: the choice \"Leave\" leads to hall, which is no choice moment",
"trap: no choice leads to it, and the game's code does not name it, so it never \
begins",
"trap: it has no way out: no choice ends it or leads to a moment that ends, and it \
allows no commands",
]
);
}
#[test]
fn a_room_with_nothing_to_choose_in_a_choice_game_is_found() {
use hexicon_compiler::{DocObject, DocPlace};
let object =
|name: &str, is_class, superclasses: &[&str], values: &[(&str, &str)]| DocObject {
name: name.to_owned(),
is_class,
superclasses: superclasses.iter().map(|s| (*s).to_owned()).collect(),
place: DocPlace {
file: "game.hxn".to_owned(),
line: 1,
},
comment: String::new(),
modified_in: Vec::new(),
members: Vec::new(),
from_library: false,
values: values
.iter()
.map(|(p, v)| ((*p).to_owned(), (*v).to_owned()))
.collect(),
};
let rooms = |choice_game: &str| hexicon_compiler::Documented {
objects: vec![
object("Story", true, &["object"], &[]),
object("Room", true, &["object"], &[]),
object("ChoiceMoment", true, &["object"], &[]),
object("RoomMoment", true, &["ChoiceMoment"], &[]),
object("Choice", true, &["object"], &[]),
object("story", false, &["Story"], &[("choiceGame", choice_game)]),
object("hall", false, &["Room"], &[("north", "frontDoor")]),
object(
"study",
false,
&["Room"],
&[("north", "'The wall is solid.'")],
),
object(
"studyMoment",
false,
&["RoomMoment"],
&[("location", "study")],
),
object("cellar", false, &["Room"], &[]),
],
anonymous: vec![object(
"",
false,
&["Choice"],
&[("label", "'Read'"), ("location", "studyMoment")],
)],
..Default::default()
};
let found = rooms("true");
let problems = Site::new(&found, true).choice_problems();
assert_eq!(problems.len(), 1, "{problems:?}");
assert!(problems[0].starts_with("cellar: in a choice game, a room with no exits"));
let parser = rooms("nil");
assert!(Site::new(&parser, true).choice_problems().is_empty());
}
#[test]
fn the_choices_page_maps_each_moment_and_where_its_choices_lead() {
use hexicon_compiler::{DocObject, DocPlace};
let object =
|name: &str, is_class, superclasses: &[&str], line, values: &[(&str, &str)]| {
DocObject {
name: name.to_owned(),
is_class,
superclasses: superclasses.iter().map(|s| (*s).to_owned()).collect(),
place: DocPlace {
file: "gorge.hxn".to_owned(),
line,
},
comment: String::new(),
modified_in: Vec::new(),
members: Vec::new(),
from_library: !name.is_empty() && is_class,
values: values
.iter()
.map(|(p, v)| ((*p).to_owned(), (*v).to_owned()))
.collect(),
}
};
let documented = hexicon_compiler::Documented {
objects: vec![
object("ChoiceMoment", true, &["object"], 1, &[]),
object("Choice", true, &["object"], 2, &[]),
object("snap", false, &["ChoiceMoment"], 10, &[]),
object(
"sway",
false,
&["ChoiceMoment"],
20,
&[("allowCommands", "true")],
),
object("ActionChoice", true, &["Choice"], 3, &[]),
object("lamp", false, &["Thing"], 30, &[]),
],
anonymous: vec![
object(
"",
false,
&["ActionChoice"],
31,
&[
("label", "'Light it'"),
("action", "Light"),
("location", "lamp"),
],
),
object(
"",
false,
&["Choice"],
11,
&[
("label", "'Grab it'"),
("leadsTo", "sway"),
("location", "snap"),
],
),
object(
"",
false,
&["Choice"],
12,
&[
("label", "'Shout'"),
("isOnce", "nil"),
("location", "snap"),
],
),
object(
"",
false,
&["Choice"],
21,
&[
("label", "'Crawl on'"),
("leadsTo", "nil"),
("location", "sway"),
],
),
],
..Default::default()
};
let site = Site::new(&documented, true);
let map = site.choices_index("A game");
assert!(map.contains("id=\"snap\"") && map.contains("id=\"sway\""));
assert!(map.find("Grab it") < map.find("Shout"));
assert!(map.contains("<td>Grab it</td><td><a href=\"#sway\">sway</a></td>"));
assert!(map.contains("<td>Shout</td><td><span class=\"from\">back to this moment</span>"));
assert!(map.contains("as often as chosen"));
assert!(map.contains("<td>Crawl on</td><td><span class=\"from\">ends the moment</span>"));
assert!(map.contains("Led to from: <a href=\"#snap\">snap</a>: Grab it."));
assert!(map.contains("nothing here; the game's code begins it."));
assert!(map.contains("a command ends it"));
assert!(map.contains("<h2>Things' choices</h2>"));
assert!(map.contains(
"<td>Light it</td><td><span class=\"from\">the command</span> <code>Light lamp</code>"
));
assert!(site.index("A game").contains("choices.html"));
let none = hexicon_compiler::Documented::default();
assert!(
!Site::new(&none, true)
.index("A game")
.contains("choices.html")
);
}
#[test]
fn an_unknown_library_is_said_to_be_unknown() {
assert!(library_reference("no-such-library", &[], &[], "").is_err());
}
#[test]
fn an_extension_is_named_as_a_manifest_includes_it() {
assert_eq!(
extension_name("<hexicon>/hexad/extensions/rules.hxn").as_deref(),
Some("extensions/rules")
);
assert_eq!(extension_name("<hexicon>/hexad/thing.hxn"), None);
assert_eq!(extension_name("<hexicon>/hexad/myextensions/x.hxn"), None);
}
#[test]
fn a_files_first_comment_is_what_it_is_about() {
let lines: Vec<String> = [
"import hexad;",
"/* include the library header */",
"/*",
" * ************************ rules.hxn",
" * RULES EXTENSION",
" *. Version 1.0 23-Apr-24",
" *",
" * Rules and rulebooks, as a",
" * game defines them.",
" *",
" * A second paragraph.",
" */",
"class RuleBook: object;",
]
.iter()
.map(|s| (*s).to_owned())
.collect();
assert_eq!(
file_comment(&lines),
"Rules and rulebooks, as a game defines them.\n\nA second paragraph."
);
let lines: Vec<String> = ["/*", " * COLLECTIVE EXTENSION", " */"]
.iter()
.map(|s| (*s).to_owned())
.collect();
assert_eq!(file_comment(&lines), "COLLECTIVE EXTENSION");
}
#[test]
fn a_file_is_shown_from_the_game_folder_reached_through_a_link() {
let dir = std::env::temp_dir().join(format!("hexicon-shown-{}", std::process::id()));
let game = dir.join("game");
std::fs::create_dir_all(&game).unwrap();
std::fs::write(game.join("start.hxn"), "").unwrap();
let link = dir.join("link");
#[cfg(unix)]
std::os::unix::fs::symlink(&game, &link).unwrap();
#[cfg(windows)]
std::os::windows::fs::symlink_dir(&game, &link).unwrap();
let resolved = std::fs::canonicalize(&game).unwrap();
let through = link.join("start.hxn").to_string_lossy().into_owned();
let direct = game.join("start.hxn").to_string_lossy().into_owned();
assert_eq!(shown_from(&through, Some(&resolved)), "start.hxn");
assert_eq!(shown_from(&direct, Some(&link)), "start.hxn");
assert_eq!(
shown_from("<hexicon>/hexad/thing.hxn", Some(&resolved)),
"hexad/thing.hxn"
);
std::fs::remove_dir_all(&dir).unwrap();
}
}