rhai/src/serde/metadata.rs

269 lines
8.4 KiB
Rust
Raw Normal View History

2021-12-25 23:49:14 +08:00
//! Serialization of functions metadata.
2021-12-06 20:52:47 +08:00
#![cfg(feature = "metadata")]
2022-01-13 18:13:38 +08:00
use crate::module::{calc_native_fn_hash, FuncInfo};
2022-07-25 17:42:15 +08:00
use crate::{calc_fn_hash, Engine, SmartString, AST};
2020-12-19 19:42:18 +08:00
use serde::{Deserialize, Serialize};
2021-04-17 15:15:54 +08:00
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
2022-06-11 16:01:15 +08:00
use std::{borrow::Cow, cmp::Ordering, collections::BTreeMap};
2020-12-19 19:42:18 +08:00
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
enum FnType {
Script,
Native,
}
2022-01-29 11:09:43 +08:00
#[cfg(not(feature = "no_module"))]
2020-12-19 19:42:18 +08:00
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
enum FnNamespace {
Global,
Internal,
}
2022-01-29 11:09:43 +08:00
#[cfg(not(feature = "no_module"))]
2020-12-19 19:42:18 +08:00
impl From<crate::FnNamespace> for FnNamespace {
fn from(value: crate::FnNamespace) -> Self {
match value {
crate::FnNamespace::Global => Self::Global,
crate::FnNamespace::Internal => Self::Internal,
}
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
enum FnAccess {
Public,
Private,
}
impl From<crate::FnAccess> for FnAccess {
fn from(value: crate::FnAccess) -> Self {
match value {
crate::FnAccess::Public => Self::Public,
crate::FnAccess::Private => Self::Private,
}
}
}
2022-01-13 18:13:38 +08:00
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
2020-12-19 19:42:18 +08:00
#[serde(rename_all = "camelCase")]
struct FnParam<'a> {
2022-01-13 18:13:38 +08:00
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<&'a str>,
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
2022-01-17 21:51:04 +08:00
pub typ: Option<Cow<'a, str>>,
2020-12-19 19:42:18 +08:00
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct FnMetadata<'a> {
2021-12-06 11:12:54 +08:00
pub base_hash: u64,
pub full_hash: u64,
2022-01-29 11:09:43 +08:00
#[cfg(not(feature = "no_module"))]
2020-12-19 19:42:18 +08:00
pub namespace: FnNamespace,
pub access: FnAccess,
pub name: String,
#[serde(rename = "type")]
pub typ: FnType,
pub num_params: usize,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub params: Vec<FnParam<'a>>,
2022-01-13 22:51:10 +08:00
// No idea why the following is needed otherwise serde comes back with a lifetime error
2020-12-19 19:42:18 +08:00
#[serde(default, skip_serializing_if = "Option::is_none")]
2022-01-13 22:51:10 +08:00
pub _dummy: Option<&'a str>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub return_type: String,
2020-12-20 12:27:47 +08:00
pub signature: String,
2021-01-18 10:23:41 +08:00
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub doc_comments: Vec<&'a str>,
2020-12-19 19:42:18 +08:00
}
impl PartialOrd for FnMetadata<'_> {
2022-01-13 19:07:56 +08:00
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2021-05-25 10:54:48 +08:00
Some(self.cmp(other))
2020-12-20 12:27:47 +08:00
}
}
impl Ord for FnMetadata<'_> {
2020-12-20 12:27:47 +08:00
fn cmp(&self, other: &Self) -> Ordering {
2021-05-25 10:54:48 +08:00
match self.name.cmp(&other.name) {
2022-01-13 18:13:38 +08:00
Ordering::Equal => self.num_params.cmp(&other.num_params),
2021-05-25 10:54:48 +08:00
cmp => cmp,
}
2020-12-20 12:27:47 +08:00
}
}
2022-01-13 18:13:38 +08:00
impl<'a> From<&'a FuncInfo> for FnMetadata<'a> {
fn from(info: &'a FuncInfo) -> Self {
2022-01-13 19:07:56 +08:00
let base_hash = calc_fn_hash(&info.metadata.name, info.metadata.params);
2021-12-06 11:12:54 +08:00
let (typ, full_hash) = if info.func.is_script() {
(FnType::Script, base_hash)
} else {
(
FnType::Native,
2022-06-11 16:01:15 +08:00
calc_native_fn_hash(None, &info.metadata.name, &info.param_types),
2021-12-06 11:12:54 +08:00
)
};
2020-12-19 19:42:18 +08:00
Self {
2021-12-06 11:12:54 +08:00
base_hash,
full_hash,
2022-01-29 11:09:43 +08:00
#[cfg(not(feature = "no_module"))]
2022-01-13 19:07:56 +08:00
namespace: info.metadata.namespace.into(),
access: info.metadata.access.into(),
name: info.metadata.name.to_string(),
2021-12-06 11:12:54 +08:00
typ,
2022-01-13 19:07:56 +08:00
num_params: info.metadata.params,
2021-01-18 10:23:41 +08:00
params: info
2022-01-13 19:07:56 +08:00
.metadata
.params_info
2021-01-18 10:23:41 +08:00
.iter()
.map(|s| {
let mut seg = s.splitn(2, ':');
2022-01-13 18:13:38 +08:00
let name = match seg.next().unwrap().trim() {
"_" => None,
s => Some(s),
};
2022-01-17 21:51:04 +08:00
let typ = seg.next().map(|s| FuncInfo::format_type(s, false));
2021-01-18 10:23:41 +08:00
FnParam { name, typ }
})
.collect(),
2022-01-13 22:51:10 +08:00
_dummy: None,
2022-01-17 21:51:04 +08:00
return_type: FuncInfo::format_type(&info.metadata.return_type, true).into_owned(),
2020-12-20 12:27:47 +08:00
signature: info.gen_signature(),
2020-12-19 19:42:18 +08:00
doc_comments: if info.func.is_script() {
2021-01-18 10:56:42 +08:00
#[cfg(feature = "no_function")]
2021-12-17 16:07:13 +08:00
unreachable!("script-defined functions should not exist under no_function");
2021-01-18 10:56:42 +08:00
#[cfg(not(feature = "no_function"))]
2021-12-17 16:07:13 +08:00
info.func
.get_script_fn_def()
.expect("script-defined function")
.comments
2022-03-06 16:37:27 +08:00
.iter()
2022-07-05 16:26:38 +08:00
.map(<_>::as_ref)
2022-03-06 16:37:27 +08:00
.collect()
2020-12-19 19:42:18 +08:00
} else {
2022-07-05 16:26:38 +08:00
info.metadata.comments.iter().map(<_>::as_ref).collect()
2020-12-19 19:42:18 +08:00
},
}
}
}
#[derive(Debug, Clone, Serialize)]
2020-12-19 19:42:18 +08:00
#[serde(rename_all = "camelCase")]
struct ModuleMetadata<'a> {
2022-07-25 17:42:15 +08:00
#[cfg(feature = "metadata")]
#[serde(skip_serializing_if = "SmartString::is_empty")]
pub doc: SmartString,
2020-12-19 19:42:18 +08:00
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub modules: BTreeMap<&'a str, Self>,
2020-12-19 19:42:18 +08:00
#[serde(skip_serializing_if = "Vec::is_empty")]
pub functions: Vec<FnMetadata<'a>>,
2020-12-19 19:42:18 +08:00
}
impl ModuleMetadata<'_> {
2021-09-11 19:40:40 +08:00
#[inline(always)]
pub fn new() -> Self {
Self {
2022-07-25 17:42:15 +08:00
#[cfg(feature = "metadata")]
doc: SmartString::new_const(),
modules: BTreeMap::new(),
functions: Vec::new(),
}
2021-09-11 19:40:40 +08:00
}
}
impl<'a> From<&'a crate::Module> for ModuleMetadata<'a> {
fn from(module: &'a crate::Module) -> Self {
2020-12-20 12:27:47 +08:00
let mut functions: Vec<_> = module.iter_fn().map(|f| f.into()).collect();
functions.sort();
2020-12-19 19:42:18 +08:00
Self {
2022-07-25 17:42:15 +08:00
doc: module.doc().into(),
2020-12-19 19:42:18 +08:00
modules: module
.iter_sub_modules()
.map(|(name, m)| (name, m.as_ref().into()))
2020-12-19 19:42:18 +08:00
.collect(),
2020-12-20 12:27:47 +08:00
functions,
2020-12-19 19:42:18 +08:00
}
}
}
impl Engine {
2021-07-25 22:56:05 +08:00
/// _(metadata)_ Generate a list of all functions (including those defined in an
/// [`AST`][crate::AST]) in JSON format.
/// Exported under the `metadata` feature only.
2020-12-19 19:42:18 +08:00
///
/// Functions from the following sources are included:
/// 1) Functions defined in an [`AST`][crate::AST]
2020-12-19 19:42:18 +08:00
/// 2) Functions registered into the global namespace
2020-12-22 23:45:14 +08:00
/// 3) Functions in static modules
/// 4) Functions in registered global packages
/// 5) Functions in standard packages (optional)
pub fn gen_fn_metadata_with_ast_to_json(
2020-12-19 19:42:18 +08:00
&self,
ast: &AST,
include_packages: bool,
2020-12-19 19:42:18 +08:00
) -> serde_json::Result<String> {
let _ast = ast;
2021-09-11 19:40:40 +08:00
let mut global = ModuleMetadata::new();
2020-12-19 19:42:18 +08:00
2022-01-29 11:09:43 +08:00
#[cfg(not(feature = "no_module"))]
2022-01-28 18:59:18 +08:00
for (name, m) in &self.global_sub_modules {
global.modules.insert(name, m.as_ref().into());
2022-01-28 18:59:18 +08:00
}
2020-12-19 19:42:18 +08:00
self.global_modules
.iter()
.filter(|m| include_packages || !m.standard)
.flat_map(|m| m.iter_fn())
.for_each(|f| {
2022-01-29 11:09:43 +08:00
#[allow(unused_mut)]
let mut meta: FnMetadata = f.into();
2022-01-29 11:09:43 +08:00
#[cfg(not(feature = "no_module"))]
{
meta.namespace = FnNamespace::Global;
}
global.functions.push(meta);
});
2020-12-19 19:42:18 +08:00
2021-01-18 10:56:42 +08:00
#[cfg(not(feature = "no_function"))]
2022-01-28 18:59:18 +08:00
for f in _ast.shared_lib().iter_fn() {
2022-01-29 11:09:43 +08:00
#[allow(unused_mut)]
let mut meta: FnMetadata = f.into();
2022-01-29 11:09:43 +08:00
#[cfg(not(feature = "no_module"))]
{
meta.namespace = FnNamespace::Global;
}
global.functions.push(meta);
2022-01-28 18:59:18 +08:00
}
2020-12-19 19:42:18 +08:00
2020-12-20 12:27:47 +08:00
global.functions.sort();
2022-07-25 17:42:15 +08:00
#[cfg(feature = "metadata")]
{
global.doc = ast.doc().into();
}
2020-12-19 19:42:18 +08:00
serde_json::to_string_pretty(&global)
}
/// Generate a list of all functions in JSON format.
/// Exported under the `metadata` feature only.
///
/// Functions from the following sources are included:
/// 1) Functions registered into the global namespace
2020-12-22 23:45:14 +08:00
/// 2) Functions in static modules
/// 3) Functions in global modules (optional)
2021-11-25 17:09:00 +08:00
#[inline(always)]
pub fn gen_fn_metadata_to_json(&self, include_packages: bool) -> serde_json::Result<String> {
self.gen_fn_metadata_with_ast_to_json(&AST::empty(), include_packages)
}
2020-12-19 19:42:18 +08:00
}