Refactor CustomType to struct CustomTypeInfo.

This commit is contained in:
Stephen Chung 2022-08-22 20:52:52 +08:00
parent db865d7538
commit 4ce8d4609d
3 changed files with 25 additions and 11 deletions

View File

@ -586,10 +586,10 @@ impl Module {
///
/// assert_eq!(module.get_custom_type(name), Some("MyType"));
/// ```
#[inline(always)]
#[inline]
#[must_use]
pub fn get_custom_type(&self, key: &str) -> Option<&str> {
self.custom_types.get(key)
self.custom_types.get(key).map(|t| t.display_name.as_str())
}
/// Returns `true` if this [`Module`] contains no items.

View File

@ -3,14 +3,18 @@
use crate::Identifier;
use std::{any::type_name, collections::BTreeMap, fmt};
/// _(internals)_ A custom type.
/// _(internals)_ Information for a custom type.
/// Exported under the `internals` feature only.
pub type CustomType = Identifier;
#[derive(Debug, Eq, PartialEq, Clone, Hash, Default)]
pub struct CustomTypeInfo {
/// Friendly display name of the custom type.
pub display_name: Identifier,
}
/// _(internals)_ A collection of custom types.
/// Exported under the `internals` feature only.
#[derive(Clone, Hash, Default)]
pub struct CustomTypesCollection(BTreeMap<Identifier, CustomType>);
pub struct CustomTypesCollection(BTreeMap<Identifier, CustomTypeInfo>);
impl fmt::Debug for CustomTypesCollection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
@ -33,21 +37,31 @@ impl CustomTypesCollection {
/// Register a custom type.
#[inline(always)]
pub fn add(&mut self, type_name: impl Into<Identifier>, name: impl Into<Identifier>) {
self.add_raw(type_name, name.into());
self.add_raw(
type_name,
CustomTypeInfo {
display_name: name.into(),
},
);
}
/// Register a custom type.
#[inline(always)]
pub fn add_type<T>(&mut self, name: &str) {
self.add_raw(type_name::<T>(), name.into());
self.add_raw(
type_name::<T>(),
CustomTypeInfo {
display_name: name.into(),
},
);
}
/// Register a custom type.
#[inline(always)]
pub fn add_raw(&mut self, type_name: impl Into<Identifier>, custom_type: CustomType) {
pub fn add_raw(&mut self, type_name: impl Into<Identifier>, custom_type: CustomTypeInfo) {
self.0.insert(type_name.into(), custom_type);
}
/// Find a custom type.
#[inline(always)]
pub fn get(&self, key: &str) -> Option<&str> {
self.0.get(key).map(CustomType::as_str)
pub fn get(&self, key: &str) -> Option<&CustomTypeInfo> {
self.0.get(key)
}
}

View File

@ -9,7 +9,7 @@ pub mod interner;
pub mod parse_error;
pub mod scope;
pub use custom_types::{CustomType, CustomTypesCollection};
pub use custom_types::{CustomTypeInfo, CustomTypesCollection};
pub use dynamic::Dynamic;
#[cfg(not(feature = "no_std"))]
pub use dynamic::Instant;