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 identifier = Identifier(s.into());
93 identifier.check_encoding(encoding)?;
96 /// Checks whether this is a valid identifier in the given `encoding`. An
97 /// identifier that is valid in one encoding might be invalid in another
98 /// because some characters are unencodable or because it is too long.
99 pub fn check_encoding(&self, encoding: &'static Encoding) -> Result<(), Error> {
100 let s = self.0.as_str();
101 let (encoded, _, unencodable) = encoding.encode(s);
103 let mut encoder = encoding.new_encoder();
104 let mut buf = Vec::with_capacity(
106 .max_buffer_length_from_utf8_without_replacement(s.len())
109 let EncoderResult::Unmappable(c) = encoder
110 .encode_from_utf8_to_vec_without_replacement(s, &mut buf, true)
115 return Err(Error::NotEncodable {
117 encoding: encoding.name(),
121 if encoded.len() > Self::MAX_LEN {
122 return Err(Error::TooLong {
124 length: encoded.len(),
125 encoding: encoding.name(),
131 pub fn is_plausible(s: &str) -> Result<(), Error> {
133 return Err(Error::Empty);
135 if is_reserved_word(s) {
136 return Err(Error::Reserved(s.into()));
139 let mut i = s.chars();
140 let first = i.next().unwrap();
141 if !first.may_start_id() {
142 return Err(Error::BadFirstCharacter(s.into(), first));
145 if !c.may_continue_id() {
146 return Err(Error::BadLaterCharacter(s.into(), c));
153 impl Display for Identifier {
154 fn fmt(&self, f: &mut Formatter) -> FmtResult {
155 write!(f, "{}", self.0)
159 pub trait HasIdentifier {
160 fn identifier(&self) -> &Identifier;
163 pub struct ByIdentifier<T>(pub T)
167 impl<T> ByIdentifier<T>
171 pub fn new(inner: T) -> Self {
176 impl<T> PartialEq for ByIdentifier<T>
180 fn eq(&self, other: &Self) -> bool {
181 self.0.identifier().eq(other.0.identifier())
185 impl<T> Eq for ByIdentifier<T> where T: HasIdentifier {}
187 impl<T> PartialOrd for ByIdentifier<T>
191 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
192 Some(self.cmp(other))
196 impl<T> Ord for ByIdentifier<T>
200 fn cmp(&self, other: &Self) -> Ordering {
201 self.0.identifier().cmp(other.0.identifier())
205 impl<T> Hash for ByIdentifier<T>
209 fn hash<H: Hasher>(&self, state: &mut H) {
210 self.0.identifier().hash(state)
214 impl<T> Borrow<Identifier> for ByIdentifier<T>
218 fn borrow(&self) -> &Identifier {
223 impl<T> Debug for ByIdentifier<T>
225 T: HasIdentifier + Debug,
227 fn fmt(&self, f: &mut Formatter) -> FmtResult {
232 impl<T> Clone for ByIdentifier<T>
234 T: HasIdentifier + Clone,
236 fn clone(&self) -> Self {