use canvist_model::Value;
use serde_json::Value as Json;
use serde_json::json;
#[derive(Clone, Debug, PartialEq)]
pub enum ValueType {
Bool,
Int,
IntRange {
min: i64,
max: i64,
},
Float,
String,
OneOf(Vec<&'static str>),
Nullable(Box<ValueType>),
List(Box<ValueType>),
Record(Vec<Field>),
}
impl ValueType {
#[must_use]
pub fn nullable(inner: Self) -> Self {
Self::Nullable(Box::new(inner))
}
#[must_use]
pub fn list(inner: Self) -> Self {
Self::List(Box::new(inner))
}
#[must_use]
pub fn accepts(&self, value: &Value) -> bool {
match (self, value) {
(Self::Nullable(_), Value::Null)
| (Self::Bool, Value::Bool(_))
| (Self::Int, Value::Int(_))
| (Self::Float, Value::Float(_) | Value::Int(_))
| (Self::String, Value::String(_)) => true,
(Self::IntRange { min, max }, Value::Int(number)) => (min..=max).contains(&number),
(Self::OneOf(options), Value::String(text)) => options.contains(&&**text),
(Self::Nullable(inner), value) => inner.accepts(value),
(Self::List(inner), Value::Array(items)) => {
items.iter().all(|item| inner.accepts(item))
}
(Self::Record(fields), Value::Map(map)) => accepts_record(fields, map),
_ => false,
}
}
#[must_use]
pub fn sample(&self) -> Value {
match self {
Self::Bool => Value::Bool(true),
Self::Int => Value::Int(1),
Self::IntRange { min, .. } => Value::Int(*min),
Self::Float => Value::Float(1.0),
Self::String => Value::from("sample"),
Self::OneOf(options) => {
options
.first()
.map_or(Value::Null, |&option| Value::from(option))
}
Self::Nullable(inner) => inner.sample(),
Self::List(inner) => Value::from(vec![inner.sample(), inner.sample()]),
Self::Record(fields) => {
let map: canvist_model::Attrs = fields
.iter()
.map(|field| (field.name, field.ty.sample()))
.collect();
Value::from(map)
}
}
}
#[must_use]
pub fn to_json(&self) -> Json {
match self {
Self::Bool => json!({ "type": "bool" }),
Self::Int => json!({ "type": "int" }),
Self::IntRange { min, max } => json!({ "type": "int", "min": min, "max": max }),
Self::Float => json!({ "type": "float" }),
Self::String => json!({ "type": "string" }),
Self::OneOf(options) => json!({ "type": "string", "enum": options }),
Self::Nullable(inner) => json!({ "type": "nullable", "of": inner.to_json() }),
Self::List(inner) => json!({ "type": "list", "of": inner.to_json() }),
Self::Record(fields) => {
let fields: Vec<Json> = fields.iter().map(Field::to_json).collect();
json!({ "type": "record", "fields": fields })
}
}
}
}
impl std::fmt::Display for ValueType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Bool => f.write_str("a boolean"),
Self::Int => f.write_str("an integer"),
Self::IntRange { min, max } => write!(f, "an integer from {min} to {max}"),
Self::Float => f.write_str("a number"),
Self::String => f.write_str("a string"),
Self::OneOf(options) => write!(f, "one of {}", options.join(", ")),
Self::Nullable(inner) => write!(f, "{inner} or null"),
Self::List(inner) => write!(f, "a list, each item {inner}"),
Self::Record(fields) => {
let names: Vec<&str> = fields.iter().map(|field| field.name).collect();
write!(f, "a record of {}", names.join(", "))
}
}
}
}
fn accepts_record(fields: &[Field], map: &canvist_model::Attrs) -> bool {
let known = map
.iter()
.all(|(key, _)| fields.iter().any(|field| field.name == key));
known
&& fields.iter().all(|field| {
match map.get(field.name) {
Some(value) => field.ty.accepts(value),
None => field.default.is_some(),
}
})
}
#[must_use]
pub fn value_to_json(value: &Value) -> Json {
match value {
Value::Null => Json::Null,
Value::Bool(flag) => Json::Bool(*flag),
Value::Int(number) => json!(number),
Value::Float(number) => json!(number),
Value::String(text) => Json::String(text.to_string()),
Value::Array(items) => Json::Array(items.iter().map(value_to_json).collect()),
Value::Map(map) => {
let mut object = serde_json::Map::new();
for (key, value) in map.iter() {
object.insert(key.to_owned(), value_to_json(value));
}
Json::Object(object)
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Field {
pub name: &'static str,
pub ty: ValueType,
pub default: Option<Value>,
pub doc: &'static str,
}
#[must_use]
pub(crate) const fn doc(text: &'static str) -> &'static str {
if cfg!(canvist_omit_docs) { "" } else { text }
}
impl Field {
#[must_use]
pub const fn required(name: &'static str, ty: ValueType, doc: &'static str) -> Self {
Self {
name,
ty,
default: None,
doc: self::doc(doc),
}
}
#[must_use]
pub fn optional(
name: &'static str,
ty: ValueType,
default: impl Into<Value>,
doc: &'static str,
) -> Self {
Self {
name,
ty,
default: Some(default.into()),
doc: self::doc(doc),
}
}
fn to_json(&self) -> Json {
let mut field = json!({ "name": self.name, "type": self.ty.to_json(), "doc": self.doc });
if let (Some(default), Some(object)) = (&self.default, field.as_object_mut()) {
object.insert("default".to_owned(), value_to_json(default));
}
field
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NodeKind {
Block,
Mark,
Embed,
}
#[derive(Clone, Debug, PartialEq)]
pub struct NodeMeta {
pub kind: NodeKind,
pub name: &'static str,
pub attrs: Vec<Field>,
}
impl NodeMeta {
#[must_use]
pub const fn new(kind: NodeKind, name: &'static str) -> Self {
Self {
kind,
name,
attrs: Vec::new(),
}
}
#[must_use]
pub fn attr(mut self, attr: Field) -> Self {
self.attrs.push(attr);
self
}
fn to_json(&self) -> Json {
let kind = match self.kind {
NodeKind::Block => "block",
NodeKind::Mark => "mark",
NodeKind::Embed => "embed",
};
let attrs: Vec<Json> = self.attrs.iter().map(Field::to_json).collect();
json!({ "kind": kind, "name": self.name, "attrs": attrs })
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct CommandMeta {
pub name: &'static str,
pub doc: &'static str,
pub args: Vec<Field>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct QueryMeta {
pub name: &'static str,
pub doc: &'static str,
pub args: Vec<Field>,
pub returns: ValueType,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ExtensionMeta {
pub name: &'static str,
pub nodes: Vec<NodeMeta>,
pub commands: Vec<CommandMeta>,
pub queries: Vec<QueryMeta>,
}
impl ExtensionMeta {
#[must_use]
pub fn to_json(&self) -> Json {
let nodes: Vec<Json> = self.nodes.iter().map(NodeMeta::to_json).collect();
let commands: Vec<Json> = self
.commands
.iter()
.map(|command| {
let args: Vec<Json> = command.args.iter().map(Field::to_json).collect();
json!({ "name": command.name, "doc": command.doc, "args": args })
})
.collect();
let queries: Vec<Json> = self
.queries
.iter()
.map(|query| {
let args: Vec<Json> = query.args.iter().map(Field::to_json).collect();
json!({
"name": query.name,
"doc": query.doc,
"args": args,
"returns": query.returns.to_json(),
})
})
.collect();
json!({ "name": self.name, "nodes": nodes, "commands": commands, "queries": queries })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn describes_types_for_error_messages() {
let level = ValueType::nullable(ValueType::IntRange { min: 1, max: 6 });
let tags = ValueType::list(ValueType::OneOf(vec!["a", "b"]));
assert_eq!(level.to_string(), "an integer from 1 to 6 or null");
assert_eq!(tags.to_string(), "a list, each item one of a, b");
}
#[test]
fn checks_values_against_types() {
let level = ValueType::IntRange { min: 1, max: 6 };
let language = ValueType::nullable(ValueType::String);
let align = ValueType::OneOf(vec!["left", "right"]);
assert!(level.accepts(&Value::Int(3)));
assert!(!level.accepts(&Value::Int(7)));
assert!(!level.accepts(&Value::from("3")));
assert!(language.accepts(&Value::Null));
assert!(language.accepts(&Value::from("rust")));
assert!(align.accepts(&Value::from("left")));
assert!(!align.accepts(&Value::from("middle")));
assert!(ValueType::Float.accepts(&Value::Int(2)));
let names = ValueType::list(ValueType::String);
assert!(names.accepts(&Value::from(vec![Value::from("a")])));
assert!(!names.accepts(&Value::from(vec![Value::Int(1)])));
let record = ValueType::Record(vec![
Field::required("query", ValueType::String, "The text."),
Field::optional("count", ValueType::Int, 0, "How many."),
]);
let query = canvist_model::Attrs::new().with("query", "ad");
assert!(
record.accepts(&Value::from(query.clone())),
"defaults may be left out"
);
assert!(!record.accepts(&Value::from(query.with("extra", 1))));
assert!(!record.accepts(&Value::from(canvist_model::Attrs::new())));
}
#[test]
fn samples_are_accepted() {
let types = [
ValueType::Bool,
ValueType::Int,
ValueType::IntRange { min: 2, max: 4 },
ValueType::Float,
ValueType::String,
ValueType::OneOf(vec!["a"]),
ValueType::nullable(ValueType::Int),
ValueType::list(ValueType::String),
ValueType::Record(vec![
Field::required("query", ValueType::String, "The text."),
Field::optional("count", ValueType::Int, 0, "How many."),
]),
];
for ty in types {
assert!(ty.accepts(&ty.sample()), "{ty:?}");
}
}
}