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::utils::{
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_serde_macros::serde_test(winter_serde(true))
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 fmt::Display::fmt(&self.name, f)
219 }
220}
221
222impl FromStr for Ident {
223 type Err = IdentError;
224
225 fn from_str(s: &str) -> Result<Self, Self::Err> {
226 Self::validate(s)?;
227 let name = Arc::from(s.to_string().into_boxed_str());
228 Ok(Self { span: SourceSpan::default(), name })
229 }
230}
231
232impl From<Ident> for miden_utils_diagnostics::miette::SourceSpan {
233 fn from(value: Ident) -> Self {
234 value.span.into()
235 }
236}
237
238#[cfg(feature = "serde")]
239impl serde::Serialize for Ident {
240 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
241 where
242 S: serde::Serializer,
243 {
244 serializer.serialize_str(self.as_str())
245 }
246}
247
248#[cfg(feature = "serde")]
249impl<'de> serde::Deserialize<'de> for Ident {
250 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
251 where
252 D: serde::Deserializer<'de>,
253 {
254 let name = <&'de str as serde::Deserialize>::deserialize(deserializer)?;
255 Self::new(name).map_err(serde::de::Error::custom)
256 }
257}
258
259impl Serializable for Ident {
260 fn write_into<W: ByteWriter>(&self, target: &mut W) {
261 target.write_usize(self.len());
262 target.write_bytes(self.as_bytes());
263 }
264}
265
266impl Deserializable for Ident {
267 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
268 use alloc::string::ToString;
269
270 let len = source.read_usize()?;
271 let bytes = source.read_slice(len)?;
272 let id = core::str::from_utf8(bytes)
273 .map_err(|err| DeserializationError::InvalidValue(err.to_string()))?;
274 Self::new(id).map_err(|err| DeserializationError::InvalidValue(err.to_string()))
275 }
276}
277
278#[cfg(feature = "arbitrary")]
279pub mod arbitrary {
280 use alloc::{borrow::Cow, string::String};
281
282 use proptest::{char::CharStrategy, collection::vec, prelude::*};
283
284 use super::*;
285
286 impl Arbitrary for Ident {
287 type Parameters = ();
288
289 fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
290 ident_any_random_length().boxed()
291 }
292
293 type Strategy = BoxedStrategy<Self>;
294 }
295
296 const SPECIAL: [char; 32] = const {
299 let mut buf = ['a'; 32];
300 let mut idx = 0;
301 let mut range_idx = 0;
302 while range_idx < SPECIAL_RANGES.len() {
303 let range = &SPECIAL_RANGES[range_idx];
304 range_idx += 1;
305 let mut j = *range.start() as u32;
306 let end = *range.end() as u32;
307 while j <= end {
308 unsafe {
309 buf[idx] = char::from_u32_unchecked(j);
310 }
311 idx += 1;
312 j += 1;
313 }
314 }
315 buf
316 };
317
318 const SPECIAL_RANGES: &[core::ops::RangeInclusive<char>] =
319 &['!'..='/', ':'..='@', '['..='`', '{'..='~'];
320 const PREFERRED_RANGES: &[core::ops::RangeInclusive<char>] = &['a'..='z', 'A'..='Z'];
321 const EXTRA_RANGES: &[core::ops::RangeInclusive<char>] = &['0'..='9', 'à'..='ö', 'ø'..='ÿ'];
322
323 const PREFERRED_CONSTANT_RANGES: &[core::ops::RangeInclusive<char>] = &['A'..='Z'];
324 const EXTRA_CONSTANT_RANGES: &[core::ops::RangeInclusive<char>] = &['0'..='9'];
325
326 prop_compose! {
327 fn bare_ident_chars()
330 (c in CharStrategy::new_borrowed(
331 &['_'],
332 PREFERRED_RANGES,
333 &['0'..='9']
334 )) -> char {
335 c
336 }
337 }
338
339 prop_compose! {
340 fn ident_chars()
343 (c in CharStrategy::new_borrowed(
344 &SPECIAL,
345 PREFERRED_RANGES,
346 EXTRA_RANGES
347 )) -> char {
348 c
349 }
350 }
351
352 prop_compose! {
353 fn const_ident_chars()
355 (c in CharStrategy::new_borrowed(
356 &['_'],
357 PREFERRED_CONSTANT_RANGES,
358 EXTRA_CONSTANT_RANGES
359 )) -> char {
360 c
361 }
362 }
363
364 prop_compose! {
365 fn ident_raw_any(length: u32)
370 ((leading_char, rest) in (
371 proptest::char::ranges(Cow::Borrowed(&['a'..='z', '_'..='_'])),
372 vec(ident_chars(), 0..=(length as usize))
373 )) -> String {
374 let mut buf = String::with_capacity(length as usize);
375 buf.push(leading_char);
376 for c in rest {
377 if !buf.is_empty() && buf.len() + c.len_utf8() > length as usize {
378 break;
379 }
380 buf.push(c);
381 }
382 buf
383 }
384 }
385
386 prop_compose! {
387 fn bare_ident_raw_any(length: u32)
389 ((leading_char, rest) in (
390 proptest::char::range('a', 'z'),
391 vec(bare_ident_chars(), 0..=(length as usize))
392 )) -> String {
393 let mut buf = String::with_capacity(length as usize);
394 buf.push(leading_char);
395 for c in rest {
396 if !buf.is_empty() && buf.len() + c.len_utf8() > length as usize {
397 break;
398 }
399 buf.push(c);
400 }
401 buf
402 }
403 }
404
405 prop_compose! {
406 fn const_ident_raw_any(length: u32)
408 ((leading_char, rest) in (
409 proptest::char::range('A', 'Z'),
410 vec(const_ident_chars(), 0..=(length as usize))
411 )) -> String {
412 let mut buf = String::with_capacity(length as usize);
413 buf.push(leading_char);
414 for c in rest {
415 if !buf.is_empty() && buf.len() + c.len_utf8() > length as usize {
416 break;
417 }
418 buf.push(c);
419 }
420 buf
421 }
422 }
423
424 prop_compose! {
425 pub fn ident_any(length: u32)
427 (raw in ident_raw_any(length)
428 .prop_filter(
429 "identifiers must be valid",
430 |s| Ident::validate(s).is_ok()
431 )
432 ) -> Ident {
433 Ident::from_raw_parts(Span::new(SourceSpan::UNKNOWN, raw.into_boxed_str().into()))
434 }
435 }
436
437 prop_compose! {
438 pub fn bare_ident_any(length: u32)
441 (raw in bare_ident_raw_any(length)
442 .prop_filter(
443 "identifiers must be valid",
444 |s| Ident::validate(s).is_ok()
445 )
446 ) -> Ident {
447 Ident::from_raw_parts(Span::new(SourceSpan::UNKNOWN, raw.into_boxed_str().into()))
448 }
449 }
450
451 prop_compose! {
452 pub fn const_ident_any(length: u32)
455 (raw in const_ident_raw_any(length)
456 .prop_filter(
457 "identifiers must be valid",
458 |s| Ident::validate(s).is_ok()
459 )
460 ) -> Ident {
461 let id = Ident::from_raw_parts(Span::new(SourceSpan::UNKNOWN, raw.into_boxed_str().into()));
462 assert!(id.is_constant_ident());
463 id
464 }
465 }
466
467 prop_compose! {
468 pub fn builtin_type_any()
470 (name in prop_oneof![
471 Just(crate::ast::types::Type::I1),
472 Just(crate::ast::types::Type::I8),
473 Just(crate::ast::types::Type::U8),
474 Just(crate::ast::types::Type::I16),
475 Just(crate::ast::types::Type::U16),
476 Just(crate::ast::types::Type::I32),
477 Just(crate::ast::types::Type::U32),
478 Just(crate::ast::types::Type::I64),
479 Just(crate::ast::types::Type::U64),
480 Just(crate::ast::types::Type::I128),
481 Just(crate::ast::types::Type::U128),
482 Just(crate::ast::types::Type::Felt),
483 ]) -> Ident {
484 Ident::from_raw_parts(Span::new(SourceSpan::UNKNOWN, name.to_string().into_boxed_str().into()))
485 }
486 }
487
488 prop_compose! {
489 pub fn ident_any_random_length()
491 (length in 1..u8::MAX)
492 (id in ident_any(length as u32)) -> Ident {
493 id
494 }
495 }
496
497 prop_compose! {
498 pub fn bare_ident_any_random_length()
501 (length in 1..u8::MAX)
502 (id in ident_any(length as u32)) -> Ident {
503 id
504 }
505 }
506
507 prop_compose! {
508 pub fn const_ident_any_random_length()
511 (length in 1..u8::MAX)
512 (id in const_ident_any(length as u32)) -> Ident {
513 id
514 }
515 }
516}