Skip to content

Commit

Permalink
Extract cycle searching into function
Browse files Browse the repository at this point in the history
  • Loading branch information
antoniosarosi committed Jan 1, 2025
1 parent 32c0a3a commit 0b4ea0b
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 15 deletions.
6 changes: 1 addition & 5 deletions engine/baml-lib/baml-core/src/ir/repr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -451,11 +451,7 @@ impl WithRepr<FieldType> for ast::FieldType {
}
}
Some(TypeWalker::TypeAlias(alias_walker)) => {
if db
.recursive_alias_cycles()
.iter()
.any(|cycle| cycle.contains(&alias_walker.id))
{
if db.is_recursive_type_alias(&alias_walker.id) {
FieldType::RecursiveTypeAlias(alias_walker.name().to_string())
} else {
alias_walker.resolved().to_owned().repr(db)?
Expand Down
6 changes: 1 addition & 5 deletions engine/baml-lib/parser-database/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,11 +244,7 @@ impl ParserDatabase {
// Add the resolved name itself to the deps.
collected_deps.insert(ident.name().to_owned());
// If the type is an alias then don't recurse.
if self
.recursive_alias_cycles()
.iter()
.any(|cycle| cycle.contains(&walker.id))
{
if self.is_recursive_type_alias(&walker.id) {
None
} else {
Some(ident.name())
Expand Down
15 changes: 10 additions & 5 deletions engine/baml-lib/parser-database/src/walkers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,15 @@ impl<'db> crate::ParserDatabase {
&self.types.recursive_alias_cycles
}

/// Returns `true` if the alias is part of a cycle.
pub fn is_recursive_type_alias(&self, alias: &TypeAliasId) -> bool {
// TODO: O(n)
// We need an additional hashmap or a Merge-Find Set or something.
self.recursive_alias_cycles()
.iter()
.any(|cycle| cycle.contains(alias))
}

/// Returns the resolved aliases map.
pub fn resolved_type_alias_by_name(&self, alias: &str) -> Option<&FieldType> {
match self.find_type_by_str(alias) {
Expand Down Expand Up @@ -293,11 +302,7 @@ impl<'db> crate::ParserDatabase {
Some(TypeWalker::Class(_)) => Type::ClassRef(idn.to_string()),
Some(TypeWalker::Enum(_)) => Type::String,
Some(TypeWalker::TypeAlias(alias)) => {
if self
.recursive_alias_cycles()
.iter()
.any(|cycle| cycle.contains(&alias.id))
{
if self.is_recursive_type_alias(&alias.id) {
Type::RecursiveTypeAlias(alias.name().to_string())
} else {
Type::Alias {
Expand Down

0 comments on commit 0b4ea0b

Please sign in to comment.