1use super::{id::Id, PrincipalOrResource, UnreservedId};
18use educe::Educe;
19use itertools::Itertools;
20use miette::Diagnostic;
21use ref_cast::RefCast;
22use regex::Regex;
23use serde::{Deserialize, Deserializer, Serialize, Serializer};
24use smol_str::ToSmolStr;
25use std::collections::HashSet;
26use std::fmt::Display;
27use std::str::FromStr;
28use std::sync::Arc;
29use thiserror::Error;
30
31use crate::parser::err::{ParseError, ParseErrors, ToASTError, ToASTErrorKind};
32use crate::parser::Loc;
33use crate::FromNormalizedStr;
34
35#[derive(Educe, Debug, Clone)]
42#[educe(PartialEq, Eq, Hash, PartialOrd, Ord)]
43pub struct InternalName {
44 pub(crate) id: Id,
46 pub(crate) path: Arc<Vec<Id>>,
48 #[educe(PartialEq(ignore))]
50 #[educe(Hash(ignore))]
51 #[educe(PartialOrd(ignore))]
52 pub(crate) loc: Option<Loc>,
53}
54
55impl From<Id> for InternalName {
57 fn from(value: Id) -> Self {
58 Self::unqualified_name(value, None)
59 }
60}
61
62impl TryFrom<InternalName> for Id {
66 type Error = ();
67 fn try_from(value: InternalName) -> Result<Self, Self::Error> {
68 if value.is_unqualified() {
69 Ok(value.id)
70 } else {
71 Err(())
72 }
73 }
74}
75
76impl InternalName {
77 pub fn new(basename: Id, path: impl IntoIterator<Item = Id>, loc: Option<Loc>) -> Self {
79 Self {
80 id: basename,
81 path: Arc::new(path.into_iter().collect()),
82 loc,
83 }
84 }
85
86 pub fn unqualified_name(id: Id, loc: Option<Loc>) -> Self {
88 Self {
89 id,
90 path: Arc::new(vec![]),
91 loc,
92 }
93 }
94
95 pub fn __cedar() -> Self {
97 Self::unqualified_name(Id::new_unchecked("__cedar"), None)
99 }
100
101 pub fn parse_unqualified_name(s: &str) -> Result<Self, ParseErrors> {
104 Ok(Self {
105 id: s.parse()?,
106 path: Arc::new(vec![]),
107 loc: None,
108 })
109 }
110
111 pub fn type_in_namespace(
114 basename: Id,
115 namespace: InternalName,
116 loc: Option<Loc>,
117 ) -> InternalName {
118 let mut path = Arc::unwrap_or_clone(namespace.path);
119 path.push(namespace.id);
120 InternalName::new(basename, path, loc)
121 }
122
123 pub fn loc(&self) -> Option<&Loc> {
125 self.loc.as_ref()
126 }
127
128 pub fn basename(&self) -> &Id {
130 &self.id
131 }
132
133 pub fn namespace_components(&self) -> impl Iterator<Item = &Id> {
135 self.path.iter()
136 }
137
138 pub fn namespace(&self) -> String {
145 self.path.iter().join("::")
146 }
147
148 pub fn qualify_with(&self, namespace: Option<&InternalName>) -> InternalName {
167 if self.is_unqualified() {
168 match namespace {
169 Some(namespace) => Self::new(
170 self.basename().clone(),
171 namespace
172 .namespace_components()
173 .chain(std::iter::once(namespace.basename()))
174 .cloned(),
175 self.loc.clone(),
176 ),
177 None => self.clone(),
178 }
179 } else {
180 self.clone()
181 }
182 }
183
184 pub fn qualify_with_name(&self, namespace: Option<&Name>) -> InternalName {
186 let ns = namespace.map(AsRef::as_ref);
187 self.qualify_with(ns)
188 }
189
190 pub fn is_unqualified(&self) -> bool {
192 self.path.is_empty()
193 }
194
195 pub fn is_reserved(&self) -> bool {
198 self.path
199 .iter()
200 .chain(std::iter::once(&self.id))
201 .any(|id| id.is_reserved())
202 }
203}
204
205impl std::fmt::Display for InternalName {
206 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207 for elem in self.path.as_ref() {
208 write!(f, "{elem}::")?;
209 }
210 write!(f, "{}", self.id)?;
211 Ok(())
212 }
213}
214
215impl Serialize for InternalName {
218 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
219 where
220 S: Serializer,
221 {
222 self.to_smolstr().serialize(serializer)
223 }
224}
225
226impl std::str::FromStr for InternalName {
228 type Err = ParseErrors;
229
230 fn from_str(s: &str) -> Result<Self, Self::Err> {
231 crate::parser::parse_internal_name(s)
232 }
233}
234
235impl FromNormalizedStr for InternalName {
236 fn describe_self() -> &'static str {
237 "internal name"
238 }
239}
240
241#[cfg(feature = "arbitrary")]
242impl<'a> arbitrary::Arbitrary<'a> for InternalName {
243 fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
244 let path_size = u.int_in_range(0..=8)?;
245 Ok(Self {
246 id: u.arbitrary()?,
247 path: Arc::new(
248 (0..path_size)
249 .map(|_| u.arbitrary())
250 .collect::<Result<Vec<Id>, _>>()?,
251 ),
252 loc: None,
253 })
254 }
255}
256
257struct NameVisitor;
258
259impl serde::de::Visitor<'_> for NameVisitor {
260 type Value = InternalName;
261
262 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
263 formatter.write_str("a name consisting of an optional namespace and id")
264 }
265
266 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
267 where
268 E: serde::de::Error,
269 {
270 InternalName::from_normalized_str(value)
271 .map_err(|err| serde::de::Error::custom(format!("invalid name `{value}`: {err}")))
272 }
273}
274
275impl<'de> Deserialize<'de> for InternalName {
278 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
279 where
280 D: Deserializer<'de>,
281 {
282 deserializer.deserialize_str(NameVisitor)
283 }
284}
285
286#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
291#[serde(transparent)]
292pub struct SlotId(pub(crate) ValidSlotId);
293
294impl SlotId {
295 pub fn principal() -> Self {
297 Self(ValidSlotId::Principal)
298 }
299
300 pub fn resource() -> Self {
302 Self(ValidSlotId::Resource)
303 }
304
305 pub fn is_principal(&self) -> bool {
307 matches!(self, Self(ValidSlotId::Principal))
308 }
309
310 pub fn is_resource(&self) -> bool {
312 matches!(self, Self(ValidSlotId::Resource))
313 }
314}
315
316impl From<PrincipalOrResource> for SlotId {
317 fn from(v: PrincipalOrResource) -> Self {
318 match v {
319 PrincipalOrResource::Principal => SlotId::principal(),
320 PrincipalOrResource::Resource => SlotId::resource(),
321 }
322 }
323}
324
325impl std::fmt::Display for SlotId {
326 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
327 write!(f, "{}", self.0)
328 }
329}
330
331#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
333pub(crate) enum ValidSlotId {
334 #[serde(rename = "?principal")]
335 Principal,
336 #[serde(rename = "?resource")]
337 Resource,
338}
339
340impl std::fmt::Display for ValidSlotId {
341 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
342 let s = match self {
343 ValidSlotId::Principal => "principal",
344 ValidSlotId::Resource => "resource",
345 };
346 write!(f, "?{s}")
347 }
348}
349
350#[derive(Educe, Debug, Clone)]
352#[educe(PartialEq, Eq, Hash)]
353pub struct Slot {
354 pub id: SlotId,
356 #[educe(PartialEq(ignore))]
358 #[educe(Hash(ignore))]
359 pub loc: Option<Loc>,
360}
361
362#[cfg(test)]
363mod vars_test {
364 use super::*;
365 #[test]
367 fn vars_correct() {
368 SlotId::principal();
369 SlotId::resource();
370 }
371
372 #[test]
373 fn display() {
374 assert_eq!(format!("{}", SlotId::principal()), "?principal")
375 }
376}
377
378#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Serialize, RefCast)]
384#[repr(transparent)]
385#[serde(transparent)]
386pub struct Name(pub(crate) InternalName);
387
388impl From<UnreservedId> for Name {
389 fn from(value: UnreservedId) -> Self {
390 Self::unqualified_name(value)
391 }
392}
393
394impl TryFrom<Name> for UnreservedId {
395 type Error = ();
396 fn try_from(value: Name) -> Result<Self, Self::Error> {
397 if value.0.is_unqualified() {
398 Ok(value.basename())
399 } else {
400 Err(())
401 }
402 }
403}
404
405impl Display for Name {
406 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
407 self.0.fmt(f)
408 }
409}
410
411impl FromStr for Name {
412 type Err = ParseErrors;
413 fn from_str(s: &str) -> Result<Self, Self::Err> {
414 let n: InternalName = s.parse()?;
415 n.try_into().map_err(ParseErrors::singleton)
416 }
417}
418
419#[allow(clippy::unwrap_used)]
421static VALID_NAME_REGEX: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| {
422 Regex::new("^[_a-zA-Z][_a-zA-Z0-9]*(?:::[_a-zA-Z][_a-zA-Z0-9]*)*$").unwrap()
423});
424static RESERVED_IDS: std::sync::LazyLock<HashSet<&'static str>> = std::sync::LazyLock::new(|| {
427 vec![
428 "true", "false", "if", "then", "else", "in", "is", "like", "has",
429 "__cedar",
431 ]
432 .into_iter()
433 .collect()
434});
435
436impl FromNormalizedStr for Name {
437 fn from_normalized_str(s: &str) -> Result<Self, ParseErrors> {
438 if !VALID_NAME_REGEX.is_match(s) {
439 return Err(Self::parse_err_from_str(s));
440 }
441
442 let path_parts: Vec<&str> = s.split("::").collect();
443 if path_parts.iter().any(|s| RESERVED_IDS.contains(s)) {
444 return Err(Self::parse_err_from_str(s));
445 }
446
447 if let Some((last, prefix)) = path_parts.split_last() {
448 Ok(Self(InternalName::new(
449 Id::new_unchecked(*last),
450 prefix.iter().map(|part| Id::new_unchecked(*part)),
451 Some(Loc::new(0..(s.len()), s.into())),
452 )))
453 } else {
454 Err(Self::parse_err_from_str(s))
455 }
456 }
457
458 fn describe_self() -> &'static str {
459 "Name"
460 }
461}
462
463impl<'de> Deserialize<'de> for Name {
466 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
467 where
468 D: Deserializer<'de>,
469 {
470 deserializer
471 .deserialize_str(NameVisitor)
472 .and_then(|n| n.try_into().map_err(serde::de::Error::custom))
473 }
474}
475
476impl Name {
477 pub fn parse_unqualified_name(s: &str) -> Result<Self, ParseErrors> {
480 InternalName::parse_unqualified_name(s)
481 .and_then(|n| n.try_into().map_err(ParseErrors::singleton))
482 }
483
484 pub fn unqualified_name(id: UnreservedId) -> Self {
486 Self(InternalName::unqualified_name(id.0, None))
488 }
489
490 pub fn basename_as_ref(&self) -> &Id {
493 self.0.basename()
494 }
495
496 pub fn basename(&self) -> UnreservedId {
499 #![allow(clippy::unwrap_used)]
501 self.0.basename().clone().try_into().unwrap()
502 }
503
504 pub fn is_unqualified(&self) -> bool {
506 self.0.is_unqualified()
507 }
508
509 pub fn qualify_with(&self, namespace: Option<&InternalName>) -> InternalName {
513 self.0.qualify_with(namespace)
514 }
515
516 pub fn qualify_with_name(&self, namespace: Option<&Self>) -> Self {
521 Self(self.as_ref().qualify_with(namespace.map(|n| n.as_ref())))
524 }
525
526 pub fn loc(&self) -> Option<&Loc> {
528 self.0.loc()
529 }
530
531 fn parse_err_from_str(s: &str) -> ParseErrors {
532 match Self::from_str(s) {
533 Err(parse_err) => parse_err,
534 Ok(parsed) => {
535 let normalized_src = parsed.to_string();
536 let diff_byte = s
537 .bytes()
538 .zip(normalized_src.bytes())
539 .enumerate()
540 .find(|(_, (b0, b1))| b0 != b1)
541 .map(|(idx, _)| idx)
542 .unwrap_or_else(|| s.len().min(normalized_src.len()));
543
544 ParseErrors::singleton(ParseError::ToAST(ToASTError::new(
545 ToASTErrorKind::NonNormalizedString {
546 kind: Self::describe_self(),
547 src: s.to_string(),
548 normalized_src,
549 },
550 Some(Loc::new(diff_byte, s.into())),
551 )))
552 }
553 }
554 }
555}
556
557#[derive(Debug, Clone, PartialEq, Eq, Error, Diagnostic, Hash)]
559#[error("The name `{0}` contains `__cedar`, which is reserved")]
560pub struct ReservedNameError(pub(crate) InternalName);
561
562impl ReservedNameError {
563 pub fn name(&self) -> &InternalName {
565 &self.0
566 }
567}
568
569impl From<ReservedNameError> for ParseError {
570 fn from(value: ReservedNameError) -> Self {
571 ParseError::ToAST(ToASTError::new(
572 value.clone().into(),
573 value.0.loc.clone().or_else(|| {
574 let name_str = value.0.to_string();
575 Some(Loc::new(0..(name_str.len()), name_str.into()))
576 }),
577 ))
578 }
579}
580
581impl TryFrom<InternalName> for Name {
582 type Error = ReservedNameError;
583 fn try_from(value: InternalName) -> Result<Self, Self::Error> {
584 if value.is_reserved() {
585 Err(ReservedNameError(value))
586 } else {
587 Ok(Self(value))
588 }
589 }
590}
591
592impl<'a> TryFrom<&'a InternalName> for &'a Name {
593 type Error = ReservedNameError;
594 fn try_from(value: &'a InternalName) -> Result<&'a Name, ReservedNameError> {
595 if value.is_reserved() {
596 Err(ReservedNameError(value.clone()))
597 } else {
598 Ok(<Name as RefCast>::ref_cast(value))
599 }
600 }
601}
602
603impl From<Name> for InternalName {
604 fn from(value: Name) -> Self {
605 value.0
606 }
607}
608
609impl AsRef<InternalName> for Name {
610 fn as_ref(&self) -> &InternalName {
611 &self.0
612 }
613}
614
615#[cfg(feature = "arbitrary")]
616impl<'a> arbitrary::Arbitrary<'a> for Name {
617 fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
618 let path_size = u.int_in_range(0..=8)?;
622 let basename: UnreservedId = u.arbitrary()?;
623 let path: Vec<UnreservedId> = (0..path_size)
624 .map(|_| u.arbitrary())
625 .collect::<Result<Vec<_>, _>>()?;
626 let name = InternalName::new(basename.into(), path.into_iter().map(|id| id.into()), None);
627 #[allow(clippy::unwrap_used)]
629 Ok(name.try_into().unwrap())
630 }
631
632 fn size_hint(depth: usize) -> (usize, Option<usize>) {
633 <InternalName as arbitrary::Arbitrary>::size_hint(depth)
634 }
635}
636
637#[cfg(test)]
638mod test {
639 use super::*;
640
641 #[test]
642 fn normalized_name() {
643 InternalName::from_normalized_str("foo").expect("should be OK");
644 InternalName::from_normalized_str("foo::bar").expect("should be OK");
645 InternalName::from_normalized_str(r#"foo::"bar""#).expect_err("shouldn't be OK");
646 InternalName::from_normalized_str(" foo").expect_err("shouldn't be OK");
647 InternalName::from_normalized_str("foo ").expect_err("shouldn't be OK");
648 InternalName::from_normalized_str("foo\n").expect_err("shouldn't be OK");
649 InternalName::from_normalized_str("foo//comment").expect_err("shouldn't be OK");
650 }
651
652 #[test]
653 fn qualify_with() {
654 assert_eq!(
655 "foo::bar::baz",
656 InternalName::from_normalized_str("baz")
657 .unwrap()
658 .qualify_with(Some(&"foo::bar".parse().unwrap()))
659 .to_smolstr()
660 );
661 assert_eq!(
662 "C::D",
663 InternalName::from_normalized_str("C::D")
664 .unwrap()
665 .qualify_with(Some(&"A::B".parse().unwrap()))
666 .to_smolstr()
667 );
668 assert_eq!(
669 "A::B::C::D",
670 InternalName::from_normalized_str("D")
671 .unwrap()
672 .qualify_with(Some(&"A::B::C".parse().unwrap()))
673 .to_smolstr()
674 );
675 assert_eq!(
676 "B::C::D",
677 InternalName::from_normalized_str("B::C::D")
678 .unwrap()
679 .qualify_with(Some(&"A".parse().unwrap()))
680 .to_smolstr()
681 );
682 assert_eq!(
683 "A",
684 InternalName::from_normalized_str("A")
685 .unwrap()
686 .qualify_with(None)
687 .to_smolstr()
688 )
689 }
690
691 #[test]
692 fn test_reserved() {
693 for n in [
694 "__cedar",
695 "__cedar::A",
696 "__cedar::A::B",
697 "A::__cedar",
698 "A::__cedar::B",
699 ] {
700 assert!(InternalName::from_normalized_str(n).unwrap().is_reserved());
701 }
702
703 for n in ["__cedarr", "A::_cedar", "A::___cedar::B"] {
704 assert!(!InternalName::from_normalized_str(n).unwrap().is_reserved());
705 }
706 }
707
708 #[test]
709 fn test_name_identifier_intersection() {
710 let not_reserved_for_ids = [
711 "permit",
712 "forbid",
713 "when",
714 "unless",
715 "principal",
716 "action",
717 "resource",
718 "context",
719 ];
720
721 for id in not_reserved_for_ids {
722 assert!(Name::from_normalized_str(&format!("A::{id}")).is_ok());
723 }
724
725 for id in RESERVED_IDS.iter() {
726 assert!(Name::from_normalized_str(&format!("A::{id}")).is_err());
727 }
728 }
729}