Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 56 additions & 3 deletions cedar-policy-core/src/ast/entity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use crate::ast::*;
use crate::evaluator::{EvaluationError, RestrictedEvaluator};
use crate::extensions::Extensions;
use crate::parser::err::ParseErrors;
use crate::parser::Loc;
use crate::transitive_closure::TCNode;
use crate::FromNormalizedStr;
use itertools::Itertools;
Expand Down Expand Up @@ -62,13 +63,43 @@ impl std::fmt::Display for EntityType {
}

/// Unique ID for an entity. These represent entities in the AST.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EntityUID {
/// Typename of the entity
ty: EntityType,
/// EID of the entity
eid: Eid,
/// Location of the entity in policy source
#[serde(skip)]
loc: Option<Loc>,
}

/// `PartialEq` implementation ignores the `loc`.
impl PartialEq for EntityUID {
fn eq(&self, other: &Self) -> bool {
self.ty == other.ty && self.eid == other.eid
}
}
impl Eq for EntityUID {}

impl std::hash::Hash for EntityUID {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
// hash the ty and eid, in line with the `PartialEq` impl which compares
// the ty and eid.
self.ty.hash(state);
self.eid.hash(state);
}
}

impl PartialOrd for EntityUID {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for EntityUID {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.ty.cmp(&other.ty).then(self.eid.cmp(&other.eid))
}
}

impl StaticallyTyped for EntityUID {
Expand All @@ -87,6 +118,7 @@ impl EntityUID {
Self {
ty: Self::test_entity_type(),
eid: Eid(eid.into()),
loc: None,
}
}
// by default, Coverlay does not track coverage for lines after a line
Expand All @@ -113,6 +145,7 @@ impl EntityUID {
Ok(Self {
ty: EntityType::Specified(Name::parse_unqualified_name(typename)?),
eid: Eid(eid.into()),
loc: None,
})
}

Expand All @@ -122,11 +155,17 @@ impl EntityUID {
(self.ty, self.eid)
}

/// Get the source location for this `EntityUID`.
pub fn loc(&self) -> &Option<Loc> {
&self.loc
}

/// Create a nominally-typed `EntityUID` with the given typename and EID
pub fn from_components(name: Name, eid: Eid) -> Self {
pub fn from_components(name: Name, eid: Eid, loc: Option<Loc>) -> Self {
Self {
ty: EntityType::Specified(name),
eid,
loc,
}
}

Expand All @@ -135,6 +174,7 @@ impl EntityUID {
Self {
ty: EntityType::Unspecified,
eid,
loc: None,
}
}

Expand Down Expand Up @@ -175,6 +215,17 @@ impl FromNormalizedStr for EntityUID {
}
}

#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for EntityUID {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(Self {
ty: u.arbitrary()?,
eid: u.arbitrary()?,
loc: None,
})
}
}

/// EID type is just a SmolStr for now
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone, Hash, PartialOrd, Ord)]
pub struct Eid(SmolStr);
Expand Down Expand Up @@ -497,12 +548,14 @@ mod test {
let e2 = EntityUID::from_components(
Name::parse_unqualified_name("test_entity_type").expect("should be a valid identifier"),
Eid("foo".into()),
None,
);
let e3 = EntityUID::unspecified_from_eid(Eid("foo".into()));
let e4 = EntityUID::unspecified_from_eid(Eid("bar".into()));
let e5 = EntityUID::from_components(
Name::parse_unqualified_name("Unspecified").expect("should be a valid identifier"),
Eid("foo".into()),
None,
);

// an EUID is equal to itself
Expand Down
59 changes: 54 additions & 5 deletions cedar-policy-core/src/ast/name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,42 @@ use super::PrincipalOrResource;
/// This is the `Name` type used to name types, functions, etc.
/// The name can include namespaces.
/// Clone is O(1).
#[derive(Debug, PartialEq, Eq, Clone, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Debug, Clone)]
pub struct Name {
/// Basename
pub(crate) id: Id,
/// Namespaces
pub(crate) path: Arc<Vec<Id>>,
/// Location of the name in source
pub(crate) loc: Option<Loc>,
}

/// `PartialEq` implementation ignores the `loc`.
impl PartialEq for Name {
fn eq(&self, other: &Self) -> bool {
self.id == other.id && self.path == other.path
}
}
impl Eq for Name {}

impl std::hash::Hash for Name {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
// hash the ty and eid, in line with the `PartialEq` impl which compares
// the ty and eid.
self.id.hash(state);
self.path.hash(state);
}
}

impl PartialOrd for Name {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Name {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.id.cmp(&other.id).then(self.path.cmp(&other.path))
}
}

/// A shortcut for `Name::unqualified_name`
Expand All @@ -61,10 +90,11 @@ impl TryFrom<Name> for Id {

impl Name {
/// A full constructor for `Name`
pub fn new(basename: Id, path: impl IntoIterator<Item = Id>) -> Self {
pub fn new(basename: Id, path: impl IntoIterator<Item = Id>, loc: Option<Loc>) -> Self {
Self {
id: basename,
path: Arc::new(path.into_iter().collect()),
loc,
}
}

Expand All @@ -73,6 +103,7 @@ impl Name {
Self {
id,
path: Arc::new(vec![]),
loc: None,
}
}

Expand All @@ -82,15 +113,21 @@ impl Name {
Ok(Self {
id: s.parse()?,
path: Arc::new(vec![]),
loc: None,
})
}

/// Given a type basename and a namespace (as a `Name` itself),
/// return a `Name` representing the type's fully qualified name
pub fn type_in_namespace(basename: Id, namespace: Name) -> Name {
pub fn type_in_namespace(basename: Id, namespace: Name, loc: Option<Loc>) -> Name {
let mut path = Arc::unwrap_or_clone(namespace.path);
path.push(namespace.id);
Name::new(basename, path)
Name::new(basename, path, loc)
}

/// Get the source location
pub fn loc(&self) -> &Option<Loc> {
&self.loc
}

/// Get the basename of the `Name` (ie, with namespaces stripped).
Expand Down Expand Up @@ -129,6 +166,7 @@ impl Name {
.namespace_components()
.chain(std::iter::once(namespace.basename()))
.cloned(),
self.loc.clone(),
),
None => self.clone(),
}
Expand Down Expand Up @@ -179,6 +217,17 @@ impl FromNormalizedStr for Name {
}
}

#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for Name {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(Self {
id: u.arbitrary()?,
path: u.arbitrary()?,
loc: None,
})
}
}

struct NameVisitor;

impl<'de> serde::de::Visitor<'de> for NameVisitor {
Expand Down
3 changes: 3 additions & 0 deletions cedar-policy-core/src/ast/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2142,6 +2142,7 @@ mod test {
let id = EntityUID::from_components(
name::Name::unqualified_name(id::Id::new_unchecked("s")),
entity::Eid::new("eid"),
None,
);
let mut i = EntityIterator::One(&id);
assert_eq!(i.next(), Some(&id));
Expand All @@ -2153,10 +2154,12 @@ mod test {
let id1 = EntityUID::from_components(
name::Name::unqualified_name(id::Id::new_unchecked("s")),
entity::Eid::new("eid1"),
None,
);
let id2 = EntityUID::from_components(
name::Name::unqualified_name(id::Id::new_unchecked("s")),
entity::Eid::new("eid2"),
None,
);
let v = vec![&id1, &id2];
let mut i = EntityIterator::Bunch(v);
Expand Down
1 change: 1 addition & 0 deletions cedar-policy-core/src/entities/json/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ impl TryFrom<TypeAndId> for EntityUID {
Ok(EntityUID::from_components(
Name::from_normalized_str(&e.entity_type)?,
Eid::new(e.id),
None,
))
}
}
Expand Down
2 changes: 2 additions & 0 deletions cedar-policy-core/src/est/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1108,6 +1108,7 @@ fn interpret_primary(
__entity: TypeAndId::from(ast::EntityUID::from_components(
name,
ast::Eid::new(eid),
None,
)),
}))),
Err(unescape_errs) => {
Expand Down Expand Up @@ -1143,6 +1144,7 @@ fn interpret_primary(
.and_then(|id| id.to_string().parse().map_err(Into::into))
})
.collect::<Result<Vec<ast::Id>, ParseErrors>>()?,
Some(node.loc.clone()),
))),
(path, id) => {
let (l, r, src) = match (path.first(), path.last()) {
Expand Down
13 changes: 8 additions & 5 deletions cedar-policy-core/src/parser/cst_to_ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2122,7 +2122,9 @@ impl Node<Option<cst::Name>> {

// computation and error generation is complete, so fail or construct
match (maybe_name, path.len()) {
(Some(r), len) if len == name.path.len() => Some(construct_name(path, r)),
(Some(r), len) if len == name.path.len() => {
Some(construct_name(path, r, self.loc.clone()))
}
_ => None,
}
}
Expand Down Expand Up @@ -2231,7 +2233,7 @@ impl Node<Option<cst::Ref>> {
};

match (maybe_path, maybe_eid) {
(Some(p), Some(e)) => Some(construct_refr(p, e)),
(Some(p), Some(e)) => Some(construct_refr(p, e, self.loc.clone())),
_ => None,
}
}
Expand Down Expand Up @@ -2347,15 +2349,16 @@ fn construct_string_from_var(v: ast::Var) -> SmolStr {
ast::Var::Context => "context".into(),
}
}
fn construct_name(path: Vec<ast::Id>, id: ast::Id) -> ast::Name {
fn construct_name(path: Vec<ast::Id>, id: ast::Id, loc: Loc) -> ast::Name {
ast::Name {
id,
path: Arc::new(path),
loc: Some(loc),
}
}
fn construct_refr(p: ast::Name, n: SmolStr) -> ast::EntityUID {
fn construct_refr(p: ast::Name, n: SmolStr, loc: Loc) -> ast::EntityUID {
let eid = ast::Eid::new(n);
ast::EntityUID::from_components(p, eid)
ast::EntityUID::from_components(p, eid, Some(loc))
}
fn construct_expr_ref(r: ast::EntityUID, loc: Loc) -> ast::Expr {
ast::ExprBuilder::new().with_source_loc(loc).val(r)
Expand Down
12 changes: 5 additions & 7 deletions cedar-policy-validator/src/human_schema/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,11 @@ impl std::fmt::Display for Path {

impl From<Path> for Name {
fn from(value: Path) -> Self {
value.0.node.into()
Self::new(
value.0.node.basename,
value.0.node.namespace,
Some(value.0.loc),
)
}
}

Expand All @@ -123,12 +127,6 @@ struct PathInternal {
namespace: Vec<Id>,
}

impl From<PathInternal> for Name {
fn from(value: PathInternal) -> Self {
Self::new(value.basename, value.namespace)
}
}

impl PathInternal {
fn iter(&self) -> impl Iterator<Item = &Id> {
self.namespace.iter().chain(once(&self.basename))
Expand Down
1 change: 1 addition & 0 deletions cedar-policy-validator/src/human_schema/to_json_schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,7 @@ impl<'a> ConversionContext<'a> {
&Some(Name::new(
prefix_base.clone(),
prefix_prefix.into_iter().cloned(),
None,
)),
),
None =>
Expand Down
Loading