Change custom precedence to Option<NonZeroU8>.

This commit is contained in:
Stephen Chung 2020-12-26 17:42:19 +08:00
parent db9dcd1bcc
commit 0a35c4cb41
2 changed files with 11 additions and 5 deletions

View File

@ -1,6 +1,6 @@
//! Configuration settings for [`Engine`]. //! Configuration settings for [`Engine`].
use crate::stdlib::{format, string::String}; use crate::stdlib::{format, num::NonZeroU8, string::String};
use crate::token::{is_valid_identifier, Token}; use crate::token::{is_valid_identifier, Token};
use crate::Engine; use crate::Engine;
@ -214,10 +214,12 @@ impl Engine {
self.disabled_symbols.insert(symbol.into()); self.disabled_symbols.insert(symbol.into());
self self
} }
/// Register a custom operator into the language. /// Register a custom operator with a precedence into the language.
/// ///
/// The operator must be a valid identifier (i.e. it cannot be a symbol). /// The operator must be a valid identifier (i.e. it cannot be a symbol).
/// ///
/// The precedence cannot be zero.
///
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
@ -245,6 +247,11 @@ impl Engine {
keyword: &str, keyword: &str,
precedence: u8, precedence: u8,
) -> Result<&mut Self, String> { ) -> Result<&mut Self, String> {
let precedence = NonZeroU8::new(precedence);
if precedence.is_none() {
return Err("precedence cannot be zero".into());
}
if !is_valid_identifier(keyword.chars()) { if !is_valid_identifier(keyword.chars()) {
return Err(format!("not a valid identifier: '{}'", keyword).into()); return Err(format!("not a valid identifier: '{}'", keyword).into());
} }
@ -259,8 +266,7 @@ impl Engine {
} }
// Add to custom keywords // Add to custom keywords
self.custom_keywords self.custom_keywords.insert(keyword.into(), precedence);
.insert(keyword.into(), Some(precedence));
Ok(self) Ok(self)
} }

View File

@ -208,7 +208,7 @@ impl Engine {
/// * `parse` is the parsing function. /// * `parse` is the parsing function.
/// * `func` is the implementation function. /// * `func` is the implementation function.
/// ///
/// All custom keywords must be manually registered via [`register_custom_operator`][Engine::register_custom_operator]. /// All custom keywords must be manually registered via [`Engine::register_custom_operator`].
/// Otherwise, custom keywords won't be recognized. /// Otherwise, custom keywords won't be recognized.
pub fn register_custom_syntax_raw( pub fn register_custom_syntax_raw(
&mut self, &mut self,