Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Structs: Fields check #1907

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 12 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
4 changes: 1 addition & 3 deletions ast/src/analyzed/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,7 @@ impl<T: Display> Display for Analyzed<T> {
if matches!(
definition,
Some(FunctionValueDefinition::TypeConstructor(_, _))
) || matches!(
definition,
Some(FunctionValueDefinition::TraitFunction(_, _))
| Some(FunctionValueDefinition::TraitFunction(_, _))
) {
// These are printed as part of the enum / trait.
continue;
Expand Down
28 changes: 25 additions & 3 deletions pil-analyzer/src/expression_processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ use powdr_ast::{
parsed::{
self, asm::SymbolPath, types::Type, ArrayExpression, ArrayLiteral, BinaryOperation,
BlockExpression, IfExpression, LambdaExpression, LetStatementInsideBlock, MatchArm,
MatchExpression, NamespacedPolynomialReference, Number, Pattern, SelectedExpressions,
StatementInsideBlock, SymbolCategory, UnaryOperation,
MatchExpression, NamedExpression, NamespacedPolynomialReference, Number, Pattern,
SelectedExpressions, StatementInsideBlock, StructExpression, SymbolCategory,
UnaryOperation,
},
};

Expand Down Expand Up @@ -189,7 +190,28 @@ impl<'a, D: AnalysisDriver> ExpressionProcessor<'a, D> {
self.process_block_expression(statements, expr, src)
}
PExpression::FreeInput(_, _) => panic!(),
PExpression::StructExpression(_, _) => unimplemented!("Structs are not supported yet"),
PExpression::StructExpression(src, StructExpression { name, fields }) => {
let type_args = name
.type_args
.map(|args| args.into_iter().map(|t| self.process_type(t)).collect());

Expression::StructExpression(
src,
StructExpression {
name: Reference::Poly(PolynomialReference {
name: self.driver.resolve_type_ref(&name.path),
type_args,
}),
fields: fields
.into_iter()
.map(|named_expr| NamedExpression {
name: named_expr.name,
body: Box::new(self.process_expression(*named_expr.body)),
})
.collect(),
},
)
}
}
}

Expand Down
147 changes: 144 additions & 3 deletions pil-analyzer/src/pil_analyzer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,14 @@ use powdr_ast::parsed::asm::{
use powdr_ast::parsed::types::Type;
use powdr_ast::parsed::visitor::{AllChildren, Children};
use powdr_ast::parsed::{
self, FunctionKind, LambdaExpression, PILFile, PilStatement, SymbolCategory,
TraitImplementation,
self, FunctionKind, LambdaExpression, PILFile, PilStatement, StructExpression, SymbolCategory,
TraitImplementation, TypeDeclaration, TypedExpression,
};
use powdr_number::{FieldElement, GoldilocksField};

use powdr_ast::analyzed::{
type_from_definition, Analyzed, DegreeRange, Expression, FunctionValueDefinition,
PolynomialType, PublicDeclaration, Reference, StatementIdentifier, Symbol, SymbolKind,
TypedExpression,
};
use powdr_parser::{parse, parse_module, parse_type};
use powdr_parser_util::Error;
Expand Down Expand Up @@ -56,6 +55,7 @@ fn analyze<T: FieldElement>(files: Vec<PILFile>) -> Result<Analyzed<T>, Vec<Erro
let mut analyzer = PILAnalyzer::new();
analyzer.process(files)?;
analyzer.side_effect_check()?;
analyzer.struct_fields_check()?;
analyzer.type_check()?;
let solved_impls = analyzer.resolve_trait_impls()?;
analyzer.condense(solved_impls)
Expand Down Expand Up @@ -257,6 +257,113 @@ impl PILAnalyzer {
}
}

/// Verifies that all struct instantiations match their corresponding declarations (existence of field names, completeness)
fn struct_fields_check(&self) -> Result<(), Vec<Error>> {
let mut errors = Vec::new();
let mut visited_structs = HashSet::new();

let structs_exprs = self.all_children().filter_map(|expr| {
gzanitti marked this conversation as resolved.
Show resolved Hide resolved
if let Expression::StructExpression(
sr,
StructExpression {
name: Reference::Poly(poly),
fields,
},
) = expr
{
Some((sr, poly.name.clone(), fields))
gzanitti marked this conversation as resolved.
Show resolved Hide resolved
} else {
None
}
});

for (sr, name, fields) in structs_exprs {
if let Some((
_,
Some(FunctionValueDefinition::TypeDeclaration(TypeDeclaration::Struct(
struct_decl,
))),
)) = self.definitions.get(&name)
{
let declared_fields: HashSet<_> =
struct_decl.fields.iter().map(|f| &f.name).collect();
let used_fields: HashSet<_> = fields.iter().map(|f| &f.name).collect();

errors.extend(
fields
.iter()
.filter(|f| !declared_fields.contains(&f.name))
.map(|f| {
sr.with_error(format!(
"Struct '{name}' has no field named '{}'",
f.name
))
}),
);

errors.extend(declared_fields.difference(&used_fields).map(|&f| {
sr.with_error(format!("Missing field '{f}' in initializer of '{name}'",))
}));

let duplicate_fields: Vec<_> =
fields.iter().map(|f| &f.name).duplicates().collect();

errors.extend(
duplicate_fields
.into_iter()
.map(|f| sr.with_error(format!("Field '{f}' specified more than once"))),
);
} else {
errors.push(sr.with_error(format!("Struct '{name}' has not been declared")));
gzanitti marked this conversation as resolved.
Show resolved Hide resolved
}

visited_structs.insert(name);
}

let structs_decls = self.definitions.iter().filter(|(_, (_, def))| {
matches!(
def,
Some(FunctionValueDefinition::TypeDeclaration(
TypeDeclaration::Struct(_)
))
)
});

for (name, (symbol, def)) in structs_decls {
if !visited_structs.contains(name) {
errors.push(
symbol
.source
.with_error(format!("warning: struct '{name}' is never constructed")), // TODO: Warningx
gzanitti marked this conversation as resolved.
Show resolved Hide resolved
);
} else if let Some(FunctionValueDefinition::TypeDeclaration(TypeDeclaration::Struct(
struct_decl,
))) = def
{
let duplicate_declaration_fields: Vec<_> = struct_decl
.fields
.iter()
.map(|f| &f.name)
.duplicates()
.collect();

errors.extend(duplicate_declaration_fields.into_iter().map(|f| {
symbol
.source
.with_error(format!("Field '{f}' is already declared",))
gzanitti marked this conversation as resolved.
Show resolved Hide resolved
}));
} else {
unreachable!()
}
}

if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}

pub fn type_check(&mut self) -> Result<(), Vec<Error>> {
let query_type: Type = parse_type("int -> std::prelude::Query").unwrap().into();
let mut expressions = vec![];
Expand Down Expand Up @@ -542,6 +649,40 @@ impl PILAnalyzer {
}
}

impl Children<Expression> for PILAnalyzer {
fn children(&self) -> Box<dyn Iterator<Item = &Expression> + '_> {
Box::new(
self.definitions
.values()
.filter_map(|(_, def)| def.as_ref())
.flat_map(|def| def.children())
.chain(
self.trait_impls
.values()
.flat_map(|impls| impls.iter())
.flat_map(|impl_| impl_.children()),
)
.chain(self.proof_items.iter()),
)
chriseth marked this conversation as resolved.
Show resolved Hide resolved
}

fn children_mut(&mut self) -> Box<dyn Iterator<Item = &mut Expression> + '_> {
Box::new(
self.definitions
.values_mut()
.filter_map(|(_, def)| def.as_mut())
.flat_map(|def| def.children_mut())
.chain(
self.trait_impls
.values_mut()
.flat_map(|impls| impls.iter_mut())
.flat_map(|impl_| impl_.children_mut()),
)
.chain(self.proof_items.iter_mut()),
)
}
}

#[derive(Clone, Copy)]
struct Driver<'a>(&'a PILAnalyzer);

Expand Down
84 changes: 84 additions & 0 deletions pil-analyzer/tests/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -761,3 +761,87 @@ fn prover_functions() {
";
type_check(input, &[("a", "", "int"), ("b", "", "()[]")]);
}

gzanitti marked this conversation as resolved.
Show resolved Hide resolved
#[test]
#[should_panic = "Type symbol not found: NotADot"]
fn wrong_struct() {
let input = "
struct Dot { x: int, y: int }
let f: int -> Dot = |i| NotADot{x: 0, y: i};
";
type_check(input, &[]);
}

#[test]
#[should_panic = "Struct 'Dot' has no field named 'a'"]
fn struct_wrong_fields() {
let input = "
struct Dot { x: int, y: int }
let f: int -> Dot = |i| Dot{x: 0, y: i, a: 2};
let x = f(0);
";
type_check(input, &[]);
}

#[test]
#[should_panic = "Missing field 'z' in initializer of 'A'"]
fn test_struct_unused_fields() {
let input = " struct A {
x: int,
y: int,
z: int,
}
let x = A{ y: 0, x: 2 };
";

type_check(input, &[]);
}

#[test]
#[should_panic = "Field 'y' specified more than once"]
fn test_struct_repeated_fields_expr() {
let input = " struct A {
x: int,
y: int,
}
let x = A{ y: 0, x: 2, y: 1 };
";

type_check(input, &[]);
}

#[test]
#[should_panic = "Field 'x' is already declared"]
gzanitti marked this conversation as resolved.
Show resolved Hide resolved
fn test_struct_repeated_fields_decl() {
let input = " struct A {
x: int,
y: int,
x: int,
}
let x = A{ y: 0, x: 2 };
";

type_check(input, &[]);
}

#[test]
#[should_panic(expected = "Struct 'A' has not been declared")]
fn enum_used_as_struct() {
let input = "
enum A { X }
let a = A{x: 8};
";
type_check(input, &[]);
}

#[test]
#[should_panic(expected = "warning: struct 'A' is never constructed")] // warning
fn struct_never_constructed() {
let input = "
struct A {
x: int,
y: int,
}
";
type_check(input, &[]);
}