rhai/src/serde/metadata.rs

291 lines
8.9 KiB
Rust
Raw Normal View History

2020-12-19 12:42:18 +01:00
use crate::{Engine, AST};
use serde::{Deserialize, Serialize};
2021-04-17 09:15:54 +02:00
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{cmp::Ordering, collections::BTreeMap};
2020-12-19 12:42:18 +01:00
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
enum FnType {
Script,
Native,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
enum FnNamespace {
Global,
Internal,
}
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,
}
}
}
2021-07-26 16:22:27 +02:00
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
2020-12-19 12:42:18 +01:00
#[serde(rename_all = "camelCase")]
struct FnParam {
2021-11-11 06:55:52 +01:00
pub name: Box<str>,
2020-12-19 12:42:18 +01:00
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
2021-11-11 06:55:52 +01:00
pub typ: Option<Box<str>>,
2020-12-19 12:42:18 +01:00
}
2020-12-20 05:27:47 +01:00
impl PartialOrd for FnParam {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2021-08-26 17:58:41 +02:00
Some(
match self
.name
.partial_cmp(&other.name)
.expect("String::partial_cmp should succeed")
{
Ordering::Less => Ordering::Less,
Ordering::Greater => Ordering::Greater,
Ordering::Equal => match (self.typ.is_none(), other.typ.is_none()) {
(true, true) => Ordering::Equal,
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
(false, false) => self
.typ
.as_ref()
.expect("`typ` is not `None`")
.partial_cmp(other.typ.as_ref().expect("`typ` is not `None`"))
.expect("String::partial_cmp should succeed"),
},
2020-12-20 05:27:47 +01:00
},
2021-08-26 17:58:41 +02:00
)
2020-12-20 05:27:47 +01:00
}
}
2021-07-26 16:22:27 +02:00
impl Ord for FnParam {
fn cmp(&self, other: &Self) -> Ordering {
match self.name.cmp(&other.name) {
Ordering::Equal => self.typ.cmp(&other.typ),
cmp => cmp,
}
}
}
2020-12-19 12:42:18 +01:00
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct FnMetadata {
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>,
#[serde(default, skip_serializing_if = "Option::is_none")]
2021-11-11 06:55:52 +01:00
pub return_type: Option<Box<str>>,
2020-12-20 05:27:47 +01:00
pub signature: String,
2021-01-18 03:23:41 +01:00
#[serde(default, skip_serializing_if = "Vec::is_empty")]
2021-11-11 06:55:52 +01:00
pub doc_comments: Vec<Box<str>>,
2020-12-19 12:42:18 +01:00
}
2020-12-20 05:27:47 +01:00
impl PartialOrd for FnMetadata {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2021-05-25 04:54:48 +02:00
Some(self.cmp(other))
2020-12-20 05:27:47 +01:00
}
}
impl Ord for FnMetadata {
fn cmp(&self, other: &Self) -> Ordering {
2021-05-25 04:54:48 +02:00
match self.name.cmp(&other.name) {
Ordering::Equal => match self.num_params.cmp(&other.num_params) {
Ordering::Equal => self.params.cmp(&other.params),
cmp => cmp,
},
cmp => cmp,
}
2020-12-20 05:27:47 +01:00
}
}
2020-12-19 12:42:18 +01:00
impl From<&crate::module::FuncInfo> for FnMetadata {
fn from(info: &crate::module::FuncInfo) -> Self {
Self {
namespace: info.namespace.into(),
access: info.access.into(),
name: info.name.to_string(),
typ: if info.func.is_script() {
FnType::Script
} else {
FnType::Native
},
num_params: info.params,
2021-01-18 03:23:41 +01:00
params: info
.param_names
.iter()
.take(info.params)
.map(|s| {
let mut seg = s.splitn(2, ':');
let name = seg
.next()
2021-11-11 06:55:52 +01:00
.map(|s| s.trim().into())
.unwrap_or_else(|| "_".into());
let typ = seg.next().map(|s| s.trim().into());
2021-01-18 03:23:41 +01:00
FnParam { name, typ }
})
.collect(),
return_type: info
.param_names
.last()
2021-11-11 06:55:52 +01:00
.map(|s| s.as_str().into())
.or_else(|| Some("()".into())),
2020-12-20 05:27:47 +01:00
signature: info.gen_signature(),
2020-12-19 12:42:18 +01:00
doc_comments: if info.func.is_script() {
2021-01-18 03:56:42 +01:00
#[cfg(feature = "no_function")]
{
2021-03-06 15:07:20 +01:00
unreachable!("scripted functions should not exist under no_function")
2021-01-18 03:56:42 +01:00
}
#[cfg(not(feature = "no_function"))]
{
2021-06-28 12:29:53 +02:00
info.func
.get_script_fn_def()
2021-08-26 17:58:41 +02:00
.expect("scripted function")
2021-06-28 12:29:53 +02:00
.comments
2021-11-12 06:25:57 +01:00
.as_ref()
.map_or_else(|| Vec::new(), |v| v.to_vec())
2021-01-18 03:56:42 +01:00
}
2020-12-19 12:42:18 +01:00
} else {
Vec::new()
2020-12-19 12:42:18 +01:00
},
}
}
}
2021-03-07 15:37:23 +01:00
#[cfg(not(feature = "no_function"))]
impl From<crate::ast::ScriptFnMetadata<'_>> for FnMetadata {
fn from(info: crate::ast::ScriptFnMetadata) -> Self {
2020-12-19 12:42:18 +01:00
Self {
namespace: FnNamespace::Global,
access: info.access.into(),
name: info.name.to_string(),
typ: FnType::Script,
num_params: info.params.len(),
params: info
.params
.iter()
2021-11-11 06:55:52 +01:00
.map(|&s| FnParam {
name: s.into(),
typ: Some("Dynamic".into()),
2020-12-19 12:42:18 +01:00
})
.collect(),
2021-11-11 06:55:52 +01:00
return_type: Some("Dynamic".into()),
2020-12-20 05:27:47 +01:00
signature: info.to_string(),
2021-11-11 06:55:52 +01:00
doc_comments: info.comments.iter().map(|&s| s.into()).collect(),
2020-12-19 12:42:18 +01:00
}
}
}
#[derive(Debug, Clone, Serialize)]
2020-12-19 12:42:18 +01:00
#[serde(rename_all = "camelCase")]
struct ModuleMetadata {
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub modules: BTreeMap<String, Self>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub functions: Vec<FnMetadata>,
}
2021-09-11 13:40:40 +02:00
impl ModuleMetadata {
#[inline(always)]
pub fn new() -> Self {
Self {
modules: BTreeMap::new(),
functions: Vec::new(),
}
2021-09-11 13:40:40 +02:00
}
}
2020-12-19 12:42:18 +01:00
impl From<&crate::Module> for ModuleMetadata {
fn from(module: &crate::Module) -> Self {
2020-12-20 05:27:47 +01:00
let mut functions: Vec<_> = module.iter_fn().map(|f| f.into()).collect();
functions.sort();
2020-12-19 12:42:18 +01:00
Self {
modules: module
.iter_sub_modules()
.map(|(name, m)| (name.to_string(), m.as_ref().into()))
.collect(),
2020-12-20 05:27:47 +01:00
functions,
2020-12-19 12:42:18 +01:00
}
}
}
2021-01-18 03:23:41 +01:00
#[cfg(feature = "metadata")]
2020-12-19 12:42:18 +01:00
impl Engine {
2021-07-25 16:56:05 +02: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 12:42:18 +01:00
///
/// Functions from the following sources are included:
/// 1) Functions defined in an [`AST`][crate::AST]
2020-12-19 12:42:18 +01:00
/// 2) Functions registered into the global namespace
2020-12-22 16:45:14 +01:00
/// 3) Functions in static modules
/// 4) Functions in global modules (optional)
pub fn gen_fn_metadata_with_ast_to_json(
2020-12-19 12:42:18 +01:00
&self,
ast: &AST,
2020-12-22 16:45:14 +01:00
include_global: bool,
2020-12-19 12:42:18 +01:00
) -> serde_json::Result<String> {
let _ast = ast;
2021-09-11 13:40:40 +02:00
let mut global = ModuleMetadata::new();
2020-12-19 12:42:18 +01:00
2020-12-22 16:45:14 +01:00
if include_global {
self.global_modules
2020-12-19 12:42:18 +01:00
.iter()
2021-08-30 04:25:24 +02:00
.take(self.global_modules.len() - 1)
2021-03-17 06:30:47 +01:00
.flat_map(|m| m.iter_fn())
.for_each(|f| global.functions.push(f.into()));
2020-12-19 12:42:18 +01:00
}
self.global_sub_modules.iter().for_each(|(name, m)| {
global.modules.insert(name.to_string(), m.as_ref().into());
});
2021-08-30 04:25:24 +02:00
self.global_namespace()
2020-12-19 12:42:18 +01:00
.iter_fn()
2021-03-17 06:30:47 +01:00
.for_each(|f| global.functions.push(f.into()));
2020-12-19 12:42:18 +01:00
2021-01-18 03:56:42 +01:00
#[cfg(not(feature = "no_function"))]
_ast.iter_functions()
2021-03-17 06:30:47 +01:00
.for_each(|f| global.functions.push(f.into()));
2020-12-19 12:42:18 +01:00
2020-12-20 05:27:47 +01:00
global.functions.sort();
2020-12-19 12:42:18 +01:00
serde_json::to_string_pretty(&global)
}
/// Generate a list of all functions in JSON format.
/// Available only under the `metadata` feature.
///
/// Functions from the following sources are included:
/// 1) Functions registered into the global namespace
2020-12-22 16:45:14 +01:00
/// 2) Functions in static modules
/// 3) Functions in global modules (optional)
pub fn gen_fn_metadata_to_json(&self, include_global: bool) -> serde_json::Result<String> {
self.gen_fn_metadata_with_ast_to_json(&AST::empty(), include_global)
}
2020-12-19 12:42:18 +01:00
}