4 fmt::{Debug, Display, Formatter, Result as FmtResult},
8 use encoding_rs::{EncoderResult, Encoding, UTF_8};
9 use finl_unicode::categories::{CharacterCategories, MajorCategory};
10 use thiserror::Error as ThisError;
13 pub trait IdentifierChar {
14 /// Returns true if `self` may be the first character in an identifier.
15 fn may_start_id(self) -> bool;
17 /// Returns true if `self` may be a second or subsequent character in an
19 fn may_continue_id(self) -> bool;
22 impl IdentifierChar for char {
23 fn may_start_id(self) -> bool {
26 ([L, M, S].contains(&self.get_major_category()) || "@#$".contains(self))
27 && self != char::REPLACEMENT_CHARACTER
30 fn may_continue_id(self) -> bool {
33 ([L, M, S, N].contains(&self.get_major_category()) || "@#$._".contains(self))
34 && self != char::REPLACEMENT_CHARACTER
38 #[derive(Clone, Debug, ThisError)]
40 #[error("Identifier cannot be empty string.")]
43 #[error("\"{0}\" may not be used as an identifier because it is a reserved word.")]
46 #[error("\"{0}\" may not be used as an identifier because it begins with disallowed character \"{1}\".")]
47 BadFirstCharacter(String, char),
49 #[error("\"{0}\" may not be used as an identifier because it contains disallowed character \"{1}\".")]
50 BadLaterCharacter(String, char),
52 #[error("Identifier \"{id}\" is {length} bytes in the encoding in use ({encoding}), which exceeds the {max}-byte limit.")]
56 encoding: &'static str,
60 #[error("\"{id}\" may not be used as an identifier because the encoding in use ({encoding}) cannot represent \"{c}\".")]
63 encoding: &'static str,
68 fn is_reserved_word(s: &str) -> bool {
70 "and", "or", "not", "eq", "ge", "gt", "le", "ne", "all", "by", "to", "with",
72 if s.eq_ignore_ascii_case(word) {
79 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
80 pub struct Identifier(pub UniCase<String>);
83 /// Maximum length of an identifier, in bytes. The limit applies in the
84 /// encoding used by the dictionary, not in UTF-8.
85 pub const MAX_LEN: usize = 64;
87 pub fn new_utf8(s: &str) -> Result<Identifier, Error> {
90 pub fn new(s: &str, encoding: &'static Encoding) -> Result<Identifier, Error> {
91 Self::is_plausible(s)?;
92 let (encoded, _, unencodable) = encoding.encode(s);
94 let mut encoder = encoding.new_encoder();
95 let mut buf = Vec::with_capacity(
97 .max_buffer_length_from_utf8_without_replacement(s.len())
100 let EncoderResult::Unmappable(c) = encoder
101 .encode_from_utf8_to_vec_without_replacement(s, &mut buf, true)
106 return Err(Error::NotEncodable {
108 encoding: encoding.name(),
112 if encoded.len() > Self::MAX_LEN {
113 return Err(Error::TooLong {
115 length: encoded.len(),
116 encoding: encoding.name(),
120 Ok(Identifier(s.into()))
122 pub fn is_plausible(s: &str) -> Result<(), Error> {
124 return Err(Error::Empty);
126 if is_reserved_word(s) {
127 return Err(Error::Reserved(s.into()));
130 let mut i = s.chars();
131 let first = i.next().unwrap();
132 if !first.may_start_id() {
133 return Err(Error::BadFirstCharacter(s.into(), first));
136 if !c.may_continue_id() {
137 return Err(Error::BadLaterCharacter(s.into(), c));
144 impl Display for Identifier {
145 fn fmt(&self, f: &mut Formatter) -> FmtResult {
146 write!(f, "{}", self.0)
150 pub trait HasIdentifier {
151 fn identifier(&self) -> &Identifier;
154 pub struct ByIdentifier<T>(pub T)
158 impl<T> ByIdentifier<T>
162 pub fn new(inner: T) -> Self {
167 impl<T> PartialEq for ByIdentifier<T>
171 fn eq(&self, other: &Self) -> bool {
172 self.0.identifier().eq(other.0.identifier())
176 impl<T> Eq for ByIdentifier<T> where T: HasIdentifier {}
178 impl<T> PartialOrd for ByIdentifier<T>
182 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
183 Some(self.cmp(other))
187 impl<T> Ord for ByIdentifier<T>
191 fn cmp(&self, other: &Self) -> Ordering {
192 self.0.identifier().cmp(other.0.identifier())
196 impl<T> Hash for ByIdentifier<T>
200 fn hash<H: Hasher>(&self, state: &mut H) {
201 self.0.identifier().hash(state)
205 impl<T> Borrow<Identifier> for ByIdentifier<T>
209 fn borrow(&self) -> &Identifier {
214 impl<T> Debug for ByIdentifier<T>
216 T: HasIdentifier + Debug,
218 fn fmt(&self, f: &mut Formatter) -> FmtResult {
223 impl<T> Clone for ByIdentifier<T>
225 T: HasIdentifier + Clone,
227 fn clone(&self) -> Self {