miden_assembly_syntax/ast/
ident.rs1use alloc::{string::ToString, sync::Arc};
2use core::{
3 fmt,
4 hash::{Hash, Hasher},
5 str::FromStr,
6};
7
8use miden_core::serde::{
9 ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
10};
11use miden_debug_types::{SourceSpan, Span, Spanned};
12
13#[derive(Debug, thiserror::Error)]
15pub enum IdentError {
16 #[error("invalid identifier: cannot be empty")]
17 Empty,
18 #[error(
19 "invalid identifier '{ident}': must contain only unicode alphanumeric or ascii graphic characters"
20 )]
21 InvalidChars { ident: Arc<str> },
22 #[error("invalid identifier: length exceeds the maximum of {max} bytes")]
23 InvalidLength { max: usize },
24 #[error("invalid identifier: {0}")]
25 Casing(CaseKindError),
26}
27
28#[derive(Debug, thiserror::Error)]
31pub enum CaseKindError {
32 #[error(
33 "only uppercase characters or underscores are allowed, and must start with an alphabetic character"
34 )]
35 Screaming,
36 #[error(
37 "only lowercase characters or underscores are allowed, and must start with an alphabetic character"
38 )]
39 Snake,
40 #[error(
41 "only alphanumeric characters are allowed, and must start with a lowercase alphabetic character"
42 )]
43 Camel,
44}
45
46#[derive(Clone)]
57#[cfg_attr(
58 all(feature = "arbitrary", test),
59 miden_test_serialization_macros::serialization_test
60)]
61pub struct Ident {
62 span: SourceSpan,
71 name: Arc<str>,
73}
74
75impl Ident {
76 pub const MAIN: &'static str = "$main";
78
79 pub fn new(source: impl AsRef<str>) -> Result<Self, IdentError> {
87 source.as_ref().parse()
88 }
89
90 pub fn new_with_span(span: SourceSpan, source: impl AsRef<str>) -> Result<Self, IdentError> {
98 source.as_ref().parse::<Self>().map(|id| id.with_span(span))
99 }
100
101 pub fn with_span(mut self, span: SourceSpan) -> Self {
103 self.span = span;
104 self
105 }
106
107 pub fn from_raw_parts(name: Span<Arc<str>>) -> Self {
116 let (span, name) = name.into_parts();
117 Self { span, name }
118 }
119
120 pub fn into_inner(self) -> Arc<str> {
122 self.name
123 }
124
125 pub fn as_str(&self) -> &str {
127 self.name.as_ref()
128 }
129
130 pub fn is_constant_ident(&self) -> bool {
132 self.name
133 .chars()
134 .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
135 }
136
137 pub fn requires_quoting(ident: impl AsRef<str>) -> bool {
139 match ident.as_ref() {
140 crate::Path::KERNEL_PATH
141 | crate::Path::EXEC_PATH
142 | crate::ast::ProcedureName::MAIN_PROC_NAME => false,
143 ident => !ident.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'),
144 }
145 }
146
147 pub fn validate(source: impl AsRef<str>) -> Result<(), IdentError> {
149 let source = source.as_ref();
150 if source.is_empty() {
151 return Err(IdentError::Empty);
152 }
153 if !source
154 .chars()
155 .all(|c| (c.is_ascii_graphic() || c.is_alphanumeric()) && c != '#')
156 {
157 return Err(IdentError::InvalidChars { ident: source.into() });
158 }
159 Ok(())
160 }
161}
162
163impl fmt::Debug for Ident {
164 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
165 f.debug_tuple("Ident").field(&self.name).finish()
166 }
167}
168
169impl Eq for Ident {}
170
171impl PartialEq for Ident {
172 fn eq(&self, other: &Self) -> bool {
173 self.name == other.name
174 }
175}
176
177impl Ord for Ident {
178 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
179 self.name.cmp(&other.name)
180 }
181}
182
183impl PartialOrd for Ident {
184 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
185 Some(self.cmp(other))
186 }
187}
188
189impl Hash for Ident {
190 fn hash<H: Hasher>(&self, state: &mut H) {
191 self.name.hash(state);
192 }
193}
194
195impl Spanned for Ident {
196 fn span(&self) -> SourceSpan {
197 self.span
198 }
199}
200
201impl core::ops::Deref for Ident {
202 type Target = str;
203
204 fn deref(&self) -> &Self::Target {
205 self.name.as_ref()
206 }
207}
208
209impl AsRef<str> for Ident {
210 #[inline]
211 fn as_ref(&self) -> &str {
212 &self.name
213 }
214}
215
216impl fmt::Display for Ident {
217 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
218 if Self::requires_quoting(&self.name) {
219 write!(f, "\"{}\"", self.name.escape_debug())
220 } else {
221 f.write_str(&self.name)
222 }
223 }
224}
225
226impl crate::prettier::PrettyPrint for Ident {
227 fn render(&self) -> crate::prettier::Document {
228 use crate::prettier::*;
229 display(self)
230 }
231}
232
233impl FromStr for Ident {
234 type Err = IdentError;
235
236 fn from_str(s: &str) -> Result<Self, Self::Err> {
237 Self::validate(s)?;
238 let name = Arc::from(s.to_string().into_boxed_str());
239 Ok(Self { span: SourceSpan::default(), name })
240 }
241}
242
243impl From<Ident> for miden_utils_diagnostics::miette::SourceSpan {
244 fn from(value: Ident) -> Self {
245 value.span.into()
246 }
247}
248
249impl Serializable for Ident {
250 fn write_into<W: ByteWriter>(&self, target: &mut W) {
251 target.write_usize(self.len());
252 target.write_bytes(self.as_bytes());
253 }
254}
255
256impl Deserializable for Ident {
257 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
258 use alloc::string::ToString;
259
260 let len = source.read_usize()?;
261 let bytes = source.read_slice(len)?;
262 let id = core::str::from_utf8(bytes)
263 .map_err(|err| DeserializationError::InvalidValue(err.to_string()))?;
264 Self::new(id).map_err(|err| DeserializationError::InvalidValue(err.to_string()))
265 }
266}
267
268#[cfg(test)]
269mod tests {
270 use super::*;
271
272 #[test]
273 fn ident_with_quotes_is_properly_escaped() {
274 let id = Ident::new("a\"b").unwrap();
275 let output = id.to_string();
276 assert_eq!(output, "\"a\\\"b\"")
277 }
278}
279
280#[cfg(feature = "arbitrary")]
281pub mod arbitrary {
282 use alloc::{borrow::Cow, string::String};
283
284 use proptest::{char::CharStrategy, collection::vec, prelude::*};
285
286 use super::*;
287
288 impl Arbitrary for Ident {
289 type Parameters = ();
290
291 fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
292 ident_any_random_length().boxed()
293 }
294
295 type Strategy = BoxedStrategy<Self>;
296 }
297
298 const SPECIAL: [char; 32] = const {
301 let mut buf = ['a'; 32];
302 let mut idx = 0;
303 let mut range_idx = 0;
304 while range_idx < SPECIAL_RANGES.len() {
305 let range = &SPECIAL_RANGES[range_idx];
306 range_idx += 1;
307 let mut j = *range.start() as u32;
308 let end = *range.end() as u32;
309 while j <= end {
310 unsafe {
311 buf[idx] = char::from_u32_unchecked(j);
312 }
313 idx += 1;
314 j += 1;
315 }
316 }
317 buf
318 };
319
320 const SPECIAL_RANGES: &[core::ops::RangeInclusive<char>] =
321 &['!'..='/', ':'..='@', '['..='`', '{'..='~'];
322 const PREFERRED_RANGES: &[core::ops::RangeInclusive<char>] = &['a'..='z', 'A'..='Z'];
323 const EXTRA_RANGES: &[core::ops::RangeInclusive<char>] = &['0'..='9', 'à'..='ö', 'ø'..='ÿ'];
324
325 const PREFERRED_CONSTANT_RANGES: &[core::ops::RangeInclusive<char>] =
326 core::slice::from_ref(&('A'..='Z'));
327 const EXTRA_CONSTANT_RANGES: &[core::ops::RangeInclusive<char>] =
328 core::slice::from_ref(&('0'..='9'));
329
330 prop_compose! {
331 #[allow(clippy::single_range_in_vec_init)]
334 fn bare_ident_chars()
335 (c in CharStrategy::new_borrowed(
336 &['_'],
337 PREFERRED_RANGES,
338 core::slice::from_ref(&('0'..='9'))
339 )) -> char {
340 c
341 }
342 }
343
344 prop_compose! {
345 fn ident_chars()
348 (c in CharStrategy::new_borrowed(
349 &SPECIAL,
350 PREFERRED_RANGES,
351 EXTRA_RANGES
352 )) -> char {
353 c
354 }
355 }
356
357 prop_compose! {
358 fn const_ident_chars()
360 (c in CharStrategy::new_borrowed(
361 &['_'],
362 PREFERRED_CONSTANT_RANGES,
363 EXTRA_CONSTANT_RANGES
364 )) -> char {
365 c
366 }
367 }
368
369 prop_compose! {
370 fn ident_raw_any(length: u32)
375 ((leading_char, rest) in (
376 proptest::char::ranges(Cow::Borrowed(&['a'..='z', '_'..='_'])),
377 vec(ident_chars(), 0..=(length as usize))
378 )) -> String {
379 let mut buf = String::with_capacity(length as usize);
380 buf.push(leading_char);
381 for c in rest {
382 if !buf.is_empty() && buf.len() + c.len_utf8() > length as usize {
383 break;
384 }
385 buf.push(c);
386 }
387 buf
388 }
389 }
390
391 prop_compose! {
392 fn bare_ident_raw_any(length: u32)
394 ((leading_char, rest) in (
395 proptest::char::range('a', 'z'),
396 vec(bare_ident_chars(), 0..=(length as usize))
397 )) -> String {
398 let mut buf = String::with_capacity(length as usize);
399 buf.push(leading_char);
400 for c in rest {
401 if !buf.is_empty() && buf.len() + c.len_utf8() > length as usize {
402 break;
403 }
404 buf.push(c);
405 }
406 buf
407 }
408 }
409
410 prop_compose! {
411 fn const_ident_raw_any(length: u32)
413 ((leading_char, rest) in (
414 proptest::char::range('A', 'Z'),
415 vec(const_ident_chars(), 0..=(length as usize))
416 )) -> String {
417 let mut buf = String::with_capacity(length as usize);
418 buf.push(leading_char);
419 for c in rest {
420 if !buf.is_empty() && buf.len() + c.len_utf8() > length as usize {
421 break;
422 }
423 buf.push(c);
424 }
425 buf
426 }
427 }
428
429 prop_compose! {
430 pub fn ident_any(length: u32)
432 (raw in ident_raw_any(length)
433 .prop_filter(
434 "identifiers must be valid",
435 |s| Ident::validate(s).is_ok()
436 )
437 ) -> Ident {
438 Ident::from_raw_parts(Span::new(SourceSpan::UNKNOWN, raw.into_boxed_str().into()))
439 }
440 }
441
442 prop_compose! {
443 pub fn bare_ident_any(length: u32)
446 (raw in bare_ident_raw_any(length)
447 .prop_filter(
448 "identifiers must be valid",
449 |s| Ident::validate(s).is_ok()
450 )
451 ) -> Ident {
452 Ident::from_raw_parts(Span::new(SourceSpan::UNKNOWN, raw.into_boxed_str().into()))
453 }
454 }
455
456 prop_compose! {
457 pub fn const_ident_any(length: u32)
460 (raw in const_ident_raw_any(length)
461 .prop_filter(
462 "identifiers must be valid",
463 |s| Ident::validate(s).is_ok()
464 )
465 ) -> Ident {
466 let id = Ident::from_raw_parts(Span::new(SourceSpan::UNKNOWN, raw.into_boxed_str().into()));
467 assert!(id.is_constant_ident());
468 id
469 }
470 }
471
472 prop_compose! {
473 pub fn builtin_type_any()
475 (name in prop_oneof![
476 Just(crate::ast::types::Type::I1),
477 Just(crate::ast::types::Type::I8),
478 Just(crate::ast::types::Type::U8),
479 Just(crate::ast::types::Type::I16),
480 Just(crate::ast::types::Type::U16),
481 Just(crate::ast::types::Type::I32),
482 Just(crate::ast::types::Type::U32),
483 Just(crate::ast::types::Type::I64),
484 Just(crate::ast::types::Type::U64),
485 Just(crate::ast::types::Type::I128),
486 Just(crate::ast::types::Type::U128),
487 Just(crate::ast::types::Type::Felt),
488 ]) -> Ident {
489 Ident::from_raw_parts(Span::new(SourceSpan::UNKNOWN, name.to_string().into_boxed_str().into()))
490 }
491 }
492
493 prop_compose! {
494 pub fn ident_any_random_length()
496 (length in 1..u8::MAX)
497 (id in ident_any(length as u32)) -> Ident {
498 id
499 }
500 }
501
502 prop_compose! {
503 pub fn bare_ident_any_random_length()
506 (length in 1..u8::MAX)
507 (id in ident_any(length as u32)) -> Ident {
508 id
509 }
510 }
511
512 prop_compose! {
513 pub fn const_ident_any_random_length()
516 (length in 1..u8::MAX)
517 (id in const_ident_any(length as u32)) -> Ident {
518 id
519 }
520 }
521}