vendor: import ReSpeak/tsclientlib@ee3bc6f
Unmodified copy of the tsclientlib workspace crates (MIT OR Apache-2.0) with the tsdeclarations submodule (83cb8a9) flattened into plain files. See crates/proto/UPSTREAM.md for the path mapping. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
119 files changed
+24322
No files matched your search
@@ -0,0 +1,207 @@
|
||||
use heck::*;
|
||||
use once_cell::sync::Lazy;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::*;
|
||||
|
||||
pub const DATA_STR: &str =
|
||||
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/declarations/Book.toml"));
|
||||
|
||||
pub static DATA: Lazy<BookDeclarations> = Lazy::new(|| toml::from_str(DATA_STR).unwrap());
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct BookDeclarations {
|
||||
#[serde(rename = "struct")]
|
||||
pub structs: Vec<Struct>,
|
||||
}
|
||||
|
||||
impl BookDeclarations {
|
||||
pub fn get_struct(&self, name: &str) -> &Struct {
|
||||
if let Some(s) = self.structs.iter().find(|s| s.name == name) {
|
||||
s
|
||||
} else {
|
||||
panic!("Cannot find bookkeeping struct {}", name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone, Debug)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Id {
|
||||
#[serde(rename = "struct")]
|
||||
pub struct_name: String,
|
||||
pub prop: String,
|
||||
}
|
||||
|
||||
impl Id {
|
||||
pub fn find_property<'a>(&self, structs: &'a [Struct]) -> &'a Property {
|
||||
// Find struct
|
||||
for s in structs {
|
||||
if s.name == self.struct_name {
|
||||
// Find property
|
||||
for p in &s.properties {
|
||||
if p.name == self.prop {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
panic!("Cannot find struct {} of id", self.struct_name);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone, Debug)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Struct {
|
||||
pub name: String,
|
||||
#[serde(default = "get_false")]
|
||||
pub opt: bool,
|
||||
pub id: Vec<Id>,
|
||||
pub doc: String,
|
||||
pub properties: Vec<Property>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone, Debug)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Property {
|
||||
/// The name of this property (in PascalCase) which can be called from rust
|
||||
/// when generated.
|
||||
pub name: String,
|
||||
/// The rust declaration type.
|
||||
#[serde(rename = "type")]
|
||||
pub type_s: String,
|
||||
pub doc: Option<String>,
|
||||
#[serde(default = "get_false")]
|
||||
pub opt: bool,
|
||||
#[serde(rename = "mod")]
|
||||
pub modifier: Option<String>,
|
||||
pub key: Option<String>,
|
||||
}
|
||||
|
||||
impl Struct {
|
||||
pub fn get_type(&self) -> Result<RustType> { RustType::with_opt(&self.name, self.opt) }
|
||||
|
||||
pub fn get_ids(&self, structs: &[Struct]) -> String {
|
||||
let mut res = String::new();
|
||||
for id in &self.id {
|
||||
let p = id.find_property(structs);
|
||||
if !res.is_empty() {
|
||||
res.push_str(", ");
|
||||
}
|
||||
res.push_str(&p.get_type().unwrap().to_string());
|
||||
}
|
||||
embrace(&res)
|
||||
}
|
||||
|
||||
pub fn get_properties(&self, structs: &[Struct]) -> Vec<&Property> {
|
||||
self.properties.iter().filter(|p| !structs.iter().any(|s| s.name == p.type_s)).collect()
|
||||
}
|
||||
|
||||
/// Get all properties, including foreign ids (own ids are listed in properties).
|
||||
pub fn get_all_properties(&self) -> impl Iterator<Item = PropId<'_>> {
|
||||
self.id.iter()
|
||||
// Only foreign ids, others are also stored in the properties
|
||||
.filter_map(move |i| if i.struct_name != self.name { Some(PropId::from(i)) }
|
||||
else { None })
|
||||
.chain(self.properties.iter().map(|p| p.into()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Property {
|
||||
pub fn get_inner_type(&self) -> Result<RustType> { RustType::with_opt(&self.type_s, self.opt) }
|
||||
|
||||
pub fn get_type(&self) -> Result<RustType> {
|
||||
let key = if self.is_map() {
|
||||
Some(self.key.as_deref().ok_or_else(|| {
|
||||
eprintln!("Specified map without key");
|
||||
fmt::Error
|
||||
})?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
RustType::with(&self.type_s, self.opt, key, self.is_set(), self.is_array())
|
||||
}
|
||||
|
||||
/// Gets the type as a name, used for storing it in an enum.
|
||||
pub fn get_inner_type_as_name(&self) -> Result<String> { Ok(self.get_inner_type()?.to_name()) }
|
||||
|
||||
pub fn get_ids(&self, structs: &[Struct], struc: &Struct) -> String {
|
||||
let mut ids = struc.get_ids(structs);
|
||||
if !ids.is_empty() {
|
||||
ids.remove(0);
|
||||
ids.pop();
|
||||
}
|
||||
if let Some(m) = &self.modifier {
|
||||
if !ids.is_empty() {
|
||||
ids.push_str(", ");
|
||||
}
|
||||
if m == "map" {
|
||||
// The key is part of the id
|
||||
ids.push_str(self.key.as_ref().unwrap());
|
||||
} else if m == "array" || m == "set" {
|
||||
// Take the element itself as part of the id.
|
||||
// It has to be copied but most of the times it is an id itself.
|
||||
ids.push_str(&self.get_inner_type().unwrap().to_string());
|
||||
} else {
|
||||
panic!("Unknown modifier {}", m);
|
||||
}
|
||||
}
|
||||
embrace(&ids)
|
||||
}
|
||||
|
||||
/// Get the name without trailing `s`.
|
||||
pub fn get_name(&self) -> &str {
|
||||
if self.modifier.is_some() && self.name.ends_with('s') {
|
||||
&self.name[..self.name.len() - 1]
|
||||
} else {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_array(&self) -> bool { self.modifier.as_ref().map(|s| s == "array").unwrap_or(false) }
|
||||
pub fn is_set(&self) -> bool { self.modifier.as_ref().map(|s| s == "set").unwrap_or(false) }
|
||||
pub fn is_map(&self) -> bool { self.modifier.as_ref().map(|s| s == "map").unwrap_or(false) }
|
||||
}
|
||||
|
||||
pub enum PropId<'a> {
|
||||
Prop(&'a Property),
|
||||
Id(&'a Id),
|
||||
}
|
||||
|
||||
impl<'a> PropId<'a> {
|
||||
pub fn get_attr_name(&self, struc: &Struct) -> String {
|
||||
match *self {
|
||||
PropId::Prop(p) => p.name.to_snake_case(),
|
||||
PropId::Id(id) => {
|
||||
if struc.name == id.struct_name {
|
||||
id.prop.to_snake_case()
|
||||
} else {
|
||||
format!("{}_{}", id.struct_name.to_snake_case(), id.prop.to_snake_case(),)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_doc(&self) -> Option<&str> {
|
||||
match *self {
|
||||
PropId::Prop(p) => p.doc.as_deref(),
|
||||
PropId::Id(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_type(&self, structs: &[Struct]) -> Result<RustType> {
|
||||
match *self {
|
||||
PropId::Prop(p) => p.get_type(),
|
||||
PropId::Id(id) => id.find_property(structs).get_type(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<&'a Property> for PropId<'a> {
|
||||
fn from(p: &'a Property) -> Self { PropId::Prop(p) }
|
||||
}
|
||||
|
||||
impl<'a> From<&'a Id> for PropId<'a> {
|
||||
fn from(p: &'a Id) -> Self { PropId::Id(p) }
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
use std::str::FromStr;
|
||||
|
||||
use heck::*;
|
||||
use once_cell::sync::Lazy;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::book::{BookDeclarations, Property, Struct};
|
||||
use crate::messages::{Field, Message, MessageDeclarations};
|
||||
use crate::*;
|
||||
|
||||
pub const DATA_STR: &str =
|
||||
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/declarations/BookToMessages.toml"));
|
||||
|
||||
pub static DATA: Lazy<BookToMessagesDeclarations<'static>> = Lazy::new(|| {
|
||||
let rules: TomlStruct = toml::from_str(DATA_STR).unwrap();
|
||||
let book = &book::DATA;
|
||||
let messages = &messages::DATA;
|
||||
|
||||
let decls: Vec<_> = rules
|
||||
.rule
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let msg = messages.get_message(&r.to);
|
||||
let msg_fields =
|
||||
msg.attributes.iter().map(|a| messages.get_field(a)).collect::<Vec<_>>();
|
||||
let book_struct = book
|
||||
.structs
|
||||
.iter()
|
||||
.find(|s| s.name == r.from)
|
||||
.unwrap_or_else(|| panic!("Cannot find struct {}", r.from));
|
||||
|
||||
let find_prop =
|
||||
|name: &str, book_struct: &'static Struct| -> Option<&'static Property> {
|
||||
book_struct.properties.iter().find(|p| p.name == *name)
|
||||
};
|
||||
|
||||
// Map RuleProperty to RuleKind
|
||||
let to_rule_kind = |p: RuleProperty| {
|
||||
p.assert_valid();
|
||||
|
||||
if p.function.is_some() {
|
||||
if p.type_s.is_some() {
|
||||
RuleKind::ArgumentFunction {
|
||||
type_s: p.type_s.unwrap(),
|
||||
from: p.from.unwrap(),
|
||||
name: p.function.unwrap(),
|
||||
to: p
|
||||
.tolist
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|p| find_field(&p, &msg_fields))
|
||||
.collect(),
|
||||
}
|
||||
} else {
|
||||
RuleKind::Function {
|
||||
from: p.from.as_ref().map(|p| {
|
||||
find_prop(p, book_struct).unwrap_or_else(|| {
|
||||
panic!("No such (nested) property {} found in struct", p)
|
||||
})
|
||||
}),
|
||||
name: p.function.unwrap(),
|
||||
to: p
|
||||
.tolist
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|p| find_field(&p, &msg_fields))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
} else if let Some(prop) = find_prop(p.from.as_ref().unwrap(), book_struct) {
|
||||
RuleKind::Map { from: prop, to: find_field(&p.to.unwrap(), &msg_fields) }
|
||||
} else {
|
||||
RuleKind::ArgumentMap {
|
||||
from: p.from.unwrap(),
|
||||
to: find_field(&p.to.unwrap(), &msg_fields),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let mut ev = Event {
|
||||
op: r.operation.parse().expect("Failed to parse operation"),
|
||||
ids: r.ids.into_iter().map(to_rule_kind).collect(),
|
||||
msg,
|
||||
book_struct,
|
||||
rules: r.properties.into_iter().map(to_rule_kind).collect(),
|
||||
};
|
||||
|
||||
// Add ids, which are required fields in the message.
|
||||
// The filter checks that the message is not optional.
|
||||
for field in msg_fields.iter().filter(|f| msg.attributes.iter().any(|a| *a == f.map)) {
|
||||
if !ev.ids.iter().any(|i| match i {
|
||||
RuleKind::Map { to, .. } => to == field,
|
||||
RuleKind::ArgumentMap { to, .. } => to == field,
|
||||
RuleKind::Function { to, .. } | RuleKind::ArgumentFunction { to, .. } => {
|
||||
to.contains(field)
|
||||
}
|
||||
}) {
|
||||
// Try to find matching property
|
||||
if let Some(prop) = book
|
||||
.get_struct(&ev.book_struct.name)
|
||||
.properties
|
||||
.iter()
|
||||
.find(|p| !p.opt && p.name == field.pretty)
|
||||
{
|
||||
ev.ids.push(RuleKind::Map { from: prop, to: field })
|
||||
}
|
||||
// The property may be in the properties
|
||||
}
|
||||
}
|
||||
|
||||
// Add properties
|
||||
for field in msg_fields.iter().filter(|f| !msg.attributes.iter().any(|a| *a == f.map)) {
|
||||
if !ev.ids.iter().chain(ev.rules.iter()).any(|i| match i {
|
||||
RuleKind::Map { to, .. } => to == field,
|
||||
RuleKind::ArgumentMap { to, .. } => to == field,
|
||||
RuleKind::Function { to, .. } | RuleKind::ArgumentFunction { to, .. } => {
|
||||
to.contains(field)
|
||||
}
|
||||
}) {
|
||||
// We ignore that properties are set as option. In all current cases, it
|
||||
// makes no sense to set them to `None`, so we handle them the same way as
|
||||
// non-optional properties.
|
||||
if let Some(prop) = book
|
||||
.get_struct(&ev.book_struct.name)
|
||||
.properties
|
||||
.iter()
|
||||
.find(|p| p.name == field.pretty)
|
||||
{
|
||||
if !ev.ids.iter().chain(ev.rules.iter()).any(|i| i.from_name() == prop.name)
|
||||
{
|
||||
ev.rules.push(RuleKind::Map { from: prop, to: field })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ev
|
||||
})
|
||||
.collect();
|
||||
|
||||
BookToMessagesDeclarations { book, messages, decls }
|
||||
});
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct BookToMessagesDeclarations<'a> {
|
||||
pub book: &'a BookDeclarations,
|
||||
pub messages: &'a MessageDeclarations,
|
||||
pub decls: Vec<Event<'a>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Event<'a> {
|
||||
pub op: RuleOp,
|
||||
pub msg: &'a Message,
|
||||
pub book_struct: &'a Struct,
|
||||
pub ids: Vec<RuleKind<'a>>,
|
||||
pub rules: Vec<RuleKind<'a>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum RuleKind<'a> {
|
||||
Map { from: &'a Property, to: &'a Field },
|
||||
ArgumentMap { from: String, to: &'a Field },
|
||||
Function { from: Option<&'a Property>, name: String, to: Vec<&'a Field> },
|
||||
ArgumentFunction { from: String, type_s: String, name: String, to: Vec<&'a Field> },
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub enum RuleOp {
|
||||
Add,
|
||||
Remove,
|
||||
Update,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct TomlStruct {
|
||||
rule: Vec<Rule>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize, Debug)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Rule {
|
||||
from: String,
|
||||
to: String,
|
||||
operation: String,
|
||||
#[serde(default = "Vec::new")]
|
||||
ids: Vec<RuleProperty>,
|
||||
#[serde(default = "Vec::new")]
|
||||
properties: Vec<RuleProperty>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize, Debug)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RuleProperty {
|
||||
from: Option<String>,
|
||||
to: Option<String>,
|
||||
|
||||
#[serde(rename = "type")]
|
||||
type_s: Option<String>,
|
||||
function: Option<String>,
|
||||
tolist: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
impl RuleProperty {
|
||||
fn assert_valid(&self) {
|
||||
if let Some(to) = &self.to {
|
||||
assert!(self.from.is_some(), "to-property '{}' is invalid. It needs a 'from'", to);
|
||||
assert!(
|
||||
self.function.is_none(),
|
||||
"to-property '{}' is invalid. It must not have a 'function'",
|
||||
to
|
||||
);
|
||||
assert!(
|
||||
self.tolist.is_none(),
|
||||
"to-property '{}' is invalid. It must not have a 'tolist'",
|
||||
to
|
||||
);
|
||||
assert!(
|
||||
self.type_s.is_none(),
|
||||
"to-property '{}' is invalid. It must not have a 'type'",
|
||||
to
|
||||
);
|
||||
} else if let Some(fun) = &self.function {
|
||||
assert!(
|
||||
self.tolist.is_some(),
|
||||
"function-property '{}' is invalid. It needs 'tolist'",
|
||||
fun
|
||||
);
|
||||
assert!(
|
||||
self.type_s.is_none() || self.from.is_some(),
|
||||
"function-property '{}' is invalid. If the type ({:?}) is set, from must be set \
|
||||
too",
|
||||
fun,
|
||||
self.type_s
|
||||
);
|
||||
} else {
|
||||
panic!(
|
||||
"Property is invalid. It needs either a 'to' or 'tolist'+'function'.Info: \
|
||||
tolist={:?} type={:?} from={:?}",
|
||||
self.tolist, self.type_s, self.from
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for RuleOp {
|
||||
type Err = fmt::Error;
|
||||
fn from_str(s: &str) -> Result<Self> {
|
||||
if s == "add" {
|
||||
Ok(RuleOp::Add)
|
||||
} else if s == "remove" {
|
||||
Ok(RuleOp::Remove)
|
||||
} else if s == "update" {
|
||||
Ok(RuleOp::Update)
|
||||
} else {
|
||||
eprintln!("Cannot parse operation, needs to be add, remove or update");
|
||||
Err(fmt::Error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// the in rust callable name (in PascalCase) from the field
|
||||
fn find_field<'a>(name: &str, msg_fields: &[&'a Field]) -> &'a Field {
|
||||
msg_fields
|
||||
.iter()
|
||||
.find(|f| f.pretty == name)
|
||||
.unwrap_or_else(|| panic!("Cannot find field '{}'", name))
|
||||
}
|
||||
|
||||
impl<'a> RuleKind<'a> {
|
||||
pub fn from_name(&'a self) -> &'a str {
|
||||
match self {
|
||||
RuleKind::Map { from, .. } => &from.name,
|
||||
RuleKind::ArgumentMap { from, .. } => from,
|
||||
RuleKind::Function { from, name, .. } => {
|
||||
&from.unwrap_or_else(|| panic!("From not set for function {}", name)).name
|
||||
}
|
||||
RuleKind::ArgumentFunction { from, .. } => from,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_name_singular(&'a self) -> &'a str {
|
||||
let name = self.from_name();
|
||||
if let Some(s) = name.strip_suffix('s') { s } else { name }
|
||||
}
|
||||
|
||||
pub fn from(&self) -> &'a Property {
|
||||
match self {
|
||||
RuleKind::Map { from, .. } => from,
|
||||
RuleKind::Function { from, name, .. } => {
|
||||
from.unwrap_or_else(|| panic!("From not set for function {}", name))
|
||||
}
|
||||
RuleKind::ArgumentMap { .. } | RuleKind::ArgumentFunction { .. } => {
|
||||
panic!("From is not a property for argument functions")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_function(&self) -> bool {
|
||||
matches!(self, RuleKind::Function { .. } | RuleKind::ArgumentFunction { .. })
|
||||
}
|
||||
|
||||
pub fn get_type(&self) -> RustType {
|
||||
match self {
|
||||
RuleKind::Map { .. } | RuleKind::Function { .. } => self.from().get_type().unwrap(),
|
||||
RuleKind::ArgumentMap { to, .. } => to.get_type("").unwrap(),
|
||||
RuleKind::ArgumentFunction { type_s, .. } => type_s.parse().unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_type_no_option(&self) -> RustType {
|
||||
match self {
|
||||
RuleKind::Map { .. } => {
|
||||
let mut rust_type = self.from().clone();
|
||||
rust_type.opt = false;
|
||||
rust_type.get_type().unwrap()
|
||||
}
|
||||
_ => self.get_type(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_argument(&self) -> String {
|
||||
format!("{}: {}", self.from_name().to_snake_case(), self.get_type().to_ref(true))
|
||||
}
|
||||
|
||||
pub fn get_argument_no_option(&self) -> String {
|
||||
format!("{}: {}", self.from_name().to_snake_case(), self.get_type_no_option().to_ref(true))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Event<'a> {
|
||||
/// The name of the change, could be a keyword.
|
||||
pub fn get_small_name(&self) -> String {
|
||||
// Strip own struct name and 'Request'
|
||||
self.msg.name.replace(&self.book_struct.name, "").replace("Request", "")
|
||||
}
|
||||
|
||||
/// The small name, not a keyword
|
||||
pub fn get_change_name(&self) -> String {
|
||||
let small_change_name = self.get_small_name();
|
||||
if small_change_name == "Move" { self.msg.name.clone() } else { small_change_name }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
use once_cell::sync::Lazy;
|
||||
use serde::Deserialize;
|
||||
|
||||
pub const DATA_STR: &str =
|
||||
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/declarations/Enums.toml"));
|
||||
|
||||
pub static DATA: Lazy<Enums> = Lazy::new(|| toml::from_str(DATA_STR).unwrap());
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Enums {
|
||||
#[serde(rename = "enum")]
|
||||
pub enums: Vec<Enum>,
|
||||
#[serde(rename = "bitflag")]
|
||||
pub bitflags: Vec<Enum>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone, Debug)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Enum {
|
||||
pub name: String,
|
||||
pub doc: Option<String>,
|
||||
#[serde(rename = "type")]
|
||||
pub use_type: Option<String>,
|
||||
pub variants: Vec<Variant>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone, Debug)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Variant {
|
||||
pub name: String,
|
||||
pub doc: String,
|
||||
pub value: Option<u64>,
|
||||
}
|
||||
|
||||
impl Enum {
|
||||
/// Computes the needed number of bits to store all possible variants.
|
||||
pub fn bitwidth(&self) -> u32 {
|
||||
let mut leading_zeros = 0;
|
||||
let mut value: u64 = 0;
|
||||
for v in &self.variants {
|
||||
if let Some(v) = v.value {
|
||||
leading_zeros = std::cmp::min(leading_zeros, value.leading_zeros());
|
||||
value = v;
|
||||
} else {
|
||||
value += 1;
|
||||
}
|
||||
}
|
||||
leading_zeros = std::cmp::min(leading_zeros, value.leading_zeros());
|
||||
(64 - leading_zeros).next_power_of_two()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
use std::result::Result;
|
||||
|
||||
use crate::*;
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
|
||||
pub const DATA_STR: &str =
|
||||
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/declarations/Errors.csv"));
|
||||
|
||||
pub static DATA: Lazy<Errors> = Lazy::new(|| {
|
||||
Errors(
|
||||
csv::Reader::from_reader(DATA_STR.as_bytes())
|
||||
.deserialize()
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.unwrap(),
|
||||
)
|
||||
});
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub struct Errors(pub Vec<EnumValue>);
|
||||
@@ -0,0 +1,398 @@
|
||||
//! `tsproto-structs` contains machine readable data for several TeamSpeak related topics.
|
||||
//!
|
||||
//! The underlying data files can be found in the
|
||||
//! [tsdeclarations](https://github.com/ReSpeak/tsdeclarations) repository.
|
||||
|
||||
use std::fmt;
|
||||
use std::str::FromStr;
|
||||
|
||||
use heck::*;
|
||||
use serde::Deserialize;
|
||||
|
||||
type Result<T> = std::result::Result<T, fmt::Error>;
|
||||
|
||||
pub mod book;
|
||||
pub mod book_to_messages;
|
||||
pub mod enums;
|
||||
pub mod errors;
|
||||
pub mod messages;
|
||||
pub mod messages_to_book;
|
||||
pub mod permissions;
|
||||
pub mod versions;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct EnumValue {
|
||||
pub name: String,
|
||||
pub doc: String,
|
||||
pub num: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum InnerRustType {
|
||||
Primitive(String),
|
||||
Struct(String),
|
||||
Ref(Box<InnerRustType>),
|
||||
Option(Box<InnerRustType>),
|
||||
/// Key, value
|
||||
Map(Box<InnerRustType>, Box<InnerRustType>),
|
||||
Set(Box<InnerRustType>),
|
||||
Vec(Box<InnerRustType>),
|
||||
Cow(Box<InnerRustType>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RustType {
|
||||
pub inner: InnerRustType,
|
||||
/// Include a lifetime specifier 'a
|
||||
pub lifetime: bool,
|
||||
}
|
||||
|
||||
impl InnerRustType {
|
||||
/// `lifetime`: Include 'a for references
|
||||
/// `is_ref`: If this is a refercene, used to emit either `str` or `String` or slices
|
||||
pub fn fmt(&self, f: &mut fmt::Formatter, lifetime: bool, is_ref: bool) -> fmt::Result {
|
||||
let lifetime_str = if lifetime { "'a " } else { "" };
|
||||
match self {
|
||||
Self::Struct(s) if s == "str" => {
|
||||
if is_ref {
|
||||
write!(f, "str")?;
|
||||
} else {
|
||||
write!(f, "String")?;
|
||||
}
|
||||
}
|
||||
Self::Struct(s) if s == "Uid" => {
|
||||
write!(f, "{}", s)?;
|
||||
}
|
||||
Self::Primitive(s) | Self::Struct(s) => write!(f, "{}", s)?,
|
||||
Self::Ref(i) => {
|
||||
write!(f, "&{}", lifetime_str)?;
|
||||
i.fmt(f, lifetime, true)?;
|
||||
}
|
||||
Self::Option(i) => {
|
||||
write!(f, "Option<")?;
|
||||
i.fmt(f, lifetime, false)?;
|
||||
write!(f, ">")?;
|
||||
}
|
||||
Self::Map(k, v) => {
|
||||
write!(f, "HashMap<")?;
|
||||
k.fmt(f, lifetime, false)?;
|
||||
write!(f, ", ")?;
|
||||
v.fmt(f, lifetime, false)?;
|
||||
write!(f, ">")?;
|
||||
}
|
||||
Self::Set(i) => {
|
||||
write!(f, "HashSet<")?;
|
||||
i.fmt(f, lifetime, false)?;
|
||||
write!(f, ">")?;
|
||||
}
|
||||
Self::Vec(i) => {
|
||||
if is_ref {
|
||||
write!(f, "[")?;
|
||||
i.fmt(f, lifetime, false)?;
|
||||
write!(f, "]")?;
|
||||
} else {
|
||||
write!(f, "Vec<")?;
|
||||
i.fmt(f, lifetime, false)?;
|
||||
write!(f, ">")?;
|
||||
}
|
||||
}
|
||||
Self::Cow(i) => {
|
||||
write!(f, "Cow<{}, ", lifetime_str.trim())?;
|
||||
i.fmt(f, false, true)?;
|
||||
write!(f, ">")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns a converted type.
|
||||
pub fn to_ref(&self) -> Self {
|
||||
match self {
|
||||
Self::Struct(s) if s == "UidBuf" => Self::Ref(Box::new(Self::Struct("Uid".into()))),
|
||||
Self::Struct(s) if s == "String" => Self::Ref(Box::new(Self::Struct("str".into()))),
|
||||
Self::Struct(_) | Self::Map(_, _) | Self::Set(_) | Self::Vec(_) => {
|
||||
Self::Ref(Box::new(self.clone()))
|
||||
}
|
||||
Self::Primitive(_) | Self::Ref(_) | Self::Cow(_) => self.clone(),
|
||||
Self::Option(i) => Self::Option(Box::new(i.to_ref())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a converted type.
|
||||
pub fn to_cow(&self) -> Self {
|
||||
match self {
|
||||
Self::Struct(s) if s == "UidBuf" => Self::Cow(Box::new(Self::Struct("Uid".into()))),
|
||||
Self::Struct(s) if s == "String" => Self::Cow(Box::new(Self::Struct("str".into()))),
|
||||
Self::Struct(_) | Self::Map(_, _) | Self::Set(_) | Self::Vec(_) => {
|
||||
Self::Cow(Box::new(self.clone()))
|
||||
}
|
||||
Self::Primitive(_) | Self::Ref(_) | Self::Cow(_) => self.clone(),
|
||||
Self::Option(i) => Self::Option(Box::new(i.to_cow())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get code snippet for `as_ref`.
|
||||
pub fn code_as_ref(&self, name: &str) -> String {
|
||||
match self {
|
||||
Self::Struct(s) if s == "UidBuf" || s == "str" => format!("{}.as_ref()", name),
|
||||
Self::Struct(s) if s == "String" => format!("{}.as_str()", name),
|
||||
Self::Struct(s) if s == "str" => name.into(),
|
||||
Self::Struct(_) => format!("&{}", name),
|
||||
Self::Map(_, _) | Self::Set(_) | Self::Vec(_) | Self::Cow(_) => {
|
||||
format!("{}.as_ref()", name)
|
||||
}
|
||||
Self::Primitive(_) => name.into(),
|
||||
Self::Ref(i) => {
|
||||
let inner = i.code_as_ref(name);
|
||||
if inner == name {
|
||||
format!("*{}", name)
|
||||
} else if inner.starts_with('&') && &inner[1..] == name {
|
||||
name.into()
|
||||
} else {
|
||||
inner
|
||||
}
|
||||
}
|
||||
Self::Option(i) => {
|
||||
match &**i {
|
||||
// Shortcut
|
||||
Self::Struct(s) if s == "String" => format!("{}.as_deref()", name),
|
||||
_ => {
|
||||
let inner = i.code_as_ref(name);
|
||||
if inner == name {
|
||||
inner
|
||||
} else if inner.starts_with('&') && &inner[1..] == name {
|
||||
format!("{0}.as_ref()", name)
|
||||
} else {
|
||||
format!("{0}.as_ref().map(|{0}| {1})", name, inner)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn uses_lifetime(&self) -> bool {
|
||||
match self {
|
||||
Self::Struct(s) if s == "Uid" => true,
|
||||
Self::Ref(_) | Self::Cow(_) => true,
|
||||
Self::Map(_, i) | Self::Set(i) | Self::Vec(i) | Self::Option(i) => i.uses_lifetime(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for InnerRustType {
|
||||
type Err = fmt::Error;
|
||||
fn from_str(s: &str) -> Result<Self> {
|
||||
if s == "DateTime" {
|
||||
Ok(Self::Primitive("OffsetDateTime".into()))
|
||||
} else if s.starts_with("Duration") {
|
||||
Ok(Self::Primitive("Duration".into()))
|
||||
} else if s == "PermissionId" {
|
||||
Ok(Self::Primitive("Permission".into()))
|
||||
} else if s == "Ts3ErrorCode" {
|
||||
Ok(Self::Primitive("Error".into()))
|
||||
} else if s == "bool"
|
||||
|| s.starts_with('i')
|
||||
|| s.starts_with('u')
|
||||
|| s.starts_with('f')
|
||||
|| s.ends_with("Id")
|
||||
|| s.ends_with("Type")
|
||||
|| s.ends_with("Mode")
|
||||
|| s == "ChannelPermissionHint"
|
||||
|| s == "ClientPermissionHint"
|
||||
|| s == "Codec"
|
||||
|| s == "LogLevel"
|
||||
|| s == "MaxClients"
|
||||
|| s == "IpAddr"
|
||||
|| s == "Reason"
|
||||
|| s == "SocketAddr"
|
||||
{
|
||||
Ok(Self::Primitive(s.into()))
|
||||
} else if s == "Uid" {
|
||||
Ok(Self::Struct("UidBuf".into()))
|
||||
} else if s == "str" || s == "String" {
|
||||
Ok(Self::Struct("String".into()))
|
||||
} else if let Some(rest) = s.strip_prefix('&') {
|
||||
let rest = if rest.starts_with('\'') {
|
||||
let i = rest.find(' ').ok_or_else(|| {
|
||||
eprintln!("Reference type with lifetime has no inner type: {:?}", s);
|
||||
fmt::Error
|
||||
})?;
|
||||
&rest[i + 1..]
|
||||
} else {
|
||||
rest
|
||||
};
|
||||
Ok(Self::Ref(Box::new(rest.parse()?)))
|
||||
} else if let Some(rest) = s.strip_suffix('?') {
|
||||
Ok(Self::Option(Box::new(rest.parse()?)))
|
||||
} else if s.starts_with("Option<") {
|
||||
let rest = &s[7..s.len() - 1];
|
||||
Ok(Self::Option(Box::new(rest.parse()?)))
|
||||
} else if let Some(rest) = s.strip_suffix("[]") {
|
||||
Ok(Self::Vec(Box::new(rest.parse()?)))
|
||||
} else if s.starts_with("HashMap<") {
|
||||
let rest = &s[8..s.len() - 1];
|
||||
let i = rest.find(',').ok_or_else(|| {
|
||||
eprintln!("HashMap without key: {:?}", s);
|
||||
fmt::Error
|
||||
})?;
|
||||
Ok(Self::Map(Box::new(rest[..i].parse()?), Box::new(rest[i..].trim().parse()?)))
|
||||
} else if s.starts_with("HashSet<") {
|
||||
let rest = &s[8..s.len() - 1];
|
||||
Ok(Self::Set(Box::new(rest.parse()?)))
|
||||
} else if s.starts_with("Vec<") {
|
||||
let rest = &s[4..s.len() - 1];
|
||||
Ok(Self::Vec(Box::new(rest.parse()?)))
|
||||
} else if s.starts_with('[') {
|
||||
let rest = &s[1..s.len() - 1];
|
||||
if rest.contains(';') {
|
||||
// Slice with explicit length, take as struct
|
||||
Ok(Self::Struct(s.into()))
|
||||
} else {
|
||||
Ok(Self::Vec(Box::new(rest.parse()?)))
|
||||
}
|
||||
} else if let Some(rest) = s.strip_suffix('T') {
|
||||
rest.parse()
|
||||
} else {
|
||||
Ok(Self::Struct(s.into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for RustType {
|
||||
type Err = fmt::Error;
|
||||
fn from_str(s: &str) -> Result<Self> {
|
||||
Ok(Self { inner: s.parse()?, lifetime: s.contains("&'") })
|
||||
}
|
||||
}
|
||||
|
||||
impl RustType {
|
||||
pub fn with_opt(s: &str, opt: bool) -> Result<Self> {
|
||||
let inner = s.parse()?;
|
||||
let inner = if opt { InnerRustType::Option(Box::new(inner)) } else { inner };
|
||||
Ok(Self { inner, lifetime: s.contains("&'") })
|
||||
}
|
||||
|
||||
/// `map` has a key
|
||||
pub fn with(s: &str, opt: bool, map: Option<&str>, set: bool, vec: bool) -> Result<Self> {
|
||||
assert!(
|
||||
[map.is_some(), set, vec].iter().filter(|b| **b).count() <= 1,
|
||||
"Too many modifiers active (map: {:?}, set: {:?}, vec: {:?})",
|
||||
map,
|
||||
set,
|
||||
vec
|
||||
);
|
||||
let mut inner = s.parse()?;
|
||||
if let Some(key) = map {
|
||||
inner = InnerRustType::Map(Box::new(key.parse()?), Box::new(inner));
|
||||
}
|
||||
if set {
|
||||
inner = InnerRustType::Set(Box::new(inner));
|
||||
}
|
||||
if vec {
|
||||
inner = InnerRustType::Vec(Box::new(inner));
|
||||
}
|
||||
|
||||
inner = if opt { InnerRustType::Option(Box::new(inner)) } else { inner };
|
||||
Ok(Self { inner, lifetime: s.contains("&'") })
|
||||
}
|
||||
|
||||
pub fn to_opt(&self, opt: bool) -> Self {
|
||||
if opt {
|
||||
Self {
|
||||
inner: InnerRustType::Option(Box::new(self.inner.clone())),
|
||||
lifetime: self.lifetime,
|
||||
}
|
||||
} else {
|
||||
self.clone()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_ref(&self, as_ref: bool) -> Self {
|
||||
if as_ref {
|
||||
Self { inner: self.inner.to_ref(), lifetime: self.lifetime }
|
||||
} else {
|
||||
self.clone()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_cow(&self) -> Self { Self { inner: self.inner.to_cow(), lifetime: self.lifetime } }
|
||||
|
||||
pub fn lifetime(&self, lifetime: bool) -> Self {
|
||||
let mut r = self.clone();
|
||||
r.lifetime = lifetime;
|
||||
r
|
||||
}
|
||||
|
||||
pub fn wrap_ref(&self) -> Self {
|
||||
Self { inner: InnerRustType::Ref(Box::new(self.inner.clone())), lifetime: self.lifetime }
|
||||
}
|
||||
|
||||
pub fn wrap_opt(&self) -> Self {
|
||||
Self { inner: InnerRustType::Option(Box::new(self.inner.clone())), lifetime: self.lifetime }
|
||||
}
|
||||
|
||||
pub fn is_opt(&self) -> bool { matches!(self.inner, InnerRustType::Option(_)) }
|
||||
|
||||
pub fn is_primitive(&self) -> bool {
|
||||
let inner = if let InnerRustType::Option(t) = &self.inner { t } else { &self.inner };
|
||||
matches!(inner, InnerRustType::Primitive(_))
|
||||
}
|
||||
|
||||
pub fn is_vec(&self) -> bool { matches!(self.inner, InnerRustType::Vec(_)) }
|
||||
|
||||
pub fn is_cow(&self) -> bool {
|
||||
let inner = if let InnerRustType::Option(i) = &self.inner { i } else { &self.inner };
|
||||
matches!(inner, InnerRustType::Cow(_))
|
||||
}
|
||||
|
||||
pub fn uses_lifetime(&self) -> bool { self.inner.uses_lifetime() }
|
||||
|
||||
/// Returns an identifier from this type in camelCase.
|
||||
pub fn to_name(&self) -> String {
|
||||
self.to_string().replace('<', "_").replace('>', "").to_upper_camel_case()
|
||||
}
|
||||
|
||||
/// Get code snippet for `as_ref`.
|
||||
pub fn code_as_ref(&self, name: &str) -> String { self.inner.code_as_ref(name) }
|
||||
}
|
||||
|
||||
impl From<InnerRustType> for RustType {
|
||||
fn from(inner: InnerRustType) -> Self { Self { inner, lifetime: false } }
|
||||
}
|
||||
|
||||
impl fmt::Display for RustType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.inner.fmt(f, self.lifetime, false) }
|
||||
}
|
||||
|
||||
fn get_false() -> bool { false }
|
||||
|
||||
/// Prepend `/// ` to each line of a string.
|
||||
pub fn doc_comment(s: &str) -> String { s.lines().map(|l| format!("/// {}\n", l)).collect() }
|
||||
|
||||
/// Indent a string by a given count using tabs.
|
||||
pub fn indent<S: AsRef<str>>(s: S, count: usize) -> String {
|
||||
let sref = s.as_ref();
|
||||
let line_count = sref.lines().count();
|
||||
let mut result = String::with_capacity(sref.len() + line_count * count * 4);
|
||||
for l in sref.lines() {
|
||||
if !l.is_empty() {
|
||||
result.push_str(&"\t".repeat(count));
|
||||
}
|
||||
result.push_str(l);
|
||||
result.push('\n');
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Unindent a string by a given count of tabs.
|
||||
pub fn unindent(s: &mut String) {
|
||||
std::mem::swap(&mut s.replace("\n\t", "\n"), s);
|
||||
if s.get(0..1) == Some("\t") {
|
||||
s.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an empty string if `s` is empty, otherwise `s` with braces.
|
||||
pub fn embrace(s: &str) -> String { if s.is_empty() { String::new() } else { format!("({})", s) } }
|
||||
@@ -0,0 +1,115 @@
|
||||
use heck::*;
|
||||
use once_cell::sync::Lazy;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::*;
|
||||
|
||||
pub const DATA_STR: &str =
|
||||
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/declarations/Messages.toml"));
|
||||
|
||||
pub static DATA: Lazy<MessageDeclarations> = Lazy::new(|| toml::from_str(DATA_STR).unwrap());
|
||||
|
||||
#[derive(Deserialize, Debug, Clone)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct MessageDeclarations {
|
||||
pub fields: Vec<Field>,
|
||||
pub msg_group: Vec<MessageGroup>,
|
||||
}
|
||||
|
||||
impl MessageDeclarations {
|
||||
pub fn get_message_opt(&self, name: &str) -> Option<&Message> {
|
||||
self.msg_group.iter().flat_map(|g| g.msg.iter()).find(|m| m.name == name)
|
||||
}
|
||||
|
||||
pub fn get_message(&self, name: &str) -> &Message {
|
||||
self.get_message_opt(name).unwrap_or_else(|| panic!("Cannot find message {}", name))
|
||||
}
|
||||
|
||||
pub fn get_message_group(&self, msg: &Message) -> &MessageGroup {
|
||||
for g in &self.msg_group {
|
||||
for m in &g.msg {
|
||||
if std::ptr::eq(m, msg) {
|
||||
return g;
|
||||
}
|
||||
}
|
||||
}
|
||||
panic!("Cannot find message group for message");
|
||||
}
|
||||
|
||||
pub fn get_field(&self, mut map: &str) -> &Field {
|
||||
if map.ends_with('?') {
|
||||
map = &map[..map.len() - 1];
|
||||
}
|
||||
if let Some(f) = self.fields.iter().find(|f| f.map == map) {
|
||||
f
|
||||
} else {
|
||||
panic!("Cannot find field {}", map);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn uses_lifetime(&self, msg: &Message) -> bool {
|
||||
for a in &msg.attributes {
|
||||
let field = self.get_field(a);
|
||||
if field.get_type(a).unwrap().to_ref(true).uses_lifetime() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Clone, Eq, Hash, PartialEq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Field {
|
||||
/// Internal name of this declarations file to map fields to messages.
|
||||
pub map: String,
|
||||
/// The name as called by TeamSpeak in messages.
|
||||
pub ts: String,
|
||||
/// The pretty name in PascalCase. This will be used for the fields in rust.
|
||||
pub pretty: String,
|
||||
#[serde(rename = "type")]
|
||||
pub type_s: String,
|
||||
#[serde(rename = "mod")]
|
||||
pub modifier: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Clone)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct MessageGroup {
|
||||
pub default: MessageGroupDefaults,
|
||||
pub msg: Vec<Message>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Clone)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct MessageGroupDefaults {
|
||||
pub s2c: bool,
|
||||
pub c2s: bool,
|
||||
pub response: bool,
|
||||
pub low: bool,
|
||||
pub np: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Clone)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Message {
|
||||
/// How we call this message.
|
||||
pub name: String,
|
||||
/// How TeamSpeak calls this message.
|
||||
pub notify: Option<String>,
|
||||
pub attributes: Vec<String>,
|
||||
}
|
||||
|
||||
impl Field {
|
||||
pub fn get_rust_name(&self) -> String { self.pretty.to_snake_case() }
|
||||
|
||||
/// Takes the attribute to look if it is optional
|
||||
pub fn get_type(&self, a: &str) -> Result<RustType> {
|
||||
RustType::with(&self.type_s, a.ends_with('?'), None, false, self.is_array())
|
||||
}
|
||||
|
||||
/// Returns if this field is optional in the message.
|
||||
pub fn is_opt(&self, msg: &Message) -> bool { !msg.attributes.iter().any(|a| *a == self.map) }
|
||||
|
||||
pub fn is_array(&self) -> bool { self.modifier.as_ref().map(|s| s == "array").unwrap_or(false) }
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
use std::collections::HashSet;
|
||||
use std::fmt::Write;
|
||||
use std::str::FromStr;
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::book::{BookDeclarations, Property, Struct};
|
||||
use crate::messages::{Field, Message, MessageDeclarations};
|
||||
use crate::*;
|
||||
|
||||
pub const DATA_STR: &str =
|
||||
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/declarations/MessagesToBook.toml"));
|
||||
|
||||
pub static DATA: Lazy<MessagesToBookDeclarations<'static>> = Lazy::new(|| {
|
||||
let rules: TomlStruct = toml::from_str(DATA_STR).unwrap();
|
||||
let book = &book::DATA;
|
||||
let messages = &messages::DATA;
|
||||
|
||||
let mut decls: Vec<_> = rules
|
||||
.rule
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let msg = messages.get_message(&r.from);
|
||||
let msg_fields =
|
||||
msg.attributes.iter().map(|a| messages.get_field(a)).collect::<Vec<_>>();
|
||||
let book_struct = book
|
||||
.structs
|
||||
.iter()
|
||||
.find(|s| s.name == r.to)
|
||||
.unwrap_or_else(|| panic!("Cannot find struct {}", r.to));
|
||||
|
||||
let mut ev = Event {
|
||||
op: r.operation.parse().expect("Failed to parse operation"),
|
||||
id: r.id.iter().map(|s| find_field(s, &msg_fields)).collect(),
|
||||
msg,
|
||||
book_struct,
|
||||
rules: r
|
||||
.properties
|
||||
.into_iter()
|
||||
.map(|p| {
|
||||
assert!(p.is_valid());
|
||||
|
||||
let find_prop = |name, book_struct: &'static Struct| -> &'static Property {
|
||||
if let Some(prop) =
|
||||
book_struct.properties.iter().find(|p| p.name == name)
|
||||
{
|
||||
return prop;
|
||||
}
|
||||
panic!(
|
||||
"No such (nested) property {} found in struct {}",
|
||||
name, book_struct.name,
|
||||
);
|
||||
};
|
||||
|
||||
if p.function.is_some() {
|
||||
RuleKind::Function {
|
||||
name: p.function.unwrap(),
|
||||
to: p
|
||||
.tolist
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|p| find_prop(p, book_struct))
|
||||
.collect(),
|
||||
}
|
||||
} else {
|
||||
RuleKind::Map {
|
||||
from: find_field(&p.from.unwrap(), &msg_fields),
|
||||
to: find_prop(p.to.unwrap(), book_struct),
|
||||
op: p
|
||||
.operation
|
||||
.map(|s| s.parse().expect("Invalid operation for property"))
|
||||
.unwrap_or(RuleOp::Update),
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
|
||||
// Add attributes with the same name automatically (if they are not
|
||||
// yet there).
|
||||
let used_flds = ev
|
||||
.rules
|
||||
.iter()
|
||||
.filter_map(|f| match *f {
|
||||
RuleKind::Map { from, .. } => Some(from),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
let mut used_props = vec![];
|
||||
for rule in &ev.rules {
|
||||
if let RuleKind::Function { to, .. } = rule {
|
||||
for p in to {
|
||||
used_props.push(p.name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for fld in &msg_fields {
|
||||
if used_flds.contains(fld) {
|
||||
continue;
|
||||
}
|
||||
if let Some(prop) = book
|
||||
.get_struct(&ev.book_struct.name)
|
||||
.properties
|
||||
.iter()
|
||||
.find(|p| p.name == fld.pretty)
|
||||
{
|
||||
if used_props.contains(&prop.name) {
|
||||
continue;
|
||||
}
|
||||
|
||||
ev.rules.push(RuleKind::Map { from: fld, to: prop, op: RuleOp::Update });
|
||||
}
|
||||
}
|
||||
|
||||
ev
|
||||
})
|
||||
.collect();
|
||||
|
||||
// InitServer is done manually
|
||||
decls.retain(|ev| ev.msg.name != "InitServer");
|
||||
|
||||
MessagesToBookDeclarations { book, messages, decls }
|
||||
});
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct MessagesToBookDeclarations<'a> {
|
||||
pub book: &'a BookDeclarations,
|
||||
pub messages: &'a MessageDeclarations,
|
||||
pub decls: Vec<Event<'a>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Event<'a> {
|
||||
pub op: RuleOp,
|
||||
/// Unique access tuple to get the property
|
||||
pub id: Vec<&'a Field>,
|
||||
pub msg: &'a Message,
|
||||
pub book_struct: &'a Struct,
|
||||
pub rules: Vec<RuleKind<'a>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum RuleKind<'a> {
|
||||
Map { from: &'a Field, to: &'a Property, op: RuleOp },
|
||||
Function { name: String, to: Vec<&'a Property> },
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub enum RuleOp {
|
||||
Add,
|
||||
Remove,
|
||||
Update,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize, Debug)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct TomlStruct {
|
||||
rule: Vec<Rule>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize, Debug)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Rule {
|
||||
id: Vec<String>,
|
||||
from: String,
|
||||
to: String,
|
||||
operation: String,
|
||||
#[serde(default = "Vec::new")]
|
||||
properties: Vec<RuleProperty>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize, Debug)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct RuleProperty {
|
||||
from: Option<String>,
|
||||
to: Option<String>,
|
||||
operation: Option<String>,
|
||||
|
||||
function: Option<String>,
|
||||
tolist: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
impl Event<'_> {
|
||||
/// Fill the id of a `PropertyId`.
|
||||
///
|
||||
/// `msg` is the name of the message object.
|
||||
pub fn get_id_args(&self, msg: &str) -> String {
|
||||
let mut res = String::new();
|
||||
for f in &self.id {
|
||||
if !res.is_empty() {
|
||||
res.push_str(", ");
|
||||
}
|
||||
if !f.get_type("").unwrap().is_primitive() {
|
||||
res.push('&');
|
||||
}
|
||||
let _ = write!(res, "{}.{}", msg, f.get_rust_name());
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
/// Create a `PropertyId` from a message struct.
|
||||
///
|
||||
/// `msg` is the name of the message object.
|
||||
pub fn get_property_id(&self, p: &Property, from: &Field, msg: &str) -> String {
|
||||
let mut ids = self.get_id_args(msg);
|
||||
if let Some(m) = &p.modifier {
|
||||
if !ids.is_empty() {
|
||||
ids.push_str(", ");
|
||||
}
|
||||
if m == "map" || m == "array" || m == "set" {
|
||||
let _ = write!(ids, "{}.{}", msg, from.get_rust_name());
|
||||
} else {
|
||||
panic!("Unknown modifier {}", m);
|
||||
}
|
||||
}
|
||||
format!("PropertyId::{}{}{}", self.book_struct.name, p.get_name(), embrace(&ids))
|
||||
}
|
||||
}
|
||||
|
||||
impl RuleProperty {
|
||||
fn is_valid(&self) -> bool {
|
||||
if self.from.is_some() {
|
||||
self.to.is_some() && self.function.is_none() && self.tolist.is_none()
|
||||
} else {
|
||||
self.from.is_none()
|
||||
&& self.to.is_none()
|
||||
&& self.operation.is_none()
|
||||
&& self.function.is_some()
|
||||
&& self.tolist.is_some()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for RuleOp {
|
||||
type Err = fmt::Error;
|
||||
fn from_str(s: &str) -> Result<Self> {
|
||||
if s == "add" {
|
||||
Ok(RuleOp::Add)
|
||||
} else if s == "remove" {
|
||||
Ok(RuleOp::Remove)
|
||||
} else if s == "update" {
|
||||
Ok(RuleOp::Update)
|
||||
} else {
|
||||
eprintln!("Cannot parse operation, needs to be add, remove or update");
|
||||
Err(fmt::Error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// the in rust callable name (in PascalCase) from the field
|
||||
fn find_field<'a>(name: &str, msg_fields: &[&'a Field]) -> &'a Field {
|
||||
msg_fields
|
||||
.iter()
|
||||
.find(|f| f.pretty == name)
|
||||
.unwrap_or_else(|| panic!("Cannot find field '{}'", name))
|
||||
}
|
||||
|
||||
impl<'a> RuleKind<'a> {
|
||||
pub fn is_function(&self) -> bool { matches!(self, RuleKind::Function { .. }) }
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use std::result::Result;
|
||||
|
||||
use crate::*;
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
|
||||
pub const DATA_STR: &str =
|
||||
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/declarations/Permissions.csv"));
|
||||
|
||||
pub static DATA: Lazy<Permissions> = Lazy::new(|| {
|
||||
Permissions(
|
||||
csv::Reader::from_reader(DATA_STR.as_bytes())
|
||||
.deserialize()
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.unwrap(),
|
||||
)
|
||||
});
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct EnumValue {
|
||||
pub name: String,
|
||||
pub doc: String,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub struct Permissions(pub Vec<EnumValue>);
|
||||
@@ -0,0 +1,94 @@
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
use std::result::Result;
|
||||
|
||||
use crate::*;
|
||||
|
||||
use base64::prelude::*;
|
||||
use once_cell::sync::Lazy;
|
||||
|
||||
pub const DATA_STR: &str =
|
||||
include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/declarations/Versions.csv"));
|
||||
|
||||
pub static DATA: Lazy<Versions> = Lazy::new(|| {
|
||||
let mut table = csv::Reader::from_reader(DATA_STR.as_bytes());
|
||||
let mut vs = Versions(table.deserialize().collect::<Result<Vec<_>, _>>().unwrap());
|
||||
|
||||
// Add count if necessary
|
||||
let mut counts: HashMap<_, u32> = HashMap::new();
|
||||
for v in &vs.0 {
|
||||
let key = VersionKey::new(v);
|
||||
*counts.entry(key).or_default() += 1;
|
||||
}
|
||||
counts.retain(|_, c| *c > 1);
|
||||
|
||||
for v in vs.0.iter_mut().rev() {
|
||||
let key = VersionKey::new(v);
|
||||
if let Some(count) = counts.get_mut(&key) {
|
||||
v.count = *count;
|
||||
*count -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
vs
|
||||
});
|
||||
|
||||
#[derive(Debug, Deserialize, Clone)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Version {
|
||||
pub version: String,
|
||||
pub platform: String,
|
||||
pub hash: String,
|
||||
#[serde(default)]
|
||||
count: u32,
|
||||
}
|
||||
|
||||
impl Version {
|
||||
pub fn get_enum_name(&self) -> String {
|
||||
let mut res = String::new();
|
||||
res.push_str(&self.platform.replace([' ', '.'], "_"));
|
||||
let ver = self.version.split(' ').next().unwrap().replace('-', "_");
|
||||
for num in ver.split('.') {
|
||||
res.push('_');
|
||||
if num != "?" {
|
||||
res.push_str(num);
|
||||
} else {
|
||||
res.push('X');
|
||||
}
|
||||
}
|
||||
if self.count != 0 {
|
||||
res.push_str("__");
|
||||
res.push_str(&self.count.to_string());
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
pub fn get_sign_array(&self) -> String {
|
||||
let mut res = String::new();
|
||||
for b in BASE64_STANDARD.decode(&self.hash).unwrap() {
|
||||
if !res.is_empty() {
|
||||
res.push_str(", ");
|
||||
}
|
||||
let _ = write!(res, "{:#x}", b);
|
||||
}
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
struct VersionKey {
|
||||
pub version: String,
|
||||
pub platform: String,
|
||||
}
|
||||
|
||||
impl VersionKey {
|
||||
fn new(v: &Version) -> Self {
|
||||
Self {
|
||||
version: v.version.split(' ').next().unwrap().to_string(),
|
||||
platform: v.platform.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub struct Versions(pub Vec<Version>);
|
||||
Reference in new issue
Block a user