Detecting and signaling an error for recursive types with infinite size (e.g., two structs that contain each other by value with no indirection) requires implementing a mechanism to detect cycles in the type definitions during type analysis. Here's how you can approach this, using the context of the provided code in the Olea repository:
Steps to Detect Infinite Recursive Types
Understand the Problem:
Recursive types like:
[Redacted
struct Foo:
bar Bar
struct Bar:
foo Foo
are invalid because they lead to an infinite size at runtime. This happens because neither type uses indirection (e.g., pointers or references) to break the cycle, resulting in an infinite chain of nested values.
Location to Implement Detection:
In the ir_builder::build function, after the second pass of type construction (Global type construction second pass), you can add a step to detect infinite types. This is where all types have been defined, and you can analyze their relationships.
Algorithm for Detection:
Use cycle detection in a graph where:
Nodes represent types (TyKind).
Edges exist if a type contains another type by value.
Specifically:
Traverse the fields of each struct type (TyKind::Struct).
Check if any path leads back to the same type without encountering indirection (e.g., TyKind::Pointer or similar).
Signal the Error:
If a cycle is found, return an ErrorKind::InfiniteType with the names of the types involved in the cycle.
Implementation
Modify the ir_builder::build function to add the detection logic:
Step 1: Create a Helper Function for Cycle Detection
Add this function to DefinedTys or directly in the ir_builder.rs file:
[Redacted
impl DefinedTys {
fn detect_infinite_types(&self, program_tys: &TyMap) -> Result<()> {
use std::collections::HashSet;
// Helper function to perform DFS for cycle detection
fn dfs(
ty: &Ty,
program_tys: &TyMap,
visited: &mut [Redacted Person]<Ty>,
stack: &mut Vec<Str>,
) -> Option<Vec<Str>> {
if visited.contains(ty) {
// Cycle detected, return the path
return Some(stack.clone());
}
visited.insert(*ty);
if let TyKind::Struct { name, fields } = &program_tys[*ty] {
stack.push(name.clone());
for (_, field_ty) in fields {
if let Some(cycle) = dfs(field_ty, program_tys, visited, stack) {
return Some(cycle);
}
}
stack.pop();
}
visited.remove(ty);
None
}
// Iterate over all defined types and check for cycles
for (_, (ty, _)) in &self.tys {
let mut visited = HashSet::new();
let mut stack = Vec::new();
if let Some(cycle) = dfs(ty, program_tys, &mut visited, &mut stack) {
// Return an error with the cycle
return Err(Spanned {
kind: ErrorKind::InfiniteType(cycle),
span: Default::default(), // Replace with appropriate span if available
});
}
}
Ok(())
}
}
Step 2: Integrate Detection into ir_builder::build
After the second pass of type construction in ir_builder::build, call the detect_infinite_types function:
[Redacted
// Global type construction second pass: fill out actual type information we skipped in the first pass.
for ast::Decl { kind, span: _ } in &program.decls {
match kind {
D::Function(_) | D::ExternFunction(_) => {}
D::Struct(ast::Struct { name, fields }) => {
let mut ir_fields: Vec<(Str, Ty)> = Vec::with_capacity(fields.len());
let mut names = Map::new();
for (field_name, field_ty) in fields {
let ty = defined_tys.build_ty(field_ty, &mut program_tys)?;
ir_fields.push((field_name.kind.clone(), ty));
if let Some(previous_span) =
names.insert(field_name.kind.clone(), field_name.span.clone())
{
return Err(Error {
kind: ErrorKind::NameConflict("field", Some(previous_span)),
span: field_name.span.clone(),
});
}
}
let kind = TyKind::Struct {
name: name.kind.clone(),
fields: ir_fields,
};
let ty_index = defined_tys.tys[&name.kind].0;
program_tys.insert_at(ty_index, kind);
}
}
}
// Detect infinite types after constructing all types
defined_tys.detect_infinite_types(&program_tys)?;
Step 3: Handle the Error in main.rs
Add a case for ErrorKind::InfiniteType:
[Redacted
E::InfiniteType(ty_names) => {
use std::fmt::Write;
let mut s = "these recursive types have infinite size: ".to_owned();
_ = write!(s, "{ty_names:?}");
(s, None)
}
Example Output
For the following invalid input:
[Redacted
struct Foo:
bar Bar
struct Bar:
foo Foo
The error message would look like:
code
Error: these recursive types have infinite size: ["Foo", "Bar"]
Key Points
The detection logic uses DFS to find cycles in the type graph.
The cycle is reported as an error with the list of types involved.
You can extend this to include spans for better error diagnostics if spans are stored for fields.
This approach ensures that the compiler correctly identifies invalid recursive types and provides clear feedback to the user.