use std::collections::HashSet;
use crate::pp::{Diagnostic, Severity};
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct TagUse {
pub(crate) name: String,
pub(crate) line: u32,
pub(crate) arg: Option<String>,
}
pub(crate) fn tags_in_strings(text: &str) -> Vec<TagUse> {
let bytes = text.as_bytes();
let mut found = Vec::new();
let mut line = 1u32;
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'\n' => {
line += 1;
i += 1;
}
b'/' if bytes.get(i + 1) == Some(&b'/') => {
while i < bytes.len() && bytes[i] != b'\n' {
i += 1;
}
}
b'/' if bytes.get(i + 1) == Some(&b'*') => {
i += 2;
while i < bytes.len() && !(bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/')) {
if bytes[i] == b'\n' {
line += 1;
}
i += 1;
}
i += 2;
}
quote @ (b'"' | b'\'') => {
i = string(bytes, i, quote, &mut line, &mut found);
}
_ => i += 1,
}
}
found
}
fn string(bytes: &[u8], start: usize, quote: u8, line: &mut u32, found: &mut Vec<TagUse>) -> usize {
let triple = bytes.get(start + 1) == Some("e) && bytes.get(start + 2) == Some("e);
let mut i = start + if triple { 3 } else { 1 };
while i < bytes.len() {
let c = bytes[i];
if c == b'\\' {
if bytes.get(i + 1) == Some(&b'\n') {
*line += 1;
}
i += 2;
continue;
}
if c == b'\n' {
*line += 1;
}
if c == quote {
if !triple {
return i + 1;
}
if bytes.get(i + 1) == Some("e) && bytes.get(i + 2) == Some("e) {
return i + 3;
}
}
if c == b'<' && bytes.get(i + 1) == Some(&b'<') {
i += 2;
while i < bytes.len() && !(bytes[i] == b'>' && bytes.get(i + 1) == Some(&b'>')) {
match bytes[i] {
b'\n' => {
*line += 1;
i += 1;
}
q @ (b'"' | b'\'') => i = string(bytes, i, q, line, found),
_ => i += 1,
}
}
i += 2;
continue;
}
if c == b'<' && bytes.get(i + 1) == Some(&b'.') {
let mut j = i + 2;
if bytes.get(j) == Some(&b'/') {
j += 1;
}
let name_start = j;
while j < bytes.len() && bytes[j].is_ascii_alphanumeric() {
j += 1;
}
if j > name_start && bytes[name_start].is_ascii_alphabetic() {
found.push(TagUse {
name: String::from_utf8_lossy(&bytes[name_start..j]).to_ascii_lowercase(),
line: *line,
arg: argument(bytes, j, quote),
});
}
i = j;
continue;
}
i += 1;
}
i
}
fn argument(bytes: &[u8], from: usize, quote: u8) -> Option<String> {
if !bytes.get(from).is_some_and(|c| *c == b' ' || *c == b'\t') {
return None;
}
let mut k = from;
while k < bytes.len() {
match bytes[k] {
b'>' => {
let arg = String::from_utf8_lossy(&bytes[from..k]).trim().to_owned();
return (!arg.is_empty()).then_some(arg);
}
b'<' if bytes.get(k + 1) == Some(&b'<') => return None,
b'\n' | b'\\' => return None,
c if c == quote => return None,
_ => k += 1,
}
}
None
}
pub(crate) fn tags_defined(text: &str) -> Vec<String> {
let mut out = Vec::new();
let quoted_after = |rest: &str| -> Option<String> {
let rest = rest.trim_start();
let rest = rest.strip_prefix('\'')?;
let end = rest.find('\'')?;
Some(rest[..end].to_owned())
};
for line in text.lines() {
let mut rest = line;
while let Some(at) = rest.find("StyleTag") {
let after = &rest[at + "StyleTag".len()..];
if let Some(name) = quoted_after(after) {
out.push(name.to_ascii_lowercase());
}
rest = after;
}
for key in ["tagName", "customTags"] {
if let Some(at) = line.find(key) {
let after = line[at + key.len()..].trim_start();
if let Some(after) = after.strip_prefix('=')
&& let Some(value) = quoted_after(after)
{
out.extend(value.split('|').map(|n| n.trim().to_ascii_lowercase()));
}
}
}
}
out
}
fn slip(a: &str, b: &str) -> bool {
crate::names::is_slip(a.as_bytes(), b.as_bytes())
}
pub(crate) fn check(file: &str, text: &str, known: &HashSet<String>) -> Vec<Diagnostic> {
let mut sorted: Vec<&String> = known.iter().collect();
sorted.sort();
let mut out: Vec<Diagnostic> = Vec::new();
for tag in tags_in_strings(text) {
if known.contains(&tag.name) {
continue;
}
let note = match sorted.iter().find(|k| slip(&tag.name, k)) {
Some(meant) => format!("did you mean \"<.{meant}>\"?"),
None => "a tag is one the library defines, or a StyleTag a source makes".to_owned(),
};
let message = format!(
"\"<.{}>\" is not a tag: nothing defines it, so it is dropped from the text",
tag.name
);
if !out
.iter()
.any(|d| d.line == tag.line && d.message == message)
{
out.push(Diagnostic {
file: file.to_owned(),
line: tag.line,
severity: Severity::Warning,
message,
note: Some(note),
hexicon: true,
..Default::default()
});
}
}
out
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct StringKey {
pub(crate) of: String,
pub(crate) key: String,
pub(crate) line: u32,
}
pub(crate) fn string_keys(text: &str, keys: &[String]) -> Vec<StringKey> {
let bytes = text.as_bytes();
let mut found = Vec::new();
let mut line = 1u32;
let mut ignored = Vec::new();
let ident = |c: u8| c.is_ascii_alphanumeric() || c == b'_';
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'\n' => {
line += 1;
i += 1;
}
b'/' if bytes.get(i + 1) == Some(&b'/') => {
while i < bytes.len() && bytes[i] != b'\n' {
i += 1;
}
}
b'/' if bytes.get(i + 1) == Some(&b'*') => {
i += 2;
while i < bytes.len() && !(bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/')) {
if bytes[i] == b'\n' {
line += 1;
}
i += 1;
}
i += 2;
}
quote @ (b'"' | b'\'') => {
i = string(bytes, i, quote, &mut line, &mut ignored);
}
c if ident(c) && (i == 0 || !ident(bytes[i - 1])) => {
let start = i;
while i < bytes.len() && ident(bytes[i]) {
i += 1;
}
let word = &text[start..i];
if !keys.iter().any(|k| k == word) {
continue;
}
let mut k = i;
while k < bytes.len() && (bytes[k] == b' ' || bytes[k] == b'\t') {
k += 1;
}
if matches!(bytes.get(k), Some(b'(') | Some(b'=')) {
k += 1;
while k < bytes.len() && matches!(bytes[k], b' ' | b'\t' | b'=') {
k += 1;
}
}
if let Some(&q @ (b'\'' | b'"')) = bytes.get(k)
&& let Some(len) = text[k + 1..].find(q as char)
{
found.push(StringKey {
of: word.to_owned(),
key: text[k + 1..k + 1 + len].to_owned(),
line,
});
}
}
_ => i += 1,
}
}
found
}
pub(crate) fn object_name(key: &str) -> String {
let mut out = String::new();
for word in key
.split(|c: char| !c.is_ascii_alphanumeric())
.filter(|w| !w.is_empty())
{
let mut chars = word.chars();
let first = chars.next().expect("a word");
if out.is_empty() {
out.push(first.to_ascii_lowercase());
} else {
out.push(first.to_ascii_uppercase());
}
out.extend(chars);
}
if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) {
out.insert_str(0, "key");
}
out
}
fn is_identifier(name: &str) -> bool {
name.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}
fn declaration(name: &str, node: bool) -> String {
if node {
format!("{name}: ConvNode")
} else {
format!("{name}: Fact")
}
}
pub(crate) fn check_objects(
file: &str,
text: &str,
tag_names: &HashSet<String>,
keys: &[String],
objects: &HashSet<&[u8]>,
) -> Vec<Diagnostic> {
let error = |line: u32, message: String, note: String| Diagnostic {
file: file.to_owned(),
line,
severity: Severity::Error,
message,
note: Some(note),
hexicon: true,
..Default::default()
};
let mut sorted: Vec<&[u8]> = objects.iter().copied().collect();
sorted.sort_unstable();
let mut out: Vec<Diagnostic> = Vec::new();
for tag in tags_in_strings(text) {
let Some(arg) = &tag.arg else { continue };
if !tag_names.contains(&tag.name) {
continue;
}
let name = arg.split('=').next().unwrap_or("").trim();
if name.is_empty() || objects.contains(name.as_bytes()) {
continue;
}
let node = tag.name.starts_with("convnode");
let note = if let Some(meant) = sorted
.iter()
.find(|o| crate::names::is_slip(name.as_bytes(), o))
{
format!("did you mean \"{}\"?", String::from_utf8_lossy(meant))
} else if is_identifier(name) {
format!(
"a <.{}> tag names an object: declare it once ({}), or name a thing or a topic",
tag.name,
declaration(name, node)
)
} else {
let named = object_name(name) + if node { "Node" } else { "" };
format!(
"a <.{}> tag names an object, not a string: declare it once ({}) and write <.{} {}>",
tag.name,
declaration(&named, node),
tag.name,
named
)
};
let message = format!("\"{name}\" in <.{} {arg}> is no object's name", tag.name);
if !out
.iter()
.any(|d| d.line == tag.line && d.message == message)
{
out.push(error(tag.line, message, note));
}
}
for key in string_keys(text, keys) {
let node = key.of == "ConvNode";
let named = object_name(&key.key) + if node { "Node" } else { "" };
let (message, note) = if node {
(
format!(
"a conversation node is named as an object, not by the string '{}'",
key.key
),
format!(
"write {} (and <.convnode {named}>)",
declaration(&named, true)
),
)
} else {
(
format!("the key '{}' is a string, and a key is an object", key.key),
format!(
"declare it once ({}), or name a thing or a topic, and write {} here",
declaration(&named, false),
named
),
)
};
out.push(error(key.line, message, note));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_tags_in_strings_and_not_in_comments() {
let text = "// <.notme>\n\
a = \"one<.p>two\";\n\
/* <.notme> */ b = 'x<./parser>';\n\
c = '<<x ? 'on<.inner>' : 'off'>> <.after>';\n";
let names: Vec<(String, u32)> = tags_in_strings(text)
.into_iter()
.map(|t| (t.name, t.line))
.collect();
assert_eq!(
names,
[
("p".to_owned(), 2),
("parser".to_owned(), 3),
("inner".to_owned(), 4),
("after".to_owned(), 4),
]
);
}
#[test]
fn the_tags_a_source_defines() {
let text = "roomnameStyleTag: HtmlStyleTag 'roomname';\n\
tipStyleTag: StyleTag 'Tip' '' '';\n\
myTag: StyleTag\n tagName = 'mine'\n;\n\
modify conversationManager customTags = 'foo|bar';\n";
assert_eq!(
tags_defined(text),
["roomname", "tip", "mine", "foo", "bar"]
);
}
#[test]
fn hexad_writes_only_the_tags_it_defines() {
let manifest = crate::builtin::FILES
.iter()
.find(|(path, _)| *path == "hexad/hexicon.toml")
.expect("Hexad's manifest");
let library = crate::manifest::library(manifest.1).expect("a library");
let sources: Vec<(&str, String)> = crate::builtin::FILES
.iter()
.filter(|(path, _)| {
path.starts_with("hexad/") && (path.ends_with(".hxn") || path.ends_with(".hxh"))
})
.map(|(path, bytes)| (*path, String::from_utf8_lossy(bytes).into_owned()))
.collect();
let mut known: HashSet<String> = library.text_tags.iter().cloned().collect();
for (_, text) in &sources {
known.extend(tags_defined(text));
}
let mut problems = Vec::new();
for (path, text) in &sources {
for warning in check(path, text, &known) {
problems.push(format!("{}:{}: {}", path, warning.line, warning.message));
}
}
assert!(problems.is_empty(), "{problems:#?}");
}
#[test]
fn a_misspelled_tag_is_said_with_what_was_meant() {
let known: HashSet<String> = ["p", "reveal"].iter().map(|s| s.to_string()).collect();
let warnings = check("start.hxn", "x = 'a<.reveel key> b<.P> c<.zzz>';\n", &known);
let said: Vec<(&str, Option<&str>)> = warnings
.iter()
.map(|d| (d.message.as_str(), d.note.as_deref()))
.collect();
assert_eq!(
said,
[
(
"\"<.reveel>\" is not a tag: nothing defines it, so it is dropped from the text",
Some("did you mean \"<.reveal>\"?")
),
(
"\"<.zzz>\" is not a tag: nothing defines it, so it is dropped from the text",
Some("a tag is one the library defines, or a StyleTag a source makes")
),
]
);
}
#[test]
fn a_tag_names_an_object_or_is_an_error() {
let tags: HashSet<String> = ["reveal", "convnode"]
.iter()
.map(|s| s.to_string())
.collect();
let objects: HashSet<&[u8]> = [b"pilotAwaited".as_slice(), b"troublesNode".as_slice()]
.into_iter()
.collect();
let text = "a = '<.reveal pilotAwaited><.reveal pilotAwaitd><.convnode troubles>';\n\
b = '<.reveal new-enlightenment> <.reveal <<k>>> <.reveal mood=angry>';\n";
let said: Vec<(u32, String, String)> =
check_objects("start.hxn", text, &tags, &[], &objects)
.into_iter()
.map(|d| (d.line, d.message, d.note.unwrap_or_default()))
.collect();
assert_eq!(
said,
[
(
1,
"\"pilotAwaitd\" in <.reveal pilotAwaitd> is no object's name".to_owned(),
"did you mean \"pilotAwaited\"?".to_owned()
),
(
1,
"\"troubles\" in <.convnode troubles> is no object's name".to_owned(),
"a <.convnode> tag names an object: declare it once (troubles: ConvNode), \
or name a thing or a topic"
.to_owned()
),
(
2,
"\"new-enlightenment\" in <.reveal new-enlightenment> is no object's name"
.to_owned(),
"a <.reveal> tag names an object, not a string: declare it once \
(newEnlightenment: Fact) and write <.reveal newEnlightenment>"
.to_owned()
),
(
2,
"\"mood\" in <.reveal mood=angry> is no object's name".to_owned(),
"a <.reveal> tag names an object: declare it once (mood: Fact), \
or name a thing or a topic"
.to_owned()
),
]
);
}
#[test]
fn a_string_where_a_key_is_an_object_is_an_error() {
let keys: Vec<String> = ["revealed", "openWhenRevealed", "ConvNode"]
.iter()
.map(|s| s.to_string())
.collect();
let text = "// now.revealed('in-a-comment')\n\
isActive = now.revealed('pilot-awaited') && now.revealed(island)\n\
openWhenRevealed = 'blue door open'\n\
+ ConvNode 'troubles';\n\
x = 'now.revealed(\\'in-a-string\\')';\n";
let found: Vec<(String, String, u32)> = string_keys(text, &keys)
.into_iter()
.map(|k| (k.of, k.key, k.line))
.collect();
assert_eq!(
found,
[
("revealed".to_owned(), "pilot-awaited".to_owned(), 2),
(
"openWhenRevealed".to_owned(),
"blue door open".to_owned(),
3
),
("ConvNode".to_owned(), "troubles".to_owned(), 4),
]
);
assert_eq!(object_name("blue door open"), "blueDoorOpen");
assert_eq!(object_name("DeskTried"), "deskTried");
assert_eq!(object_name("2nd-try"), "key2ndTry");
}
#[test]
fn hexad_writes_no_key_as_a_string() {
let manifest = crate::builtin::FILES
.iter()
.find(|(path, _)| *path == "hexad/hexicon.toml")
.expect("Hexad's manifest");
let library = crate::manifest::library(manifest.1).expect("a library");
assert!(!library.object_keys.is_empty());
let mut problems = Vec::new();
for (path, bytes) in crate::builtin::FILES {
if path.starts_with("hexad/") && (path.ends_with(".hxn") || path.ends_with(".hxh")) {
let text = String::from_utf8_lossy(bytes);
for key in string_keys(&text, &library.object_keys) {
problems.push(format!("{path}:{}: {} '{}'", key.line, key.of, key.key));
}
}
}
assert!(problems.is_empty(), "{problems:#?}");
}
}