1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
//! Validate derive-declared field obligations after source type resolution.
use super::*;
use crate::ast::EnumVariant;
pub(super) fn analyze(
program: &Program,
module: &[String],
resolver: &crate::semantic::DeclarationTypeResolver,
) -> Vec<AnalysisDiagnostic> {
fn visit(
statements: &[Stmt],
module: &[String],
resolver: &crate::semantic::DeclarationTypeResolver,
diagnostics: &mut Vec<AnalysisDiagnostic>,
) {
for statement in statements {
let (name, attributes, parameters, fields) = match statement {
Stmt::Struct {
name,
attributes,
generic_parameters,
fields,
..
} => (
name,
attributes,
generic_parameters,
fields
.iter()
.map(|field| (&field.type_annotation, field.span))
.collect::<Vec<_>>(),
),
Stmt::Enum {
name,
attributes,
generic_parameters,
variants,
..
} => (
name,
attributes,
generic_parameters,
variants
.iter()
.flat_map(|variant| match variant {
EnumVariant::Unit { .. } => Vec::new(),
EnumVariant::Tuple { fields, span, .. } => {
fields.iter().map(|field| (field, *span)).collect()
}
EnumVariant::Record { fields, .. } => fields
.iter()
.map(|field| (&field.type_annotation, field.span))
.collect(),
})
.collect(),
),
Stmt::Module {
name,
statements: Some(children),
..
} => {
let mut child = module.to_vec();
child.push(name.clone());
visit(children, &child, resolver, diagnostics);
continue;
}
_ => continue,
};
for derive in rils_builtins::NATIVE_DERIVES {
if !attributes.iter().any(|attribute| {
attribute.path == ["derive"]
&& attribute.arguments.iter().any(|arg| arg == &[derive.name])
}) {
continue;
}
// Derived implementations add the declared field obligations to
// their type parameters. Check fields under those same bounds;
// concrete instantiations still go through the obligation solver.
let assumptions = parameters
.iter()
.map(|parameter| {
let mut bounds = parameter.bounds.clone();
bounds.extend(derive.field_traits.iter().map(|bound| Type::named(*bound)));
(
parameter.name.clone(),
Type::BoundVariable {
name: parameter.name.clone(),
bounds,
},
)
})
.collect();
for (field, span) in &fields {
let field = resolver.resolve(&field.substitute(&assumptions), module);
for required in derive.field_traits {
let required = resolver.resolve_canonical(&Type::named(*required));
if resolver.trait_obligation(&field, &required)
!= crate::semantic::TraitObligation::Satisfied
{
diagnostics.push(AnalysisDiagnostic::error(
format!("cannot derive {} for `{name}`: field type `{field}` does not implement `{required}`", derive.name),
*span,
));
}
}
}
}
}
}
let mut diagnostics = Vec::new();
visit(&program.statements, module, resolver, &mut diagnostics);
diagnostics
}