Extract metadata into separate type.

This commit is contained in:
Stephen Chung 2022-01-13 19:07:56 +08:00
parent 5dae2b07f7
commit 09aa9fc3db
2 changed files with 123 additions and 77 deletions

View File

@ -15,6 +15,7 @@ use crate::{
use std::prelude::v1::*; use std::prelude::v1::*;
use std::{ use std::{
any::TypeId, any::TypeId,
cmp::Ordering,
collections::{BTreeMap, BTreeSet}, collections::{BTreeMap, BTreeSet},
fmt, fmt,
iter::{empty, once}, iter::{empty, once},
@ -31,11 +32,9 @@ pub enum FnNamespace {
Internal, Internal,
} }
/// Data structure containing a single registered function. /// A type containing all metadata for a registered function.
#[derive(Debug, Clone)] #[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct FuncInfo { pub struct FnMetadata {
/// Function instance.
pub func: Shared<CallableFunction>,
/// Function namespace. /// Function namespace.
pub namespace: FnNamespace, pub namespace: FnNamespace,
/// Function access mode. /// Function access mode.
@ -44,37 +43,65 @@ pub struct FuncInfo {
pub name: Identifier, pub name: Identifier,
/// Number of parameters. /// Number of parameters.
pub params: usize, pub params: usize,
/// Parameter types (if applicable).
pub param_types: StaticVec<TypeId>,
/// Parameter names and types (if available). /// Parameter names and types (if available).
#[cfg(feature = "metadata")] #[cfg(feature = "metadata")]
pub param_names_and_types: StaticVec<Identifier>, pub params_info: StaticVec<Identifier>,
/// Return type name. /// Return type name.
#[cfg(feature = "metadata")] #[cfg(feature = "metadata")]
pub return_type_name: Identifier, pub return_type: Identifier,
/// Comments. /// Comments.
#[cfg(feature = "metadata")] #[cfg(feature = "metadata")]
pub comments: Option<Box<[Box<str>]>>, pub comments: Option<Box<[Box<str>]>>,
} }
impl PartialOrd for FnMetadata {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for FnMetadata {
fn cmp(&self, other: &Self) -> Ordering {
match self.name.cmp(&other.name) {
Ordering::Equal => match self.params.cmp(&other.params) {
Ordering::Equal => self.params_info.cmp(&other.params_info),
cmp => cmp,
},
cmp => cmp,
}
}
}
/// A type containing a single registered function.
#[derive(Debug, Clone)]
pub struct FuncInfo {
/// Function instance.
pub func: Shared<CallableFunction>,
/// Parameter types (if applicable).
pub param_types: StaticVec<TypeId>,
/// Function metadata.
pub metadata: FnMetadata,
}
impl FuncInfo { impl FuncInfo {
/// Generate a signature of the function. /// Generate a signature of the function.
/// Exported under the `metadata` feature only. /// Exported under the `metadata` feature only.
#[cfg(feature = "metadata")] #[cfg(feature = "metadata")]
#[must_use] #[must_use]
pub fn gen_signature(&self) -> String { pub fn gen_signature(&self) -> String {
let mut sig = format!("{}(", self.name); let mut sig = format!("{}(", self.metadata.name);
if !self.param_names_and_types.is_empty() { if !self.metadata.params_info.is_empty() {
let params: StaticVec<_> = self let params: StaticVec<_> = self
.param_names_and_types .metadata
.params_info
.iter() .iter()
.map(|s| s.as_str()) .map(|s| s.as_str())
.collect(); .collect();
sig.push_str(&params.join(", ")); sig.push_str(&params.join(", "));
sig.push_str(")"); sig.push_str(")");
match self.return_type_name.as_str() { match self.metadata.return_type.as_str() {
"" | "()" => (), "" | "()" => (),
ty => { ty => {
sig.push_str(" -> "); sig.push_str(" -> ");
@ -82,9 +109,9 @@ impl FuncInfo {
} }
} }
} else { } else {
for x in 0..self.params { for x in 0..self.metadata.params {
sig.push('_'); sig.push('_');
if x < self.params - 1 { if x < self.metadata.params - 1 {
sig.push_str(", "); sig.push_str(", ");
} }
} }
@ -94,7 +121,7 @@ impl FuncInfo {
} else { } else {
sig.push_str(")"); sig.push_str(")");
match self.return_type_name.as_str() { match self.metadata.return_type.as_str() {
"()" => (), "()" => (),
_ => sig.push_str(" -> ?"), _ => sig.push_str(" -> ?"),
} }
@ -372,7 +399,7 @@ impl Module {
#[inline] #[inline]
pub fn gen_fn_signatures(&self) -> impl Iterator<Item = String> + '_ { pub fn gen_fn_signatures(&self) -> impl Iterator<Item = String> + '_ {
self.iter_fn() self.iter_fn()
.filter(|&f| match f.access { .filter(|&f| match f.metadata.access {
FnAccess::Public => true, FnAccess::Public => true,
FnAccess::Private => false, FnAccess::Private => false,
}) })
@ -478,22 +505,24 @@ impl Module {
let num_params = fn_def.params.len(); let num_params = fn_def.params.len();
let hash_script = crate::calc_fn_hash(&fn_def.name, num_params); let hash_script = crate::calc_fn_hash(&fn_def.name, num_params);
#[cfg(feature = "metadata")] #[cfg(feature = "metadata")]
let param_names_and_types = fn_def.params.iter().cloned().collect(); let params_info = fn_def.params.iter().cloned().collect();
self.functions.insert( self.functions.insert(
hash_script, hash_script,
FuncInfo { FuncInfo {
name: fn_def.name.clone(), metadata: FnMetadata {
namespace: FnNamespace::Internal, name: fn_def.name.clone(),
access: fn_def.access, namespace: FnNamespace::Internal,
params: num_params, access: fn_def.access,
param_types: StaticVec::new_const(), params: num_params,
#[cfg(feature = "metadata")] #[cfg(feature = "metadata")]
param_names_and_types, params_info,
#[cfg(feature = "metadata")] #[cfg(feature = "metadata")]
return_type_name: "Dynamic".into(), return_type: "Dynamic".into(),
#[cfg(feature = "metadata")] #[cfg(feature = "metadata")]
comments: None, comments: None,
},
func: Into::<CallableFunction>::into(fn_def).into(), func: Into::<CallableFunction>::into(fn_def).into(),
param_types: StaticVec::new_const(),
} }
.into(), .into(),
); );
@ -518,7 +547,7 @@ impl Module {
let name = name.as_ref(); let name = name.as_ref();
self.iter_fn() self.iter_fn()
.find(|f| f.params == num_params && f.name == name) .find(|f| f.metadata.params == num_params && f.metadata.name == name)
.and_then(|f| f.func.get_script_fn_def()) .and_then(|f| f.func.get_script_fn_def())
} }
} }
@ -648,14 +677,14 @@ impl Module {
.collect(); .collect();
if let Some(f) = self.functions.get_mut(&hash_fn) { if let Some(f) = self.functions.get_mut(&hash_fn) {
let (param_names, return_type_name) = if param_names.len() > f.params { let (param_names, return_type_name) = if param_names.len() > f.metadata.params {
let return_type = param_names.pop().unwrap(); let return_type = param_names.pop().unwrap();
(param_names, return_type) (param_names, return_type)
} else { } else {
(param_names, Default::default()) (param_names, Default::default())
}; };
f.param_names_and_types = param_names; f.metadata.params_info = param_names;
f.return_type_name = return_type_name; f.metadata.return_type = return_type_name;
} }
self self
@ -698,7 +727,7 @@ impl Module {
if !comments.is_empty() { if !comments.is_empty() {
let f = self.functions.get_mut(&hash_fn).unwrap(); let f = self.functions.get_mut(&hash_fn).unwrap();
f.comments = Some(comments.iter().map(|s| s.as_ref().into()).collect()); f.metadata.comments = Some(comments.iter().map(|s| s.as_ref().into()).collect());
} }
self self
@ -710,7 +739,7 @@ impl Module {
#[inline] #[inline]
pub fn update_fn_namespace(&mut self, hash_fn: u64, namespace: FnNamespace) -> &mut Self { pub fn update_fn_namespace(&mut self, hash_fn: u64, namespace: FnNamespace) -> &mut Self {
if let Some(f) = self.functions.get_mut(&hash_fn) { if let Some(f) = self.functions.get_mut(&hash_fn) {
f.namespace = namespace; f.metadata.namespace = namespace;
self.indexed = false; self.indexed = false;
self.contains_indexed_global_functions = false; self.contains_indexed_global_functions = false;
} }
@ -795,18 +824,20 @@ impl Module {
self.functions.insert( self.functions.insert(
hash_fn, hash_fn,
FuncInfo { FuncInfo {
name: name.as_ref().into(), metadata: FnMetadata {
namespace, name: name.as_ref().into(),
access, namespace,
params: param_types.len(), access,
param_types, params: param_types.len(),
#[cfg(feature = "metadata")] #[cfg(feature = "metadata")]
param_names_and_types: param_names, params_info: param_names,
#[cfg(feature = "metadata")] #[cfg(feature = "metadata")]
return_type_name, return_type: return_type_name,
#[cfg(feature = "metadata")] #[cfg(feature = "metadata")]
comments: None, comments: None,
},
func: func.into(), func: func.into(),
param_types,
} }
.into(), .into(),
); );
@ -861,7 +892,7 @@ impl Module {
if !comments.is_empty() { if !comments.is_empty() {
let f = self.functions.get_mut(&hash).unwrap(); let f = self.functions.get_mut(&hash).unwrap();
f.comments = Some(comments.iter().map(|s| s.as_ref().into()).collect()); f.metadata.comments = Some(comments.iter().map(|s| s.as_ref().into()).collect());
} }
hash hash
@ -1374,11 +1405,11 @@ impl Module {
.iter() .iter()
.filter(|&(_, f)| { .filter(|&(_, f)| {
_filter( _filter(
f.namespace, f.metadata.namespace,
f.access, f.metadata.access,
f.func.is_script(), f.func.is_script(),
f.name.as_str(), f.metadata.name.as_str(),
f.params, f.metadata.params,
) )
}) })
.map(|(&k, v)| (k, v.clone())), .map(|(&k, v)| (k, v.clone())),
@ -1404,7 +1435,12 @@ impl Module {
.into_iter() .into_iter()
.filter(|(_, f)| { .filter(|(_, f)| {
if f.func.is_script() { if f.func.is_script() {
filter(f.namespace, f.access, f.name.as_str(), f.params) filter(
f.metadata.namespace,
f.metadata.access,
f.metadata.name.as_str(),
f.metadata.params,
)
} else { } else {
false false
} }
@ -1472,10 +1508,10 @@ impl Module {
> + '_ { > + '_ {
self.iter_fn().filter(|&f| f.func.is_script()).map(|f| { self.iter_fn().filter(|&f| f.func.is_script()).map(|f| {
( (
f.namespace, f.metadata.namespace,
f.access, f.metadata.access,
f.name.as_str(), f.metadata.name.as_str(),
f.params, f.metadata.params,
f.func.get_script_fn_def().expect("script-defined function"), f.func.get_script_fn_def().expect("script-defined function"),
) )
}) })
@ -1494,9 +1530,14 @@ impl Module {
pub fn iter_script_fn_info( pub fn iter_script_fn_info(
&self, &self,
) -> impl Iterator<Item = (FnNamespace, FnAccess, &str, usize)> { ) -> impl Iterator<Item = (FnNamespace, FnAccess, &str, usize)> {
self.iter_fn() self.iter_fn().filter(|&f| f.func.is_script()).map(|f| {
.filter(|&f| f.func.is_script()) (
.map(|f| (f.namespace, f.access, f.name.as_str(), f.params)) f.metadata.namespace,
f.metadata.access,
f.metadata.name.as_str(),
f.metadata.params,
)
})
} }
/// _(internals)_ Get an iterator over all script-defined functions in the [`Module`]. /// _(internals)_ Get an iterator over all script-defined functions in the [`Module`].
@ -1607,7 +1648,7 @@ impl Module {
if ast.has_functions() { if ast.has_functions() {
ast.shared_lib() ast.shared_lib()
.iter_fn() .iter_fn()
.filter(|&f| match f.access { .filter(|&f| match f.metadata.access {
FnAccess::Public => true, FnAccess::Public => true,
FnAccess::Private => false, FnAccess::Private => false,
}) })
@ -1682,7 +1723,7 @@ impl Module {
// Index all Rust functions // Index all Rust functions
module.functions.iter().for_each(|(&hash, f)| { module.functions.iter().for_each(|(&hash, f)| {
match f.namespace { match f.metadata.namespace {
FnNamespace::Global => { FnNamespace::Global => {
// Flatten all functions with global namespace // Flatten all functions with global namespace
functions.insert(hash, f.func.clone()); functions.insert(hash, f.func.clone());
@ -1690,20 +1731,23 @@ impl Module {
} }
FnNamespace::Internal => (), FnNamespace::Internal => (),
} }
match f.access { match f.metadata.access {
FnAccess::Public => (), FnAccess::Public => (),
FnAccess::Private => return, // Do not index private functions FnAccess::Private => return, // Do not index private functions
} }
if !f.func.is_script() { if !f.func.is_script() {
let hash_qualified_fn = let hash_qualified_fn = calc_native_fn_hash(
calc_native_fn_hash(path.iter().cloned(), f.name.as_str(), &f.param_types); path.iter().cloned(),
f.metadata.name.as_str(),
&f.param_types,
);
functions.insert(hash_qualified_fn, f.func.clone()); functions.insert(hash_qualified_fn, f.func.clone());
} else if cfg!(not(feature = "no_function")) { } else if cfg!(not(feature = "no_function")) {
let hash_qualified_script = crate::calc_qualified_fn_hash( let hash_qualified_script = crate::calc_qualified_fn_hash(
path.iter().cloned(), path.iter().cloned(),
f.name.as_str(), f.metadata.name.as_str(),
f.params, f.metadata.params,
); );
functions.insert(hash_qualified_script, f.func.clone()); functions.insert(hash_qualified_script, f.func.clone());
} }

View File

@ -71,14 +71,14 @@ struct FnMetadata<'a> {
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]
pub params: Vec<FnParam<'a>>, pub params: Vec<FnParam<'a>>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub return_type_name: Option<&'a str>, pub return_type: Option<&'a str>,
pub signature: String, pub signature: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]
pub doc_comments: Vec<&'a str>, pub doc_comments: Vec<&'a str>,
} }
impl PartialOrd for FnMetadata<'_> { impl PartialOrd for FnMetadata<'_> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other)) Some(self.cmp(other))
} }
} }
@ -94,26 +94,27 @@ impl Ord for FnMetadata<'_> {
impl<'a> From<&'a FuncInfo> for FnMetadata<'a> { impl<'a> From<&'a FuncInfo> for FnMetadata<'a> {
fn from(info: &'a FuncInfo) -> Self { fn from(info: &'a FuncInfo) -> Self {
let base_hash = calc_fn_hash(&info.name, info.params); let base_hash = calc_fn_hash(&info.metadata.name, info.metadata.params);
let (typ, full_hash) = if info.func.is_script() { let (typ, full_hash) = if info.func.is_script() {
(FnType::Script, base_hash) (FnType::Script, base_hash)
} else { } else {
( (
FnType::Native, FnType::Native,
calc_native_fn_hash(empty::<&str>(), &info.name, &info.param_types), calc_native_fn_hash(empty::<&str>(), &info.metadata.name, &info.param_types),
) )
}; };
Self { Self {
base_hash, base_hash,
full_hash, full_hash,
namespace: info.namespace.into(), namespace: info.metadata.namespace.into(),
access: info.access.into(), access: info.metadata.access.into(),
name: info.name.to_string(), name: info.metadata.name.to_string(),
typ, typ,
num_params: info.params, num_params: info.metadata.params,
params: info params: info
.param_names_and_types .metadata
.params_info
.iter() .iter()
.map(|s| { .map(|s| {
let mut seg = s.splitn(2, ':'); let mut seg = s.splitn(2, ':');
@ -125,7 +126,7 @@ impl<'a> From<&'a FuncInfo> for FnMetadata<'a> {
FnParam { name, typ } FnParam { name, typ }
}) })
.collect(), .collect(),
return_type_name: match info.return_type_name.as_str() { return_type: match info.metadata.return_type.as_str() {
"" | "()" => None, "" | "()" => None,
ty => Some(ty), ty => Some(ty),
}, },
@ -142,7 +143,8 @@ impl<'a> From<&'a FuncInfo> for FnMetadata<'a> {
.as_ref() .as_ref()
.map_or_else(|| Vec::new(), |v| v.iter().map(|s| &**s).collect()) .map_or_else(|| Vec::new(), |v| v.iter().map(|s| &**s).collect())
} else { } else {
info.comments info.metadata
.comments
.as_ref() .as_ref()
.map_or_else(|| Vec::new(), |v| v.iter().map(|s| &**s).collect()) .map_or_else(|| Vec::new(), |v| v.iter().map(|s| &**s).collect())
}, },