use toml::{Table, Value};
pub const MANIFEST: &str = "hexicon.toml";
pub(crate) fn is_manifest(path: &str) -> bool {
path.len() >= 5 && path[path.len() - 5..].eq_ignore_ascii_case(".toml")
}
pub(crate) fn source_name(name: &str) -> String {
let file = name.rsplit(['/', '\\']).next().unwrap_or(name);
if file.contains('.') {
name.to_owned()
} else {
format!("{name}.hxn")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ModuleRef {
Source(String),
Library {
name: String,
exclude: Vec<String>,
include: Vec<String>,
},
}
#[derive(Debug, Default)]
pub(crate) struct Library {
pub modules: Vec<ModuleRef>,
pub resources: Vec<String>,
pub needs: Vec<(String, String)>,
pub header: Option<String>,
pub text_tags: Vec<String>,
pub object_tags: Vec<String>,
pub object_keys: Vec<String>,
}
struct Section<'t> {
table: &'t Table,
name: &'static str,
}
impl Section<'_> {
fn check_keys(&self, known: &[&str]) -> Result<(), String> {
for key in self.table.keys() {
if !known.contains(&key.as_str()) {
return Err(format!("unknown key \"{key}\" in [{}]", self.name));
}
}
Ok(())
}
fn string(&self, key: &str) -> Result<Option<String>, String> {
match self.table.get(key) {
None => Ok(None),
Some(Value::String(s)) => Ok(Some(s.clone())),
Some(_) => Err(format!("\"{key}\" in [{}] must be a string", self.name)),
}
}
fn boolean(&self, key: &str) -> Result<Option<bool>, String> {
match self.table.get(key) {
None => Ok(None),
Some(Value::Boolean(b)) => Ok(Some(*b)),
Some(_) => Err(format!(
"\"{key}\" in [{}] must be true or false",
self.name
)),
}
}
fn strings(&self, key: &str) -> Result<Vec<String>, String> {
match self.table.get(key) {
None => Ok(Vec::new()),
Some(Value::Array(items)) => items
.iter()
.map(|item| match item {
Value::String(s) => Ok(s.clone()),
_ => Err(self.not_strings(key)),
})
.collect(),
Some(_) => Err(self.not_strings(key)),
}
}
fn not_strings(&self, key: &str) -> String {
format!("\"{key}\" in [{}] must be a list of strings", self.name)
}
}
fn parse(text: &[u8]) -> Result<Table, String> {
let text = std::str::from_utf8(text).map_err(|_| "the manifest is not UTF-8".to_owned())?;
text.parse::<Table>()
.map_err(|error| error.to_string().trim_end().to_owned())
}
fn section<'t>(top: &'t Table, name: &'static str) -> Result<Option<Section<'t>>, String> {
match top.get(name) {
None => Ok(None),
Some(Value::Table(table)) => Ok(Some(Section { table, name })),
Some(_) => Err(format!("\"{name}\" must be a table ([{name}])")),
}
}
fn module_refs(sec: &Section<'_>, libraries_first: bool) -> Result<Vec<ModuleRef>, String> {
let name = sec.name;
let library = |table: &Table, key: &str| -> Result<ModuleRef, String> {
let lib = Section {
table,
name: "a library",
};
lib.check_keys(&[key, "exclude", "include"])?;
let lib_name = lib
.string(key)?
.ok_or_else(|| format!("a library given as a table needs a \"{key}\""))?;
Ok(ModuleRef::Library {
name: lib_name,
exclude: lib.strings("exclude")?,
include: lib.strings("include")?,
})
};
if let Some(value) = sec.table.get("modules") {
if sec.table.contains_key("sources") || sec.table.contains_key("libraries") {
return Err(format!(
"[{name}] has \"modules\", so it cannot also have \"sources\" or \"libraries\""
));
}
let bad = || {
format!(
"\"modules\" in [{name}] must be a list of sources, and of tables with a \"library\""
)
};
let Value::Array(items) = value else {
return Err(bad());
};
return items
.iter()
.map(|item| match item {
Value::String(source) => Ok(ModuleRef::Source(source.clone())),
Value::Table(table) => library(table, "library"),
_ => Err(bad()),
})
.collect();
}
let mut libraries = Vec::new();
match sec.table.get("libraries") {
None => {}
Some(Value::Array(items)) => {
for item in items {
libraries.push(match item {
Value::String(lib_name) => ModuleRef::Library {
name: lib_name.clone(),
exclude: Vec::new(),
include: Vec::new(),
},
Value::Table(table) => library(table, "name")?,
_ => return Err(bad_libraries(name)),
});
}
}
Some(_) => return Err(bad_libraries(name)),
}
let sources = sec.strings("sources")?.into_iter().map(ModuleRef::Source);
Ok(if libraries_first {
libraries.into_iter().chain(sources).collect()
} else {
sources.chain(libraries).collect()
})
}
fn check_sections(top: &Table, known: &[&str]) -> Result<(), String> {
for key in top.keys() {
if !known.contains(&key.as_str()) {
return Err(format!("unknown section [{key}]"));
}
}
Ok(())
}
pub(crate) fn game_args(text: &[u8]) -> Result<Vec<String>, String> {
let top = parse(text)?;
if top.contains_key("library") {
return Err("this is the manifest of a library, not of a game".to_owned());
}
check_sections(&top, &["game", "defines", "build"])?;
let game = section(&top, "game")?.ok_or("there is no [game] section")?;
game.check_keys(&[
"name",
"sources",
"libraries",
"modules",
"tests",
"image",
"resources",
"stylesheets",
])?;
let mut args: Vec<String> = Vec::new();
let mut push = |items: &[&str]| args.extend(items.iter().map(|&s| s.to_owned()));
if let Some(build) = section(&top, "build")? {
build.check_keys(&[
"preinit",
"debug",
"warnings",
"warnings-as-errors",
"verbose",
"charset",
"include-paths",
"library-paths",
"source-text-group",
"system",
])?;
if build.boolean("system")? == Some(false) {
push(&["--no-system"]);
}
if build.boolean("debug")? == Some(true) {
push(&["-d"]);
}
match build.boolean("preinit")? {
Some(true) => push(&["--preinit"]),
Some(false) => push(&["--no-preinit"]),
None => {}
}
if build.boolean("warnings")? == Some(false) {
push(&["--no-warnings"]);
}
if build.boolean("warnings-as-errors")? == Some(true) {
push(&["--warnings-as-errors"]);
}
if build.boolean("verbose")? == Some(true) {
push(&["-v"]);
}
if build.boolean("source-text-group")? == Some(true) {
push(&["--source-text-groups"]);
}
if let Some(charset) = build.string("charset")? {
push(&["--charset", &charset]);
}
for path in build.strings("include-paths")? {
push(&["-I", &path]);
}
for path in build.strings("library-paths")? {
push(&["--library-path", &path]);
}
}
if let Some(defines) = section(&top, "defines")? {
for (name, value) in defines.table {
match value {
Value::String(s) => push(&["-D", &format!("{name}={s}")]),
Value::Integer(n) => push(&["-D", &format!("{name}={n}")]),
Value::Boolean(true) => push(&["-D", name]),
Value::Boolean(false) => push(&["-U", name]),
_ => {
return Err(format!(
"\"{name}\" in [defines] must be a string, a number, or true or false"
));
}
}
}
}
if let Some(image) = game.string("image")? {
push(&["-o", &image]);
}
let _ = game.string("name")?;
let modules = module_refs(&game, true)?;
if !modules
.iter()
.any(|module| matches!(module, ModuleRef::Source(_)))
{
return Err("[game] names no sources".to_owned());
}
for module in modules {
match module {
ModuleRef::Source(source) => push(&["--source", &source]),
ModuleRef::Library {
name,
exclude,
include,
} => {
push(&["--library", &name]);
for module in exclude {
push(&["--exclude", &module]);
}
for module in include {
push(&["--include", &module]);
}
}
}
}
for test in game.strings("tests")? {
push(&["--test", &test]);
}
let mut resources = game.strings("resources")?;
resources.extend(game.strings("stylesheets")?);
if !resources.is_empty() {
push(&["--resources"]);
for resource in resources {
push(&[&resource]);
}
}
Ok(args)
}
fn bad_libraries(section: &str) -> String {
format!("\"libraries\" in [{section}] must be a list of names, or of tables with a \"name\"")
}
pub(crate) fn library(text: &[u8]) -> Result<Library, String> {
let top = parse(text)?;
if top.contains_key("game") {
return Err("this is the manifest of a game, not of a library".to_owned());
}
check_sections(&top, &["library", "needs"])?;
let lib = section(&top, "library")?.ok_or("there is no [library] section")?;
lib.check_keys(&[
"name",
"sources",
"libraries",
"modules",
"resources",
"header",
"text-tags",
"object-tags",
"object-keys",
])?;
let _ = lib.string("name")?;
let mut needs = Vec::new();
if let Some(section) = section(&top, "needs")? {
for key in section.table.keys() {
let why = section.string(key)?.unwrap_or_default();
needs.push((key.clone(), why));
}
}
let modules = module_refs(&lib, false)?;
if modules
.iter()
.any(|module| matches!(module, ModuleRef::Library { exclude, include, .. } if !exclude.is_empty() || !include.is_empty()))
{
return Err(
"a library cannot leave out or add to the sources of the libraries it names".to_owned(),
);
}
Ok(Library {
modules,
resources: lib.strings("resources")?,
needs,
header: lib.string("header")?,
text_tags: lib.strings("text-tags")?,
object_tags: lib.strings("object-tags")?,
object_keys: lib.strings("object-keys")?,
})
}