rhai/src/serde/metadata.rs

304 lines
9.7 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-12-21 13:54:54 +08:00
use crate::api::formatting::format_type;
2022-11-23 11:36:30 +08:00
use crate::module::{calc_native_fn_hash, FuncInfo, ModuleFlags};
2022-08-18 21:16:42 +08:00
use crate::{calc_fn_hash, Engine, FnAccess, SmartString, StaticVec, AST};
2022-08-14 14:20:37 +08:00
use serde::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
2022-08-14 14:20:37 +08:00
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize)]
2020-12-19 19:42:18 +08:00
#[serde(rename_all = "camelCase")]
enum FnType {
Script,
Native,
}
2022-08-14 14:20:37 +08:00
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize)]
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
}
2022-08-14 14:20:37 +08:00
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize)]
2020-12-19 19:42:18 +08:00
#[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"))]
2022-08-18 21:16:42 +08:00
pub namespace: crate::FnNamespace,
2020-12-19 19:42:18 +08:00
pub access: FnAccess,
2022-08-14 14:20:37 +08:00
pub name: &'a str,
2023-03-17 06:46:43 +08:00
#[cfg(not(feature = "no_function"))]
2023-03-17 06:28:00 +08:00
pub is_anonymous: bool,
2020-12-19 19:42:18 +08:00
#[serde(rename = "type")]
pub typ: FnType,
2023-03-22 16:05:25 +08:00
#[cfg(not(feature = "no_object"))]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub this_type: Option<&'a str>,
2020-12-19 19:42:18 +08:00
pub num_params: usize,
2022-08-14 14:20:37 +08:00
#[serde(default, skip_serializing_if = "StaticVec::is_empty")]
pub params: StaticVec<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>,
2022-08-14 14:20:37 +08:00
#[serde(default, skip_serializing_if = "str::is_empty")]
pub return_type: Cow<'a, str>,
pub signature: SmartString,
#[serde(default, skip_serializing_if = "StaticVec::is_empty")]
pub doc_comments: StaticVec<&'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 {
2022-08-29 14:27:05 +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-11-25 12:14:37 +08:00
let base_hash = calc_fn_hash(None, &info.metadata.name, info.metadata.num_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-11-25 12:14:37 +08:00
calc_native_fn_hash(None, &info.metadata.name, &info.metadata.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-11-25 12:14:37 +08:00
namespace: info.metadata.namespace,
access: info.metadata.access,
name: &info.metadata.name,
2023-03-17 06:46:43 +08:00
#[cfg(not(feature = "no_function"))]
is_anonymous: crate::parser::is_anonymous_fn(&info.metadata.name),
2021-12-06 11:12:54 +08:00
typ,
2023-03-22 16:05:25 +08:00
#[cfg(not(feature = "no_object"))]
this_type: info.metadata.this_type.as_ref().map(|s| s.as_str()),
2022-11-25 12:14:37 +08:00
num_params: info.metadata.num_params,
2021-01-18 10:23:41 +08:00
params: info
2022-11-25 12:14:37 +08:00
.metadata
2022-01-13 19:07:56 +08:00
.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-09-08 10:52:58 +08:00
let typ = seg.next().map(|s| 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-11-25 12:14:37 +08:00
return_type: format_type(&info.metadata.return_type, true),
2022-08-14 14:20:37 +08:00
signature: info.gen_signature().into(),
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-11-25 12:14:37 +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")]
2022-08-14 14:20:37 +08:00
#[serde(skip_serializing_if = "str::is_empty")]
pub doc: &'a str,
2020-12-19 19:42:18 +08:00
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub modules: BTreeMap<&'a str, Self>,
2022-08-14 14:20:37 +08:00
#[serde(skip_serializing_if = "StaticVec::is_empty")]
pub functions: StaticVec<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")]
2022-08-14 14:20:37 +08:00
doc: "",
modules: BTreeMap::new(),
2022-08-14 14:20:37 +08:00
functions: StaticVec::new_const(),
}
2021-09-11 19:40:40 +08:00
}
}
impl<'a> From<&'a crate::Module> for ModuleMetadata<'a> {
fn from(module: &'a crate::Module) -> Self {
2022-08-14 14:20:37 +08:00
let mut functions: StaticVec<_> = module.iter_fn().map(Into::into).collect();
2020-12-20 12:27:47 +08:00
functions.sort();
2020-12-19 19:42:18 +08:00
Self {
2022-08-29 14:27:05 +08:00
doc: module.doc(),
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
}
}
}
/// Generate a list of all functions in JSON format.
pub fn gen_metadata_to_json(
engine: &Engine,
ast: Option<&AST>,
include_standard_packages: bool,
) -> serde_json::Result<String> {
let _ast = ast;
2022-12-01 23:35:26 +08:00
#[cfg(feature = "metadata")]
let mut global_doc = String::new();
let mut global = ModuleMetadata::new();
#[cfg(not(feature = "no_module"))]
2022-11-25 23:03:20 +08:00
for (name, m) in engine.global_sub_modules.as_deref().into_iter().flatten() {
global.modules.insert(name, m.as_ref().into());
}
2022-11-23 16:14:11 +08:00
let exclude_flags = if include_standard_packages {
2022-11-23 11:36:30 +08:00
ModuleFlags::empty()
2022-11-23 16:14:11 +08:00
} else {
ModuleFlags::STANDARD_LIB
2022-11-23 11:36:30 +08:00
};
engine
.global_modules
.iter()
2022-11-23 11:36:30 +08:00
.filter(|m| !m.flags.contains(exclude_flags))
2022-12-01 23:35:26 +08:00
.flat_map(|m| {
#[cfg(feature = "metadata")]
if !m.doc().is_empty() {
if !global_doc.is_empty() {
global_doc.push('\n');
}
global_doc.push_str(m.doc());
}
m.iter_fn()
})
.for_each(|f| {
#[allow(unused_mut)]
let mut meta: FnMetadata = f.into();
#[cfg(not(feature = "no_module"))]
{
2022-08-18 21:16:42 +08:00
meta.namespace = crate::FnNamespace::Global;
}
global.functions.push(meta);
});
#[cfg(not(feature = "no_function"))]
if let Some(ast) = _ast {
for f in ast.shared_lib().iter_fn() {
#[allow(unused_mut)]
let mut meta: FnMetadata = f.into();
#[cfg(not(feature = "no_module"))]
{
2022-08-18 21:16:42 +08:00
meta.namespace = crate::FnNamespace::Global;
}
global.functions.push(meta);
}
}
global.functions.sort();
#[cfg(feature = "metadata")]
if let Some(ast) = _ast {
2022-12-01 23:35:26 +08:00
if !ast.doc().is_empty() {
if !global_doc.is_empty() {
global_doc.push('\n');
}
global_doc.push_str(ast.doc());
}
}
#[cfg(feature = "metadata")]
{
global.doc = &global_doc;
}
serde_json::to_string_pretty(&global)
}
#[cfg(feature = "internals")]
impl crate::api::definitions::Definitions<'_> {
/// Generate a list of all functions in JSON format.
///
/// Functions from the following sources are included:
/// 1) Functions defined in an [`AST`][crate::AST]
/// 2) Functions registered into the global namespace
/// 3) Functions in static modules
/// 4) Functions in registered global packages
/// 5) Functions in standard packages (optional)
#[inline(always)]
pub fn json(&self) -> serde_json::Result<String> {
gen_metadata_to_json(self.engine(), None, self.config().include_standard_packages)
}
}
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)
#[inline(always)]
pub fn gen_fn_metadata_with_ast_to_json(
2020-12-19 19:42:18 +08:00
&self,
ast: &AST,
include_standard_packages: bool,
2020-12-19 19:42:18 +08:00
) -> serde_json::Result<String> {
gen_metadata_to_json(self, Some(ast), include_standard_packages)
2020-12-19 19:42:18 +08:00
}
/// 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 registered global packages
/// 4) Functions in standard packages (optional)
2021-11-25 17:09:00 +08:00
#[inline(always)]
pub fn gen_fn_metadata_to_json(
&self,
include_standard_packages: bool,
) -> serde_json::Result<String> {
gen_metadata_to_json(self, None, include_standard_packages)
}
2020-12-19 19:42:18 +08:00
}