use std::fmt;
use serde::de::{Error as _, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer};
use serde_json::Value;
use techy::latexlike::Mode;
use crate::lang::mint::decl::{ArgDef, ArgLayout, TackOnField};
use crate::lang::mint::parsers::ArgStdKind;
use crate::model::names::Name;
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(untagged)]
pub enum ArgData {
Code(#[schemars(schema_with = "arg_code_schema")] String),
Declared(ArgDataFields),
}
impl<'de> Deserialize<'de> for ArgData {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<ArgData, D::Error> {
struct Entry;
impl<'de> Visitor<'de> for Entry {
type Value = ArgData;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("an argument code or a map")
}
fn visit_str<E: serde::de::Error>(self, code: &str) -> Result<ArgData, E> {
Ok(ArgData::Code(code.to_string()))
}
fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<ArgData, A::Error> {
ArgDataFields::deserialize(serde::de::value::MapAccessDeserializer::new(map))
.map(ArgData::Declared)
}
}
deserializer.deserialize_any(Entry)
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[schemars(transform = arg_map_schema)]
pub struct ArgDataFields {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(schema_with = "arg_code_schema")]
pub code: Option<String>,
#[serde(flatten, deserialize_with = "deserialize_syntax")]
#[schemars(schema_with = "syntax_schema")]
pub syntax: Option<ArgStdKind>,
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub layout: ArgLayout,
#[serde(default)]
pub opaque_wrapper: bool,
#[serde(default)]
pub docs: String,
#[serde(default)]
#[schemars(schema_with = "mode_schema")]
pub mode: Option<Mode>,
#[serde(default)]
pub scoped: Vec<Name>,
#[serde(default)]
pub role: Option<Name>,
}
impl From<&ArgDef> for ArgDataFields {
fn from(arg: &ArgDef) -> ArgDataFields {
let code = arg.code().map(str::to_string);
let syntax = match (&code, arg.kind.std_kind()) {
(None, Some(kind)) => Some(kind.clone()),
_ => None,
};
ArgDataFields {
code,
syntax,
name: arg.name.clone(),
layout: arg.layout,
opaque_wrapper: arg.opaque_wrapper,
docs: arg.docs.clone(),
mode: arg.mode,
scoped: arg.scoped.clone(),
role: arg.role.clone(),
}
}
}
impl TryFrom<ArgData> for ArgDef {
type Error = ArgDataError;
fn try_from(data: ArgData) -> Result<ArgDef, ArgDataError> {
match data {
ArgData::Code(code) => Ok(arg_def_from_code(&code)?),
ArgData::Declared(fields) => {
let arg = match (fields.code, fields.syntax) {
(Some(code), None) => arg_def_from_code(&code)?,
(None, Some(kind)) => ArgDef::new(kind),
(Some(_), Some(_)) => return Err(ArgDataError::BothCodeAndSyntax),
(None, None) => return Err(ArgDataError::NeitherCodeNorSyntax),
};
let mut arg = arg.layout(fields.layout).docs(fields.docs);
arg.name = fields.name;
arg.opaque_wrapper = fields.opaque_wrapper;
arg.mode = fields.mode;
arg.scoped = fields.scoped;
arg.role = fields.role;
Ok(arg)
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ArgDataError {
Code(ArgCodeError),
BothCodeAndSyntax,
NeitherCodeNorSyntax,
}
impl From<ArgCodeError> for ArgDataError {
fn from(error: ArgCodeError) -> ArgDataError {
ArgDataError::Code(error)
}
}
impl fmt::Display for ArgDataError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ArgDataError::Code(error) => fmt::Display::fmt(error, f),
ArgDataError::BothCodeAndSyntax => f.write_str(
"an argument written as a map must hold exactly one of the keys `code` and `syntax`, \
and this one holds both",
),
ArgDataError::NeitherCodeNorSyntax => f.write_str(
"an argument written as a map must hold the key `code` or the key `syntax`, which \
gives its syntax",
),
}
}
}
impl std::error::Error for ArgDataError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
ArgDataError::Code(error) => Some(error),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArgListError {
pub index: usize,
pub error: ArgDataError,
}
impl fmt::Display for ArgListError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "argument {}: {}", self.index + 1, self.error)
}
}
impl std::error::Error for ArgListError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.error)
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(untagged)]
pub enum ArgListData {
Codes(#[schemars(schema_with = "arg_codes_text_schema")] String),
List(Vec<ArgData>),
}
impl<'de> Deserialize<'de> for ArgListData {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<ArgListData, D::Error> {
struct List;
impl<'de> Visitor<'de> for List {
type Value = ArgListData;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(LIST_EXPECTED)
}
fn visit_str<E: serde::de::Error>(self, codes: &str) -> Result<ArgListData, E> {
Ok(ArgListData::Codes(codes.to_string()))
}
fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<ArgListData, A::Error> {
entries(seq).map(ArgListData::List)
}
}
deserializer.deserialize_any(List)
}
}
impl ArgListData {
pub fn arg_defs(self) -> Result<Vec<ArgDef>, ArgListError> {
match self {
ArgListData::Codes(codes) => codes
.chars()
.enumerate()
.map(|(index, code)| {
arg_def_from_code(&String::from(code)).map_err(|error| ArgListError { index, error: error.into() })
})
.collect(),
ArgListData::List(args) => args
.into_iter()
.enumerate()
.map(|(index, arg)| ArgDef::try_from(arg).map_err(|error| ArgListError { index, error }))
.collect(),
}
}
}
const LIST_EXPECTED: &str = "a text of argument codes or a list of arguments";
fn entries<'de, A: SeqAccess<'de>, T: Deserialize<'de>>(mut seq: A) -> Result<Vec<T>, A::Error> {
let mut entries = Vec::new();
while let Some(entry) = seq.next_element()? {
entries.push(entry);
}
Ok(entries)
}
pub fn deserialize_arg_list<'de, D>(deserializer: D) -> Result<Vec<ArgDef>, D::Error>
where
D: Deserializer<'de>,
{
struct Args;
impl<'de> Visitor<'de> for Args {
type Value = Vec<ArgDef>;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(LIST_EXPECTED)
}
fn visit_str<E: serde::de::Error>(self, codes: &str) -> Result<Vec<ArgDef>, E> {
ArgListData::Codes(codes.to_string()).arg_defs().map_err(E::custom)
}
fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<Vec<ArgDef>, A::Error> {
entries(seq)
}
}
deserializer.deserialize_any(Args)
}
#[derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
#[serde(tag = "syntax", rename_all = "kebab-case", deny_unknown_fields)]
pub(crate) enum ArgStdKindData {
Mandatory {},
Optional {},
Star {},
Marker {
#[schemars(pattern(CHARACTERS))]
marker: String,
},
DelimitedGroup {
#[schemars(length(equal = 2), inner(pattern(ONE_CHARACTER)))]
delimiters: Vec<String>,
},
OptionalDelimitedGroup {
#[schemars(length(equal = 2), inner(pattern(ONE_CHARACTER)))]
delimiters: Vec<String>,
},
AnyDelimitedGroup {},
OptionalAnyDelimitedGroup {},
BracedOnly {},
Embellishments {
#[schemars(length(min = 1), inner(pattern(ONE_CHARACTER)))]
markers: Vec<String>,
},
KeyVals {},
CharsGroup {},
Verbatim {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(length(equal = 2), inner(pattern(ONE_CHARACTER)))]
delimiters: Option<Vec<String>>,
},
TackOn {
fields: Vec<TackOnFieldData>,
},
Terminated {
terminator: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(pattern(ONE_CHARACTER))]
repeat_char: Option<String>,
#[serde(default)]
opener: String,
#[serde(default)]
head: String,
#[serde(default)]
raw: bool,
},
}
#[derive(serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct TackOnFieldData {
name: String,
#[serde(default = "no_arguments")]
args: ArgListData,
#[serde(default)]
repeatable: bool,
#[serde(default)]
docs: String,
}
fn no_arguments() -> ArgListData {
ArgListData::List(Vec::new())
}
const ONE_CHARACTER: &str = r"^\S$";
const CHARACTERS: &str = r"^\S+$";
impl From<ArgStdKind> for ArgStdKindData {
fn from(kind: ArgStdKind) -> ArgStdKindData {
let pair = |open: char, close: char| vec![String::from(open), String::from(close)];
match kind {
ArgStdKind::Mandatory => ArgStdKindData::Mandatory {},
ArgStdKind::Optional => ArgStdKindData::Optional {},
ArgStdKind::Star => ArgStdKindData::Star {},
ArgStdKind::Marker { marker } => ArgStdKindData::Marker { marker },
ArgStdKind::DelimitedGroup { open, close } => {
ArgStdKindData::DelimitedGroup { delimiters: pair(open, close) }
}
ArgStdKind::OptionalDelimitedGroup { open, close } => {
ArgStdKindData::OptionalDelimitedGroup { delimiters: pair(open, close) }
}
ArgStdKind::AnyDelimitedGroup => ArgStdKindData::AnyDelimitedGroup {},
ArgStdKind::OptionalAnyDelimitedGroup => ArgStdKindData::OptionalAnyDelimitedGroup {},
ArgStdKind::BracedOnly => ArgStdKindData::BracedOnly {},
ArgStdKind::Embellishments { markers } => {
ArgStdKindData::Embellishments { markers: markers.into_iter().map(String::from).collect() }
}
ArgStdKind::KeyVals => ArgStdKindData::KeyVals {},
ArgStdKind::CharsGroup => ArgStdKindData::CharsGroup {},
ArgStdKind::Verbatim { delimiters } => ArgStdKindData::Verbatim {
delimiters: delimiters.map(|(open, close)| pair(open, close)),
},
ArgStdKind::TackOn { fields } => ArgStdKindData::TackOn {
fields: fields
.iter()
.map(|field: &TackOnField| TackOnFieldData {
name: field.name.clone(),
args: ArgListData::List(
field.args.iter().map(|arg| ArgData::Declared(ArgDataFields::from(arg))).collect(),
),
repeatable: field.repeatable,
docs: field.docs.clone(),
})
.collect(),
},
ArgStdKind::Terminated { terminator, repeat_char, opener, head, raw } => ArgStdKindData::Terminated {
terminator,
repeat_char: repeat_char.map(String::from),
opener,
head,
raw,
},
}
}
}
impl TryFrom<ArgStdKindData> for ArgStdKind {
type Error = String;
fn try_from(data: ArgStdKindData) -> Result<ArgStdKind, String> {
Ok(match data {
ArgStdKindData::Mandatory {} => ArgStdKind::Mandatory,
ArgStdKindData::Optional {} => ArgStdKind::Optional,
ArgStdKindData::Star {} => ArgStdKind::Star,
ArgStdKindData::Marker { marker } => {
if marker.is_empty() || marker.chars().any(char::is_whitespace) {
return Err(format!(
"`marker` must be one or more characters other than whitespace, not {marker:?}"
));
}
marker_kind(marker)
}
ArgStdKindData::DelimitedGroup { delimiters } => {
let (open, close) = delimiter_pair(&delimiters)?;
ArgStdKind::DelimitedGroup { open, close }
}
ArgStdKindData::OptionalDelimitedGroup { delimiters } => {
let (open, close) = delimiter_pair(&delimiters)?;
ArgStdKind::OptionalDelimitedGroup { open, close }
}
ArgStdKindData::AnyDelimitedGroup {} => ArgStdKind::AnyDelimitedGroup,
ArgStdKindData::OptionalAnyDelimitedGroup {} => ArgStdKind::OptionalAnyDelimitedGroup,
ArgStdKindData::BracedOnly {} => ArgStdKind::BracedOnly,
ArgStdKindData::Embellishments { markers } => {
if markers.is_empty() {
return Err(String::from("`markers` must list at least one marker character"));
}
let markers = markers
.iter()
.map(|marker| character("each of the `markers`", marker))
.collect::<Result<Vec<char>, String>>()?;
ArgStdKind::Embellishments { markers }
}
ArgStdKindData::KeyVals {} => ArgStdKind::KeyVals,
ArgStdKindData::CharsGroup {} => ArgStdKind::CharsGroup,
ArgStdKindData::Verbatim { delimiters } => ArgStdKind::Verbatim {
delimiters: delimiters.as_deref().map(delimiter_pair).transpose()?,
},
ArgStdKindData::TackOn { fields } => ArgStdKind::TackOn { fields: tack_on_fields(fields)? },
ArgStdKindData::Terminated { terminator, repeat_char, opener, head, raw } => {
let repeat_char = repeat_char.as_deref().map(|text| character("`repeat_char`", text)).transpose()?;
match repeat_char {
None if terminator.is_empty() && head.is_empty() => {
return Err(String::from(
"a `terminated` argument must give a non-empty `terminator` or `head`, or a \
`repeat_char`, so that its terminator is never empty",
));
}
Some(repeat_char) if opener.starts_with(repeat_char) => {
return Err(format!(
"the `opener` of a `terminated` argument must not begin with its \
`repeat_char` `{repeat_char}`"
));
}
_ => {}
}
ArgStdKind::Terminated { terminator, repeat_char, opener, head, raw }
}
})
}
}
fn tack_on_fields(fields: Vec<TackOnFieldData>) -> Result<Vec<TackOnField>, String> {
fields
.into_iter()
.map(|data| {
let args = data.args.arg_defs().map_err(|error| format!("in the field `{}`, {error}", data.name))?;
let field = TackOnField::new(data.name, args).docs(data.docs);
Ok(if data.repeatable { field.repeatable() } else { field })
})
.collect()
}
fn marker_kind(marker: String) -> ArgStdKind {
if marker == "*" {
ArgStdKind::Star
} else {
ArgStdKind::Marker { marker }
}
}
fn character(what: &str, text: &str) -> Result<char, String> {
let mut chars = text.chars();
match (chars.next(), chars.next()) {
(Some(c), None) if !c.is_whitespace() => Ok(c),
_ => Err(format!("{what} must be one character other than whitespace, not {text:?}")),
}
}
fn delimiter_pair(delimiters: &[String]) -> Result<(char, char), String> {
let [open, close] = delimiters else {
return Err(format!(
"`delimiters` must list two characters, the opening one and the closing one, and it lists {}",
delimiters.len()
));
};
Ok((character("each of the `delimiters`", open)?, character("each of the `delimiters`", close)?))
}
fn deserialize_syntax<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<ArgStdKind>, D::Error> {
let keys = serde_json::Map::<String, Value>::deserialize(deserializer)?;
let Some(syntax) = keys.get("syntax") else {
return match keys.keys().next() {
Some(key) => Err(D::Error::custom(unknown_key(key, None, map_form(&map_forms(), None)))),
None => Ok(None),
};
};
ArgStdKind::deserialize(Value::Object(keys.clone())).map(Some).map_err(|error| {
D::Error::custom(syntax_problem(syntax, &keys).unwrap_or_else(|| error.to_string()))
})
}
fn syntax_problem(syntax: &Value, keys: &serde_json::Map<String, Value>) -> Option<String> {
let forms = map_forms();
let name = syntax.as_str();
let Some(form) = name.and_then(|name| map_form(&forms, Some(name))) else {
return Some(unknown_syntax(syntax, &forms));
};
if let Some(key) = keys.keys().find(|key| !form.contains_key(*key)) {
return Some(unknown_key(key, name, Some(form)));
}
keys.iter().find_map(|(key, value)| mistyped(key, form.get(key)?, value))
}
fn unknown_syntax(syntax: &Value, forms: &[MapForm]) -> String {
let names: Vec<String> = forms.iter().filter_map(form_syntax).map(|name| format!("`{name}`")).collect();
format!("{syntax} is not a syntax of an argument; the syntaxes are {}", names.join(", "))
}
fn unknown_key(key: &str, syntax: Option<&str>, form: Option<&MapForm>) -> String {
let listed = |code: bool| {
let known = form.into_iter().flat_map(MapForm::keys).filter(|known| code || known.as_str() != "code");
known.map(|known| format!("`{known}`")).collect::<Vec<_>>().join(", ")
};
match (syntax, form) {
(_, None) => format!("`{key}` is not a key of an argument's map"),
(Some(name), Some(_)) => format!(
"`{key}` is not a key of an argument's map with the syntax `{name}`; its keys are {}",
listed(true)
),
(None, Some(_)) => format!(
"`{key}` is not a key of an argument's map; its keys are {}, and `code` or `syntax` with the \
syntax's parameters",
listed(false)
),
}
}
fn mistyped(key: &str, schema: &Value, value: &Value) -> Option<String> {
if !admits(schema, value) {
return Some(format!("`{key}` must be {}, not {value}", expected(schema)?));
}
let (Some(items), Value::Array(entries)) = (schema.get("items"), value) else {
return None;
};
let entry = entries.iter().find(|entry| !admits(items, entry))?;
Some(format!("each of the `{key}` must be {}, not {entry}", expected(items)?))
}
fn admits(schema: &Value, value: &Value) -> bool {
let name = match value {
Value::Null => "null",
Value::Bool(_) => "boolean",
Value::Number(_) => "number",
Value::String(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "object",
};
match schema.get("type") {
Some(Value::Array(names)) => names.iter().any(|admitted| admitted == name),
Some(admitted) => admitted == name,
None => true,
}
}
fn expected(schema: &Value) -> Option<&'static str> {
let name = match schema.get("type")? {
Value::Array(names) => names.iter().filter_map(Value::as_str).find(|name| *name != "null")?,
name => name.as_str()?,
};
let pattern = schema.get("pattern").and_then(Value::as_str);
match name {
"string" if pattern == Some(ONE_CHARACTER) => Some("one character other than whitespace"),
"string" if pattern == Some(CHARACTERS) => Some("one or more characters other than whitespace"),
"string" => Some("a text"),
"array" => Some("a list"),
"boolean" => Some("`true` or `false`"),
_ => None,
}
}
type MapForm = serde_json::Map<String, Value>;
fn map_forms() -> Vec<MapForm> {
let schema = schemars::SchemaGenerator::default().into_root_schema_for::<ArgDataFields>();
let alternatives = schema.get("oneOf").and_then(Value::as_array).into_iter().flatten();
alternatives.filter_map(|alternative| alternative.get("properties").and_then(Value::as_object)).cloned().collect()
}
fn map_form<'a>(forms: &'a [MapForm], syntax: Option<&str>) -> Option<&'a MapForm> {
forms.iter().find(|form| form_syntax(form) == syntax)
}
fn form_syntax(form: &MapForm) -> Option<&str> {
form.get("syntax")?.get("const")?.as_str()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArgCodeProblem {
Unknown,
Incomplete,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArgCodeError {
pub code: String,
pub problem: ArgCodeProblem,
}
impl fmt::Display for ArgCodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.problem {
ArgCodeProblem::Unknown => {
let codes: Vec<String> = FIXED_CODES
.iter()
.map(|(code, _)| *code)
.chain(CODE_FORMS.iter().flat_map(|form| form.written.iter().copied()))
.map(|code| format!("`{code}`"))
.collect();
write!(f, "`{}` is not an argument code; the codes are {}", self.code, codes.join(", "))
}
ArgCodeProblem::Incomplete => {
let letter = self.code.chars().next();
match CODE_FORMS.iter().find(|form| Some(form.letter) == letter) {
Some(form) => write!(
f,
"in the argument code `{}`, `{}` must be followed by {}, as in `{}`",
self.code, form.letter, form.takes, form.example
),
None => write!(f, "`{}` is not a complete argument code", self.code),
}
}
}
}
}
impl std::error::Error for ArgCodeError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArgCode {
code: String,
kind: ArgStdKind,
}
impl ArgCode {
pub fn read(code: &str) -> Result<ArgCode, ArgCodeError> {
let read = |kind: ArgStdKind| ArgCode { code: code.to_string(), kind };
if let Some((_, kind)) = FIXED_CODES.iter().find(|(known, _)| *known == code) {
return Ok(read(kind.clone()));
}
let error = |problem| ArgCodeError { code: code.to_string(), problem };
let mut chars = code.chars();
let Some(letter) = chars.next() else {
return Err(error(ArgCodeProblem::Unknown));
};
let Some(form) = CODE_FORMS.iter().find(|form| form.letter == letter) else {
return Err(error(ArgCodeProblem::Unknown));
};
let rest: Vec<char> = chars.collect();
(form.read)(&rest).map(read).map_err(error)
}
pub fn as_str(&self) -> &str {
&self.code
}
pub fn kind(&self) -> &ArgStdKind {
&self.kind
}
}
impl From<ArgCode> for ArgDef {
fn from(code: ArgCode) -> ArgDef {
let mut arg = ArgDef::new(code.kind.clone());
arg.code = Some(code);
arg
}
}
pub fn arg_def_from_code(code: &str) -> Result<ArgDef, ArgCodeError> {
ArgCode::read(code).map(ArgDef::from)
}
const FIXED_CODES: [(&str, ArgStdKind); 10] = [
("{", ArgStdKind::Mandatory),
("m", ArgStdKind::Mandatory),
("[", ArgStdKind::Optional),
("o", ArgStdKind::Optional),
("*", ArgStdKind::Star),
("s", ArgStdKind::Star),
("v", ArgStdKind::Verbatim { delimiters: None }),
("AnyDelimited", ArgStdKind::AnyDelimitedGroup),
("AnyDelimitedOptional", ArgStdKind::OptionalAnyDelimitedGroup),
("BracedOnly", ArgStdKind::BracedOnly),
];
struct CodeForm {
letter: char,
written: &'static [&'static str],
takes: &'static str,
example: &'static str,
pattern: &'static str,
description: &'static str,
read: fn(&[char]) -> Result<ArgStdKind, ArgCodeProblem>,
}
const CODE_FORMS: [CodeForm; 9] = [
CodeForm {
letter: 't',
written: &["t<c>", "t{<chars>}"],
takes: "one marker character, or by `{`, one or more marker characters and `}`",
example: "t!",
pattern: r"^t(\S|\{[^\s}]+\})$",
description: "an optional marker made of the one character after `t`, or of the characters \
between the braces after `t`",
read: |rest| {
let marker: String = match rest {
['{', _, ..] => braced(rest)?.iter().collect(),
_ => parameters::<1>(rest)?.iter().collect(),
};
Ok(marker_kind(marker))
},
},
CodeForm {
letter: 'r',
written: &["r<c1><c2>"],
takes: "an opening and a closing character",
example: "r()",
pattern: r"^r\S\S$",
description: "a mandatory group between the two characters after `r`",
read: |rest| {
let [open, close] = parameters::<2>(rest)?;
Ok(ArgStdKind::DelimitedGroup { open, close })
},
},
CodeForm {
letter: 'd',
written: &["d<c1><c2>"],
takes: "an opening and a closing character",
example: "d<>",
pattern: r"^d\S\S$",
description: "an optional group between the two characters after `d`",
read: |rest| {
let [open, close] = parameters::<2>(rest)?;
Ok(ArgStdKind::OptionalDelimitedGroup { open, close })
},
},
CodeForm {
letter: 'v',
written: &["v<c1><c2>"],
takes: "an opening and a closing character",
example: "v||",
pattern: r"^v\S\S$",
description: "verbatim text between the two characters after `v`",
read: |rest| {
let [open, close] = parameters::<2>(rest)?;
Ok(ArgStdKind::Verbatim { delimiters: Some((open, close)) })
},
},
CodeForm {
letter: 'e',
written: &["e{<chars>}"],
takes: "`{`, one or more marker characters and `}`",
example: "e{_^}",
pattern: r"^e\{[^\s}]+\}$",
description: "embellishments: each character between the braces is a marker that is \
followed by one expression; the markers may be written in any order, \
each at most once",
read: |rest| Ok(ArgStdKind::Embellishments { markers: braced(rest)?.to_vec() }),
},
CodeForm {
letter: 'u',
written: &["u<terminator>"],
takes: "the terminator, one or more characters",
example: "u\\endm",
pattern: r"^u\S+$",
description: "document content up to the characters after `u`, its terminator",
read: |rest| terminated(rest, false, false),
},
CodeForm {
letter: 'U',
written: &["U<terminator>"],
takes: "the terminator, one or more characters",
example: "U\\endm",
pattern: r"^U\S+$",
description: "raw text up to the characters after `U`, its terminator",
read: |rest| terminated(rest, false, true),
},
CodeForm {
letter: 'f',
written: &["f<c><terminator>"],
takes: "a repeated character, then the rest of the terminator, if any",
example: "f+",
pattern: r"^f\S+$",
description: "document content after a run of the character after `f`, up to the same run \
followed by the characters after that character",
read: |rest| terminated(rest, true, false),
},
CodeForm {
letter: 'F',
written: &["F<c><terminator>"],
takes: "a repeated character, then the rest of the terminator, if any",
example: "F+",
pattern: r"^F\S+$",
description: "raw text after a run of the character after `F`, up to the same run \
followed by the characters after that character",
read: |rest| terminated(rest, true, true),
},
];
fn terminated(rest: &[char], repeated: bool, raw: bool) -> Result<ArgStdKind, ArgCodeProblem> {
if rest.is_empty() || rest.iter().any(|c| c.is_whitespace()) {
return Err(ArgCodeProblem::Incomplete);
}
let (repeat_char, terminator) = if repeated { (Some(rest[0]), &rest[1..]) } else { (None, rest) };
Ok(ArgStdKind::Terminated {
terminator: terminator.iter().collect(),
repeat_char,
opener: String::new(),
head: String::new(),
raw,
})
}
fn braced(rest: &[char]) -> Result<&[char], ArgCodeProblem> {
let Some(('{', inner)) = rest.split_first().map(|(first, inner)| (*first, inner)) else {
return Err(ArgCodeProblem::Incomplete);
};
let Some(end) = inner.iter().position(|c| *c == '}') else {
return Err(ArgCodeProblem::Incomplete);
};
let chars = &inner[..end];
if chars.is_empty() || chars.iter().any(|c| c.is_whitespace()) {
return Err(ArgCodeProblem::Incomplete);
}
if end + 1 != inner.len() {
return Err(ArgCodeProblem::Unknown);
}
Ok(chars)
}
fn parameters<const N: usize>(rest: &[char]) -> Result<[char; N], ArgCodeProblem> {
if rest.len() > N {
return Err(ArgCodeProblem::Unknown);
}
match <[char; N]>::try_from(rest) {
Ok(chars) if !chars.iter().any(|c| c.is_whitespace()) => Ok(chars),
_ => Err(ArgCodeProblem::Incomplete),
}
}
fn arg_code_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
let fixed = FIXED_CODES.iter().map(|(code, kind)| {
let parser = ArgDef::new(kind.clone()).kind;
serde_json::json!({ "const": code, "description": parser.description() })
});
let forms = CODE_FORMS.iter().map(|form| {
serde_json::json!({
"type": "string",
"pattern": form.pattern,
"description": format!("{}: {}", shapes(form), form.description),
})
});
let codes: Vec<serde_json::Value> = fixed.chain(forms).collect();
schemars::json_schema!({
"description": "The argument code, which says what form the argument takes.",
"anyOf": codes,
})
}
fn shapes(form: &CodeForm) -> String {
form.written.iter().map(|shape| format!("`{shape}`")).collect::<Vec<_>>().join(" or ")
}
fn mode_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"description": "The parsing mode the argument is read in: `text` or `math`. Without it, \
the argument is read in the mode the command is written in.",
"enum": ["text", "math", null],
})
}
fn arg_codes_text_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
let singles: String = FIXED_CODES
.iter()
.map(|(code, _)| *code)
.filter(|code| code.chars().count() == 1)
.map(|code| match code {
"[" | "]" | "\\" | "^" | "-" => format!("\\{code}"),
_ => code.to_string(),
})
.collect();
schemars::json_schema!({
"type": "string",
"pattern": format!("^[{singles}]*$"),
"description": "The arguments written as one text, in which each character is one \
argument code.",
})
}
fn syntax_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
let kinds = <ArgStdKind as schemars::JsonSchema>::json_schema(generator);
let alternatives = kinds.get("oneOf").cloned().unwrap_or_else(|| Value::Array(Vec::new()));
schemars::json_schema!({ "oneOf": alternatives })
}
fn arg_map_schema(schema: &mut schemars::Schema) {
let Some(object) = schema.as_object_mut() else { return };
let (Some(Value::Array(kinds)), Some(Value::Object(properties))) = (object.get("oneOf"), object.get("properties"))
else {
return;
};
let mut own = properties.clone();
let Some(code) = own.shift_remove("code") else { return };
let whole = |mut keys: serde_json::Map<String, Value>, required: Value, description: Option<&Value>| {
keys.extend(own.clone());
let mut map = serde_json::Map::new();
map.insert(String::from("type"), Value::from("object"));
if let Some(description) = description {
map.insert(String::from("description"), description.clone());
}
map.insert(String::from("properties"), Value::Object(keys));
map.insert(String::from("required"), required);
map.insert(String::from("additionalProperties"), Value::Bool(false));
Value::Object(map)
};
let mut alternatives = vec![whole(
serde_json::Map::from_iter([(String::from("code"), code)]),
serde_json::json!(["code"]),
None,
)];
for kind in kinds {
let parameters = kind.get("properties").and_then(Value::as_object).cloned().unwrap_or_default();
let mut keys = serde_json::Map::new();
if let Some(name) = parameters.get("syntax") {
keys.insert(String::from("syntax"), name.clone());
}
keys.extend(parameters);
let required = kind.get("required").cloned().unwrap_or_else(|| serde_json::json!(["syntax"]));
alternatives.push(whole(keys, required, kind.get("description")));
}
for key in ["oneOf", "properties", "type", "required", "additionalProperties"] {
object.shift_remove(key);
}
object.insert(String::from("oneOf"), Value::Array(alternatives));
}
#[cfg(test)]
mod tests {
use super::*;
fn kind(code: &str) -> Result<String, ArgCodeProblem> {
ArgCode::read(code).map(|code| format!("{:?}", code.kind())).map_err(|error| error.problem)
}
#[test]
fn each_form_reads_its_characters() {
assert_eq!(kind("t!").unwrap(), r#"Marker { marker: "!" }"#);
assert_eq!(kind("t*").unwrap(), "Star");
assert_eq!(kind("t{").unwrap(), r#"Marker { marker: "{" }"#);
assert_eq!(kind("t{\\big}").unwrap(), r#"Marker { marker: "\\big" }"#);
assert_eq!(kind("t{*}").unwrap(), "Star");
assert_eq!(kind("r()").unwrap(), "DelimitedGroup { open: '(', close: ')' }");
assert_eq!(kind("d<>").unwrap(), "OptionalDelimitedGroup { open: '<', close: '>' }");
assert_eq!(kind("v").unwrap(), "Verbatim { delimiters: None }");
assert_eq!(kind("v||").unwrap(), "Verbatim { delimiters: Some(('|', '|')) }");
assert_eq!(kind("e{_^}").unwrap(), "Embellishments { markers: ['_', '^'] }");
assert_eq!(kind("e{`}").unwrap(), "Embellishments { markers: ['`'] }");
assert_eq!(
kind("u\\endphf").unwrap(),
r#"Terminated { terminator: "\\endphf", repeat_char: None, opener: "", head: "", raw: false }"#
);
assert_eq!(
kind("U!!").unwrap(),
r#"Terminated { terminator: "!!", repeat_char: None, opener: "", head: "", raw: true }"#
);
assert_eq!(
kind("f+").unwrap(),
r#"Terminated { terminator: "", repeat_char: Some('+'), opener: "", head: "", raw: false }"#
);
assert_eq!(
kind("F``").unwrap(),
r#"Terminated { terminator: "`", repeat_char: Some('`'), opener: "", head: "", raw: true }"#
);
}
#[test]
fn a_terminated_code_round_trips_through_its_declaration() {
for code in ["u\\endphf", "U\\endverb", "f+", "F``", "F=]]"] {
let arg = arg_def_from_code(code).unwrap();
assert_eq!(arg.code(), Some(code));
let again = arg_def_from_code(arg.code().unwrap()).unwrap();
assert_eq!(again.kind.identity(), arg.kind.identity(), "{code}");
}
assert_ne!(
arg_def_from_code("u\\endphf").unwrap().kind.identity(),
arg_def_from_code("U\\endphf").unwrap().kind.identity()
);
assert_ne!(
arg_def_from_code("f+").unwrap().kind.identity(),
arg_def_from_code("u+").unwrap().kind.identity()
);
}
#[test]
fn a_code_lacking_characters_is_incomplete_and_one_with_more_is_unknown() {
for code in [
"t", "t ", "t{}", "t{ab", "t{a b}", "r", "r(", "r( ", "d<", "v|", "e", "e{", "e{}", "e{_", "e^", "e{ }",
"u", "U", "f", "F", "u ", "ua b", "F` ",
] {
assert_eq!(kind(code), Err(ArgCodeProblem::Incomplete), "{code:?}");
}
for code in ["", "q", " m", "m ", "mo", "t!!", "t{ab}x", "r()x", "e{^}x", "anydelimited"] {
assert_eq!(kind(code), Err(ArgCodeProblem::Unknown), "{code:?}");
}
}
#[test]
fn each_form_s_example_reads_and_matches_its_pattern() {
for form in &CODE_FORMS {
assert!(ArgCode::read(form.example).is_ok(), "{}", form.example);
assert!(form.pattern.starts_with(&format!("^{}", form.letter)));
}
}
#[test]
fn the_data_form_reads_the_role_and_leaves_it_absent_by_default() {
let list: ArgListData = serde_json::from_value(serde_json::json!([
{ "code": "{", "name": "target", "role": "flm.refs.target" },
{ "code": "[" },
"m",
]))
.unwrap();
let args = list.arg_defs().unwrap();
assert_eq!(args[0].role.as_ref().map(Name::as_str), Some("flm.refs.target"));
assert_eq!(args[0].name.as_deref(), Some("target"));
assert!(args[1].role.is_none());
assert!(args[2].role.is_none());
}
#[test]
fn a_structured_syntax_declares_what_its_code_does_and_a_map_gives_exactly_one() {
let arg = |data| ArgDef::try_from(serde_json::from_value::<ArgData>(data).unwrap());
let structured = arg(serde_json::json!({
"syntax": "delimited-group", "delimiters": ["(", ")"], "name": "size",
}))
.unwrap();
let mut coded = arg(serde_json::json!({ "code": "r()", "name": "size" })).unwrap();
assert_eq!(coded.code(), Some("r()"));
coded.code = None;
assert_eq!(structured, coded);
let both = serde_json::json!({ "code": "r()", "syntax": "delimited-group", "delimiters": ["(", ")"] });
assert_eq!(arg(both).unwrap_err(), ArgDataError::BothCodeAndSyntax);
assert_eq!(arg(serde_json::json!({ "name": "size" })).unwrap_err(), ArgDataError::NeitherCodeNorSyntax);
}
#[test]
fn the_data_form_serializes_every_field_and_reads_back_the_same() {
let fields: ArgDataFields = serde_json::from_value(serde_json::json!({
"code": "{", "name": "path", "mode": "text", "scoped": ["my.package"], "role": "my.path",
}))
.unwrap();
let written = serde_json::to_value(&fields).unwrap();
assert_eq!(
written,
serde_json::json!({
"code": "{", "name": "path", "layout": "inline", "opaque_wrapper": false, "docs": "",
"mode": "text", "scoped": ["my.package"], "role": "my.path",
})
);
let read: ArgDataFields = serde_json::from_value(written).unwrap();
assert_eq!(read, fields);
}
#[test]
fn a_tack_on_kind_reads_its_fields_and_writes_back_the_same() {
let arg = |data| ArgDef::try_from(serde_json::from_value::<ArgData>(data).unwrap()).unwrap();
let declared = arg(serde_json::json!({
"syntax": "tack-on",
"name": "fields",
"fields": [
{ "name": "label", "args": [{ "syntax": "chars-group", "name": "target" }], "repeatable": true },
{ "name": "nolink", "docs": "No link." },
],
}));
assert_eq!(declared.name.as_deref(), Some("fields"));
let fields = declared.kind.tack_on_fields().expect("a tack-on argument");
assert_eq!(
fields,
[
TackOnField::new("label", vec![ArgDef::named("target", ArgStdKind::CharsGroup)]).repeatable(),
TackOnField::new("nolink", Vec::new()).docs("No link."),
]
);
let written = serde_json::to_value(ArgDataFields::from(&declared)).unwrap();
assert_eq!(arg(written), declared);
}
}