work
[pspp] / rust / src / identifier.rs
1 use std::{
2     borrow::Borrow,
3     cmp::Ordering,
4     fmt::{Debug, Display, Formatter, Result as FmtResult},
5     hash::{Hash, Hasher},
6 };
7
8 use encoding_rs::{EncoderResult, Encoding, UTF_8};
9 use finl_unicode::categories::{CharacterCategories, MajorCategory};
10 use thiserror::Error as ThisError;
11 use unicase::UniCase;
12
13 pub trait IdentifierChar {
14     /// Returns true if `self` may be the first character in an identifier.
15     fn may_start_id(self) -> bool;
16
17     /// Returns true if `self` may be a second or subsequent character in an
18     /// identifier.
19     fn may_continue_id(self) -> bool;
20 }
21
22 impl IdentifierChar for char {
23     fn may_start_id(self) -> bool {
24         use MajorCategory::*;
25
26         ([L, M, S].contains(&self.get_major_category()) || "@#$".contains(self))
27             && self != char::REPLACEMENT_CHARACTER
28     }
29
30     fn may_continue_id(self) -> bool {
31         use MajorCategory::*;
32
33         ([L, M, S, N].contains(&self.get_major_category()) || "@#$._".contains(self))
34             && self != char::REPLACEMENT_CHARACTER
35     }
36 }
37
38 #[derive(Clone, Debug, ThisError)]
39 pub enum Error {
40     #[error("Identifier cannot be empty string.")]
41     Empty,
42
43     #[error("\"{0}\" may not be used as an identifier because it is a reserved word.")]
44     Reserved(String),
45
46     #[error("\"{0}\" may not be used as an identifier because it begins with disallowed character \"{1}\".")]
47     BadFirstCharacter(String, char),
48
49     #[error("\"{0}\" may not be used as an identifier because it contains disallowed character \"{1}\".")]
50     BadLaterCharacter(String, char),
51
52     #[error("Identifier \"{id}\" is {length} bytes in the encoding in use ({encoding}), which exceeds the {max}-byte limit.")]
53     TooLong {
54         id: String,
55         length: usize,
56         encoding: &'static str,
57         max: usize,
58     },
59
60     #[error("\"{id}\" may not be used as an identifier because the encoding in use ({encoding}) cannot represent \"{c}\".")]
61     NotEncodable {
62         id: String,
63         encoding: &'static str,
64         c: char,
65     },
66 }
67
68 fn is_reserved_word(s: &str) -> bool {
69     for word in [
70         "and", "or", "not", "eq", "ge", "gt", "le", "ne", "all", "by", "to", "with",
71     ] {
72         if s.eq_ignore_ascii_case(word) {
73             return true;
74         }
75     }
76     false
77 }
78
79 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
80 pub struct Identifier(pub UniCase<String>);
81
82 impl Identifier {
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;
86
87     pub fn new_utf8(s: &str) -> Result<Identifier, Error> {
88         Self::new(s, UTF_8)
89     }
90     pub fn new(s: &str, encoding: &'static Encoding) -> Result<Identifier, Error> {
91         Self::is_plausible(s)?;
92         let (encoded, _, unencodable) = encoding.encode(s);
93         if unencodable {
94             let mut encoder = encoding.new_encoder();
95             let mut buf = Vec::with_capacity(
96                 encoder
97                     .max_buffer_length_from_utf8_without_replacement(s.len())
98                     .unwrap(),
99             );
100             let EncoderResult::Unmappable(c) = encoder
101                 .encode_from_utf8_to_vec_without_replacement(s, &mut buf, true)
102                 .0
103             else {
104                 unreachable!();
105             };
106             return Err(Error::NotEncodable {
107                 id: s.into(),
108                 encoding: encoding.name(),
109                 c,
110             });
111         }
112         if encoded.len() > Self::MAX_LEN {
113             return Err(Error::TooLong {
114                 id: s.into(),
115                 length: encoded.len(),
116                 encoding: encoding.name(),
117                 max: Self::MAX_LEN,
118             });
119         }
120         Ok(Identifier(s.into()))
121     }
122     pub fn is_plausible(s: &str) -> Result<(), Error> {
123         if s.is_empty() {
124             return Err(Error::Empty);
125         }
126         if is_reserved_word(s) {
127             return Err(Error::Reserved(s.into()));
128         }
129
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));
134         }
135         for c in i {
136             if !c.may_continue_id() {
137                 return Err(Error::BadLaterCharacter(s.into(), c));
138             }
139         }
140         Ok(())
141     }
142 }
143
144 impl Display for Identifier {
145     fn fmt(&self, f: &mut Formatter) -> FmtResult {
146         write!(f, "{}", self.0)
147     }
148 }
149
150 pub trait HasIdentifier {
151     fn identifier(&self) -> &Identifier;
152 }
153
154 pub struct ByIdentifier<T>(pub T)
155 where
156     T: HasIdentifier;
157
158 impl<T> ByIdentifier<T>
159 where
160     T: HasIdentifier,
161 {
162     pub fn new(inner: T) -> Self {
163         Self(inner)
164     }
165 }
166
167 impl<T> PartialEq for ByIdentifier<T>
168 where
169     T: HasIdentifier,
170 {
171     fn eq(&self, other: &Self) -> bool {
172         self.0.identifier().eq(other.0.identifier())
173     }
174 }
175
176 impl<T> Eq for ByIdentifier<T> where T: HasIdentifier {}
177
178 impl<T> PartialOrd for ByIdentifier<T>
179 where
180     T: HasIdentifier,
181 {
182     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
183         Some(self.cmp(other))
184     }
185 }
186
187 impl<T> Ord for ByIdentifier<T>
188 where
189     T: HasIdentifier,
190 {
191     fn cmp(&self, other: &Self) -> Ordering {
192         self.0.identifier().cmp(other.0.identifier())
193     }
194 }
195
196 impl<T> Hash for ByIdentifier<T>
197 where
198     T: HasIdentifier,
199 {
200     fn hash<H: Hasher>(&self, state: &mut H) {
201         self.0.identifier().hash(state)
202     }
203 }
204
205 impl<T> Borrow<Identifier> for ByIdentifier<T>
206 where
207     T: HasIdentifier,
208 {
209     fn borrow(&self) -> &Identifier {
210         self.0.identifier()
211     }
212 }
213
214 impl<T> Debug for ByIdentifier<T>
215 where
216     T: HasIdentifier + Debug,
217 {
218     fn fmt(&self, f: &mut Formatter) -> FmtResult {
219         self.0.fmt(f)
220     }
221 }
222
223 impl<T> Clone for ByIdentifier<T>
224 where
225     T: HasIdentifier + Clone,
226 {
227     fn clone(&self) -> Self {
228         Self(self.0.clone())
229     }
230 }