Debian Codegraph @

gcc/rust/typecheck/rust-hir-type-check-struct.cc

raw
1 // Copyright (C) 2020-2025 Free Software Foundation, Inc.
2
3 // This file is part of GCC.
4
5 // GCC is free software; you can redistribute it and/or modify it under
6 // the terms of the GNU General Public License as published by the Free
7 // Software Foundation; either version 3, or (at your option) any later
8 // version.
9
10 // GCC is distributed in the hope that it will be useful, but WITHOUT ANY
11 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 // for more details.
14
15 // You should have received a copy of the GNU General Public License
16 // along with GCC; see the file COPYING3. If not see
17 // <http://www.gnu.org/licenses/>.
18
19 #include "rust-hir-type-check.h"
20 #include "rust-hir-type-check-expr.h"
21 #include "rust-hir-type-check-struct-field.h"
22 #include "rust-type-util.h"
23
24 namespace Rust {
25 namespace Resolver {
26
27 TypeCheckStructExpr::TypeCheckStructExpr (HIR::Expr &e)
28 : TypeCheckBase (),
29 resolved (new TyTy::ErrorType (e.get_mappings ().get_hirid ())),
30 struct_path_resolved (nullptr),
31 variant (&TyTy::VariantDef::get_error_node ())
32 {}
33
34 TyTy::BaseType *
35 TypeCheckStructExpr::Resolve (HIR::StructExprStructFields &expr)
36 {
37 TypeCheckStructExpr resolver (expr);
38 resolver.resolve (expr);
39 return resolver.resolved;
40 }
41
42 void
43 TypeCheckStructExpr::resolve (HIR::StructExprStructFields &struct_expr)
44 {
45 TyTy::BaseType *struct_path_ty
46 = TypeCheckExpr::Resolve (struct_expr.get_struct_name ());
47 if (struct_path_ty->get_kind () != TyTy::TypeKind::ADT)
48 {
49 rust_error_at (struct_expr.get_struct_name ().get_locus (),
50 "expected an ADT type for constructor");
51 return;
52 }
53
54 struct_path_resolved = static_cast<TyTy::ADTType *> (struct_path_ty);
55 TyTy::ADTType *struct_def = struct_path_resolved;
56 if (struct_expr.has_struct_base ())
57 {
58 TyTy::BaseType *base_resolved
59 = TypeCheckExpr::Resolve (struct_expr.get_struct_base ().get_base ());
60 TyTy::BaseType *base_unify = unify_site (
61 struct_expr.get_struct_base ().get_base ().get_mappings ().get_hirid (),
62 TyTy::TyWithLocation (struct_path_resolved),
63 TyTy::TyWithLocation (base_resolved),
64 struct_expr.get_struct_base ().get_base ().get_locus ());
65
66 if (base_unify->get_kind () != struct_path_ty->get_kind ())
67 {
68 rust_fatal_error (
69 struct_expr.get_struct_base ().get_base ().get_locus (),
70 "incompatible types for base struct reference");
71 return;
72 }
73
74 struct_def = static_cast<TyTy::ADTType *> (base_unify);
75 }
76
77 // figure out the variant
78 if (struct_path_resolved->is_enum ())
79 {
80 // lookup variant id
81 HirId variant_id;
82 bool ok = context->lookup_variant_definition (
83 struct_expr.get_struct_name ().get_mappings ().get_hirid (),
84 &variant_id);
85 rust_assert (ok);
86
87 ok = struct_path_resolved->lookup_variant_by_id (variant_id, &variant);
88 rust_assert (ok);
89 }
90 else
91 {
92 rust_assert (struct_path_resolved->number_of_variants () == 1);
93 variant = struct_path_resolved->get_variants ().at (0);
94 }
95
96 std::vector<TyTy::StructFieldType *> infered_fields;
97 bool ok = true;
98
99 for (auto &field : struct_expr.get_fields ())
100 {
101 resolved_field_value_expr = nullptr;
102
103 switch (field->get_kind ())
104 {
105 case HIR::StructExprField::StructExprFieldKind::IDENTIFIER:
106 ok = visit (
107 static_cast<HIR::StructExprFieldIdentifier &> (*field.get ()));
108 break;
109
110 case HIR::StructExprField::StructExprFieldKind::IDENTIFIER_VALUE:
111 ok = visit (
112 static_cast<HIR::StructExprFieldIdentifierValue &> (*field.get ()));
113 break;
114
115 case HIR::StructExprField::StructExprFieldKind::INDEX_VALUE:
116 ok = visit (
117 static_cast<HIR::StructExprFieldIndexValue &> (*field.get ()));
118 break;
119 }
120
121 if (!ok)
122 {
123 return;
124 }
125
126 if (resolved_field_value_expr == nullptr)
127 {
128 rust_fatal_error (field->get_locus (),
129 "failed to resolve type for field");
130 ok = false;
131 break;
132 }
133
134 context->insert_type (field->get_mappings (), resolved_field_value_expr);
135 }
136
137 // something failed setting up the fields
138 if (!ok)
139 {
140 rust_error_at (struct_expr.get_locus (),
141 "constructor type resolution failure");
142 return;
143 }
144
145 // check the arguments are all assigned and fix up the ordering
146 std::vector<std::string> missing_field_names;
147 for (auto &field : variant->get_fields ())
148 {
149 auto it = fields_assigned.find (field->get_name ());
150 if (it == fields_assigned.end ())
151 {
152 missing_field_names.push_back (field->get_name ());
153 }
154 }
155 if (!missing_field_names.empty ())
156 {
157 if (struct_def->is_union ())
158 {
159 if (fields_assigned.size () != 1 || struct_expr.has_struct_base ())
160 {
161 rust_error_at (
162 struct_expr.get_locus (),
163 "union must have exactly one field variant assigned");
164 return;
165 }
166 }
167 else if (!struct_expr.has_struct_base ())
168 {
169 Error missing_fields_error
170 = make_missing_field_error (struct_expr.get_locus (),
171 missing_field_names,
172 struct_path_ty->get_name ());
173 // We might want to return or handle these in the future emit for now.
174 missing_fields_error.emit ();
175 return;
176 }
177 else
178 {
179 // we have a struct base to assign the missing fields from.
180 // the missing fields can be implicit FieldAccessExprs for the value
181 std::set<std::string> missing_fields;
182 for (auto &field : variant->get_fields ())
183 {
184 auto it = fields_assigned.find (field->get_name ());
185 if (it == fields_assigned.end ())
186 missing_fields.insert (field->get_name ());
187 }
188
189 // we can generate FieldAccessExpr or TupleAccessExpr for the
190 // values of the missing fields.
191 for (auto &missing : missing_fields)
192 {
193 HIR::Expr *receiver
194 = struct_expr.get_struct_base ().get_base ().clone_expr_impl ();
195
196 HIR::StructExprField *implicit_field = nullptr;
197
198 AST::AttrVec outer_attribs;
199 auto crate_num = mappings.get_current_crate ();
200 Analysis::NodeMapping mapping (crate_num,
201 struct_expr.get_struct_base ()
202 .get_base ()
203 .get_mappings ()
204 .get_nodeid (),
205 mappings.get_next_hir_id (
206 crate_num),
207 UNKNOWN_LOCAL_DEFID);
208
209 HIR::Expr *field_value = new HIR::FieldAccessExpr (
210 mapping, std::unique_ptr<HIR::Expr> (receiver), missing,
211 std::move (outer_attribs),
212 struct_expr.get_struct_base ().get_base ().get_locus ());
213
214 implicit_field = new HIR::StructExprFieldIdentifierValue (
215 mapping, missing, std::unique_ptr<HIR::Expr> (field_value),
216 struct_expr.get_struct_base ().get_base ().get_locus ());
217
218 size_t field_index;
219 bool ok = variant->lookup_field (missing, nullptr, &field_index);
220 rust_assert (ok);
221
222 adtFieldIndexToField[field_index] = implicit_field;
223 struct_expr.get_fields ().push_back (
224 std::unique_ptr<HIR::StructExprField> (implicit_field));
225 }
226 }
227 }
228
229 if (struct_def->is_union ())
230 {
231 // There is exactly one field in this constructor, we need to
232 // figure out the field index to make sure we initialize the
233 // right union field.
234 for (size_t i = 0; i < adtFieldIndexToField.size (); i++)
235 {
236 if (adtFieldIndexToField[i])
237 {
238 struct_expr.union_index = i;
239 break;
240 }
241 }
242 rust_assert (struct_expr.union_index != -1);
243 }
244 else
245 {
246 // everything is ok, now we need to ensure all field values are ordered
247 // correctly. The GIMPLE backend uses a simple algorithm that assumes each
248 // assigned field in the constructor is in the same order as the field in
249 // the type
250 for (auto &field : struct_expr.get_fields ())
251 field.release ();
252
253 std::vector<std::unique_ptr<HIR::StructExprField> > ordered_fields;
254 for (size_t i = 0; i < adtFieldIndexToField.size (); i++)
255 {
256 ordered_fields.push_back (
257 std::unique_ptr<HIR::StructExprField> (adtFieldIndexToField[i]));
258 }
259 struct_expr.set_fields_as_owner (std::move (ordered_fields));
260 }
261
262 resolved = struct_def;
263 }
264
265 bool
266 TypeCheckStructExpr::visit (HIR::StructExprFieldIdentifierValue &field)
267 {
268 size_t field_index;
269 TyTy::StructFieldType *field_type;
270 bool ok = variant->lookup_field (field.field_name.as_string (), &field_type,
271 &field_index);
272 if (!ok)
273 {
274 rust_error_at (field.get_locus (), "unknown field");
275 return true;
276 }
277
278 auto it = adtFieldIndexToField.find (field_index);
279 if (it != adtFieldIndexToField.end ())
280 {
281 rich_location repeat_location (line_table, field.get_locus ());
282 auto prev_field_locus = it->second->get_locus ();
283 repeat_location.add_range (prev_field_locus);
284
285 rust_error_at (repeat_location, ErrorCode::E0062,
286 "field %qs specified more than once",
287 field.field_name.as_string ().c_str ());
288 return false;
289 }
290
291 TyTy::BaseType *value = TypeCheckExpr::Resolve (field.get_value ());
292 location_t value_locus = field.get_value ().get_locus ();
293
294 HirId coercion_site_id = field.get_mappings ().get_hirid ();
295 resolved_field_value_expr
296 = coercion_site (coercion_site_id,
297 TyTy::TyWithLocation (field_type->get_field_type (),
298 field_type->get_locus ()),
299 TyTy::TyWithLocation (value, value_locus),
300 field.get_locus ());
301 if (resolved_field_value_expr != nullptr)
302 {
303 fields_assigned.insert (field.field_name.as_string ());
304 adtFieldIndexToField[field_index] = &field;
305 }
306
307 return true;
308 }
309
310 bool
311 TypeCheckStructExpr::visit (HIR::StructExprFieldIndexValue &field)
312 {
313 std::string field_name (std::to_string (field.get_tuple_index ()));
314
315 size_t field_index;
316 TyTy::StructFieldType *field_type;
317 bool ok = variant->lookup_field (field_name, &field_type, &field_index);
318 if (!ok)
319 {
320 rust_error_at (field.get_locus (), "unknown field");
321 return true;
322 }
323
324 auto it = adtFieldIndexToField.find (field_index);
325 if (it != adtFieldIndexToField.end ())
326 {
327 rich_location repeat_location (line_table, field.get_locus ());
328 auto prev_field_locus = it->second->get_locus ();
329 repeat_location.add_range (prev_field_locus);
330
331 rust_error_at (repeat_location, ErrorCode::E0062,
332 "field %qs specified more than once",
333 field_name.c_str ());
334 return false;
335 }
336
337 TyTy::BaseType *value = TypeCheckExpr::Resolve (field.get_value ());
338 location_t value_locus = field.get_value ().get_locus ();
339
340 HirId coercion_site_id = field.get_mappings ().get_hirid ();
341 resolved_field_value_expr
342 = coercion_site (coercion_site_id,
343 TyTy::TyWithLocation (field_type->get_field_type (),
344 field_type->get_locus ()),
345 TyTy::TyWithLocation (value, value_locus),
346 field.get_locus ());
347 if (resolved_field_value_expr != nullptr)
348 {
349 fields_assigned.insert (field_name);
350 adtFieldIndexToField[field_index] = &field;
351 }
352
353 return true;
354 }
355
356 bool
357 TypeCheckStructExpr::visit (HIR::StructExprFieldIdentifier &field)
358 {
359 size_t field_index;
360 TyTy::StructFieldType *field_type;
361 bool ok = variant->lookup_field (field.get_field_name ().as_string (),
362 &field_type, &field_index);
363 if (!ok)
364 {
365 rust_error_at (field.get_locus (), "unknown field");
366 return true;
367 }
368
369 auto it = adtFieldIndexToField.find (field_index);
370 if (it != adtFieldIndexToField.end ())
371 {
372 rich_location repeat_location (line_table, field.get_locus ());
373 auto prev_field_locus = it->second->get_locus ();
374 repeat_location.add_range (prev_field_locus);
375
376 rust_error_at (repeat_location, ErrorCode::E0062,
377 "field %qs specified more than once",
378 field.get_field_name ().as_string ().c_str ());
379 return false;
380 }
381
382 // we can make the field look like a path expr to take advantage of existing
383 // code
384 Analysis::NodeMapping mappings_copy1 = field.get_mappings ();
385 Analysis::NodeMapping mappings_copy2 = field.get_mappings ();
386
387 HIR::PathIdentSegment ident_seg (field.get_field_name ().as_string ());
388 HIR::PathExprSegment seg (mappings_copy1, ident_seg, field.get_locus (),
389 HIR::GenericArgs::create_empty ());
390 HIR::PathInExpression expr (mappings_copy2, {seg}, field.get_locus (), false,
391 {});
392 TyTy::BaseType *value = TypeCheckExpr::Resolve (expr);
393 location_t value_locus = expr.get_locus ();
394
395 HirId coercion_site_id = field.get_mappings ().get_hirid ();
396 resolved_field_value_expr
397 = coercion_site (coercion_site_id,
398 TyTy::TyWithLocation (field_type->get_field_type (),
399 field_type->get_locus ()),
400 TyTy::TyWithLocation (value, value_locus),
401 field.get_locus ());
402 if (resolved_field_value_expr != nullptr)
403
404 {
405 fields_assigned.insert (field.get_field_name ().as_string ());
406 adtFieldIndexToField[field_index] = &field;
407 }
408
409 return true;
410 }
411
412 Error
413 TypeCheckStructExpr::make_missing_field_error (
414 location_t locus, const std::vector<std::string> &missing_field_names,
415 const std::string &struct_name)
416 {
417 // Message plurality depends on size
418 if (missing_field_names.size () == 1)
419 {
420 return Error (locus, ErrorCode::E0063,
421 "missing field %s in initializer of %qs",
422 missing_field_names[0].c_str (), struct_name.c_str ());
423 }
424 // Make comma separated string for display
425 std::stringstream display_field_names;
426 bool first = true;
427 for (auto &name : missing_field_names)
428 {
429 if (!first)
430 {
431 display_field_names << ", ";
432 }
433 first = false;
434 display_field_names << name;
435 }
436 return Error (locus, ErrorCode::E0063,
437 "missing fields %s in initializer of %qs",
438 display_field_names.str ().c_str (), struct_name.c_str ());
439 }
440
441 } // namespace Resolver
442 } // namespace Rust