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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
//! Struct instantiation field/mutability validation and lookup helpers.
use super::super::module_resolver::ModuleResolver;
use super::super::sem_type::SemType;
use super::super::SemanticAnalyzer;
use crate::ast::{Definition, Expr, File, Statement, StructDef};
use crate::error::CompilerError;
use crate::location::Span;
impl<R: ModuleResolver> SemanticAnalyzer<R> {
/// Validate struct field requirements: all required fields must be provided, no unknown fields
pub(super) fn validate_struct_fields(
&mut self,
struct_name: &str,
args: &[(crate::ast::Ident, Expr)],
span: Span,
file: &File,
) {
// Find the struct definition in current file or module cache.
// Clone the field name + declared type pairs so we can release the
// borrow on `self` before recursing into type inference calls below.
let (field_names, field_types, required_fields, generic_params) = {
if let Some(def) = self.find_struct_def_in_files(struct_name, file) {
let field_names: Vec<String> =
def.fields.iter().map(|f| f.name.name.clone()).collect();
let field_types: Vec<(String, String)> = def
.fields
.iter()
.map(|f| (f.name.name.clone(), Self::type_to_string(&f.ty)))
.collect();
let required_fields: Vec<String> = def
.fields
.iter()
.filter(|f| {
// Field is required if it has no inline default and is not optional
f.default.is_none() && !f.optional
})
.map(|f| f.name.name.clone())
.collect();
let generic_params: Vec<String> =
def.generics.iter().map(|g| g.name.name.clone()).collect();
(field_names, field_types, required_fields, generic_params)
} else {
return; // Struct not found, skip validation
}
};
// Check all provided regular fields exist and type-check each value.
for (arg_name, arg_value) in args {
if !field_names.contains(&arg_name.name) {
self.errors.push(CompilerError::UnknownField {
field: arg_name.name.clone(),
type_name: struct_name.to_string(),
span: arg_name.span,
});
continue;
}
let Some((_, declared)) = field_types.iter().find(|(n, _)| n == &arg_name.name) else {
continue;
};
// Skip the check if the declared type references a generic
// parameter of the struct — generic substitution is handled by
// the IR monomorphisation pass, not the string-level comparison
// here.
if generic_params.iter().any(|g| declared.contains(g)) {
continue;
}
let inferred_sem = self.infer_type_sem(arg_value, file);
let inferred = inferred_sem.display();
// nil is compatible with any optional type
let nil_to_optional = matches!(inferred_sem, SemType::Nil) && declared.ends_with('?');
// T is compatible with T? (implicit wrapping)
let inner_to_optional =
declared.ends_with('?') && declared.trim_end_matches('?') == inferred.as_str();
// declared can still be a string with "Unknown" in it (e.g. unresolved
// type annotation); preserve the legacy guard for that case.
let declared_indeterminate = declared.contains("Unknown");
if !nil_to_optional
&& !inner_to_optional
&& !inferred_sem.is_indeterminate()
&& !declared_indeterminate
&& !self.type_strings_compatible(declared, &inferred)
{
self.errors.push(CompilerError::TypeMismatch {
expected: declared.clone(),
found: inferred,
span: arg_value.span(),
});
}
}
// Check all required regular fields are provided
for field_name in required_fields {
if !args.iter().any(|(name, _)| name.name == field_name) {
self.errors.push(CompilerError::MissingField {
field: field_name,
type_name: struct_name.to_string(),
span,
});
}
}
}
/// Find a struct definition in the current file and module cache
pub(super) fn find_struct_def_in_files<'a>(
&'a self,
struct_name: &str,
current_file: &'a File,
) -> Option<&'a StructDef> {
// Search in current file
for statement in ¤t_file.statements {
if let Statement::Definition(def) = statement {
if let Definition::Struct(struct_def) = &**def {
if struct_def.name.name == struct_name {
return Some(struct_def);
}
}
}
}
// Search in module cache
for (file, _) in self.module_cache.values() {
for statement in &file.statements {
if let Statement::Definition(def) = statement {
if let Definition::Struct(struct_def) = &**def {
if struct_def.name.name == struct_name {
return Some(struct_def);
}
}
}
}
}
None
}
pub(super) fn validate_struct_mutability(
&mut self,
struct_name: &str,
args: &[(crate::ast::Ident, Expr)],
file: &File,
span: Span,
) {
// Collect closure-typed field names and mutability info from the struct def,
// dropping the borrow before mutating `self` for escape tracking.
let struct_info: Option<Vec<(String, bool, bool)>> = {
let mut found = None;
for statement in &file.statements {
if let Statement::Definition(def) = statement {
if let Definition::Struct(struct_def) = &**def {
if struct_def.name.name == struct_name {
let info: Vec<(String, bool, bool)> = struct_def
.fields
.iter()
.map(|f| {
(
f.name.name.clone(),
f.mutable,
matches!(f.ty, crate::ast::Type::Closure { .. }),
)
})
.collect();
found = Some(info);
break;
}
}
}
}
// Fall back to module cache if not found in current file.
if found.is_none() {
for (cached_file, _) in self.module_cache.values() {
for statement in &cached_file.statements {
if let Statement::Definition(def) = statement {
if let Definition::Struct(struct_def) = &**def {
if struct_def.name.name == struct_name {
let info: Vec<(String, bool, bool)> = struct_def
.fields
.iter()
.map(|f| {
(
f.name.name.clone(),
f.mutable,
matches!(f.ty, crate::ast::Type::Closure { .. }),
)
})
.collect();
found = Some(info);
break;
}
}
}
}
if found.is_some() {
break;
}
}
}
found
};
let Some(fields) = struct_info else {
return;
};
for (arg_name, arg_expr) in args {
let Some((_, field_mutable, field_is_closure)) =
fields.iter().find(|(n, _, _)| n == &arg_name.name)
else {
continue;
};
if *field_mutable && !self.is_expr_mutable(arg_expr, file) {
self.errors.push(CompilerError::MutabilityMismatch {
param: arg_name.name.clone(),
span,
});
}
// Escape analysis: a closure value stored in a struct field escapes
// with the struct — mark its captures as consumed.
if *field_is_closure {
self.escape_closure_value(arg_expr);
}
}
}
}