Debian Codegraph @

gcc/rust/typecheck/rust-autoderef.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-autoderef.h"
20 #include "rust-hir-path-probe.h"
21 #include "rust-hir-dot-operator.h"
22 #include "rust-hir-trait-resolve.h"
23 #include "rust-type-util.h"
24 #include "rust-substitution-mapper.h"
25
26 namespace Rust {
27 namespace Resolver {
28
29 static bool
30 resolve_operator_overload_fn (
31 LangItem::Kind lang_item_type, TyTy::BaseType *ty, TyTy::FnType **resolved_fn,
32 Adjustment::AdjustmentType *requires_ref_adjustment);
33
34 TyTy::BaseType *
35 Adjuster::adjust_type (const std::vector<Adjustment> &adjustments)
36 {
37 if (adjustments.size () == 0)
38 return base->clone ();
39
40 return adjustments.back ().get_expected ()->clone ();
41 }
42
43 Adjustment
44 Adjuster::try_deref_type (TyTy::BaseType *ty, LangItem::Kind deref_lang_item)
45 {
46 TyTy::FnType *fn = nullptr;
47 Adjustment::AdjustmentType requires_ref_adjustment
48 = Adjustment::AdjustmentType::ERROR;
49 bool operator_overloaded
50 = resolve_operator_overload_fn (deref_lang_item, ty, &fn,
51 &requires_ref_adjustment);
52 if (!operator_overloaded)
53 {
54 return Adjustment::get_error ();
55 }
56
57 auto resolved_base = fn->get_return_type ()->destructure ();
58 bool is_valid_type = resolved_base->get_kind () == TyTy::TypeKind::REF;
59 if (!is_valid_type)
60 return Adjustment::get_error ();
61
62 TyTy::ReferenceType *ref_base
63 = static_cast<TyTy::ReferenceType *> (resolved_base);
64
65 Adjustment::AdjustmentType adjustment_type
66 = Adjustment::AdjustmentType::ERROR;
67 switch (deref_lang_item)
68 {
69 case LangItem::Kind::DEREF:
70 adjustment_type = Adjustment::AdjustmentType::DEREF;
71 break;
72
73 case LangItem::Kind::DEREF_MUT:
74 adjustment_type = Adjustment::AdjustmentType::DEREF_MUT;
75 break;
76
77 default:
78 break;
79 }
80
81 return Adjustment::get_op_overload_deref_adjustment (adjustment_type, ty,
82 ref_base, fn,
83 requires_ref_adjustment);
84 }
85
86 Adjustment
87 Adjuster::try_raw_deref_type (TyTy::BaseType *ty)
88 {
89 bool is_valid_type = ty->get_kind () == TyTy::TypeKind::REF;
90 if (!is_valid_type)
91 return Adjustment::get_error ();
92
93 const TyTy::ReferenceType *ref_base
94 = static_cast<const TyTy::ReferenceType *> (ty);
95 auto infered = ref_base->get_base ()->destructure ();
96
97 return Adjustment (Adjustment::AdjustmentType::INDIRECTION, ty, infered);
98 }
99
100 Adjustment
101 Adjuster::try_unsize_type (TyTy::BaseType *ty)
102 {
103 bool is_valid_type = ty->get_kind () == TyTy::TypeKind::ARRAY;
104 if (!is_valid_type)
105 return Adjustment::get_error ();
106
107 auto &mappings = Analysis::Mappings::get ();
108 auto context = TypeCheckContext::get ();
109
110 const auto ref_base = static_cast<const TyTy::ArrayType *> (ty);
111 auto slice_elem = ref_base->get_element_type ();
112
113 auto slice
114 = new TyTy::SliceType (mappings.get_next_hir_id (), ty->get_ident ().locus,
115 TyTy::TyVar (slice_elem->get_ref ()));
116 context->insert_implicit_type (slice->get_ref (), slice);
117
118 return Adjustment (Adjustment::AdjustmentType::UNSIZE, ty, slice);
119 }
120
121 static bool
122 resolve_operator_overload_fn (
123 LangItem::Kind lang_item_type, TyTy::BaseType *lhs,
124 TyTy::FnType **resolved_fn,
125 Adjustment::AdjustmentType *requires_ref_adjustment)
126 {
127 auto context = TypeCheckContext::get ();
128 auto &mappings = Analysis::Mappings::get ();
129
130 // look up lang item for arithmetic type
131 std::string associated_item_name = LangItem::ToString (lang_item_type);
132 auto lang_item_defined = mappings.lookup_lang_item (lang_item_type);
133
134 if (!lang_item_defined)
135 return false;
136 DefId &respective_lang_item_id = lang_item_defined.value ();
137
138 // we might be in a static or const context and unknown is fine
139 TypeCheckContextItem current_context = TypeCheckContextItem::get_error ();
140 if (context->have_function_context ())
141 {
142 current_context = context->peek_context ();
143 }
144
145 // this flags stops recurisve calls to try and deref when none is available
146 // which will cause an infinite loop
147 bool autoderef_flag = true;
148 auto segment = HIR::PathIdentSegment (associated_item_name);
149 auto candidates = MethodResolver::Probe (lhs, segment, autoderef_flag);
150
151 // remove any recursive candidates
152 std::set<MethodCandidate> resolved_candidates;
153 for (auto &c : candidates)
154 {
155 const TyTy::BaseType *candidate_type = c.candidate.ty;
156 rust_assert (candidate_type->get_kind () == TyTy::TypeKind::FNDEF);
157
158 const TyTy::FnType &fn
159 = *static_cast<const TyTy::FnType *> (candidate_type);
160
161 DefId current_fn_defid = current_context.get_defid ();
162 bool recursive_candidated = fn.get_id () == current_fn_defid;
163 if (!recursive_candidated)
164 {
165 resolved_candidates.insert (c);
166 }
167 }
168
169 auto selected_candidates
170 = MethodResolver::Select (resolved_candidates, lhs, {});
171 bool have_implementation_for_lang_item = selected_candidates.size () > 0;
172 if (!have_implementation_for_lang_item)
173 return false;
174
175 if (selected_candidates.size () > 1)
176 {
177 // no need to error out as we are just trying to see if there is a fit
178 return false;
179 }
180
181 // Get the adjusted self
182 MethodCandidate candidate = *selected_candidates.begin ();
183 Adjuster adj (lhs);
184 TyTy::BaseType *adjusted_self = adj.adjust_type (candidate.adjustments);
185
186 PathProbeCandidate &resolved_candidate = candidate.candidate;
187 TyTy::BaseType *lookup_tyty = candidate.candidate.ty;
188 rust_assert (lookup_tyty->get_kind () == TyTy::TypeKind::FNDEF);
189 TyTy::BaseType *lookup = lookup_tyty;
190 TyTy::FnType *fn = static_cast<TyTy::FnType *> (lookup);
191 rust_assert (fn->is_method ());
192
193 rust_debug ("is_impl_item_candidate: %s",
194 resolved_candidate.is_impl_candidate () ? "true" : "false");
195
196 // in the case where we resolve to a trait bound we have to be careful we are
197 // able to do so there is a case where we are currently resolving the deref
198 // operator overload function which is generic and this might resolve to the
199 // trait item of deref which is not valid as its just another recursive case
200 if (current_context.get_type () == TypeCheckContextItem::ItemType::IMPL_ITEM)
201 {
202 auto &impl_item = current_context.get_impl_item ();
203 HIR::ImplBlock *parent = impl_item.first;
204 HIR::Function *fn = impl_item.second;
205
206 if (parent->has_trait_ref ()
207 && fn->get_function_name ().as_string ().compare (
208 associated_item_name)
209 == 0)
210 {
211 TraitReference *trait_reference
212 = TraitResolver::Lookup (parent->get_trait_ref ());
213 if (!trait_reference->is_error ())
214 {
215 TyTy::BaseType *lookup = nullptr;
216 bool ok = context->lookup_type (fn->get_mappings ().get_hirid (),
217 &lookup);
218 rust_assert (ok);
219 rust_assert (lookup->get_kind () == TyTy::TypeKind::FNDEF);
220
221 TyTy::FnType *fntype = static_cast<TyTy::FnType *> (lookup);
222 rust_assert (fntype->is_method ());
223
224 bool is_lang_item_impl
225 = trait_reference->get_mappings ().get_defid ()
226 == respective_lang_item_id;
227 bool self_is_lang_item_self
228 = fntype->get_self_type ()->is_equal (*adjusted_self);
229 bool recursive_operator_overload
230 = is_lang_item_impl && self_is_lang_item_self;
231
232 if (recursive_operator_overload)
233 return false;
234 }
235 }
236 }
237
238 // we found a valid operator overload
239 fn->prepare_higher_ranked_bounds ();
240 rust_debug ("resolved operator overload to: {%u} {%s}",
241 candidate.candidate.ty->get_ref (),
242 candidate.candidate.ty->debug_str ().c_str ());
243
244 if (fn->needs_substitution ())
245 {
246 if (lhs->get_kind () == TyTy::TypeKind::ADT)
247 {
248 const TyTy::ADTType *adt = static_cast<const TyTy::ADTType *> (lhs);
249
250 auto s = fn->get_self_type ()->get_root ();
251 rust_assert (s->can_eq (adt, false));
252 rust_assert (s->get_kind () == TyTy::TypeKind::ADT);
253 const TyTy::ADTType *self_adt
254 = static_cast<const TyTy::ADTType *> (s);
255
256 // we need to grab the Self substitutions as the inherit type
257 // parameters for this
258 if (self_adt->needs_substitution ())
259 {
260 rust_assert (adt->was_substituted ());
261
262 TyTy::SubstitutionArgumentMappings used_args_in_prev_segment
263 = GetUsedSubstArgs::From (adt);
264
265 TyTy::SubstitutionArgumentMappings inherit_type_args
266 = self_adt->solve_mappings_from_receiver_for_self (
267 used_args_in_prev_segment);
268
269 // there may or may not be inherited type arguments
270 if (!inherit_type_args.is_error ())
271 {
272 // need to apply the inherited type arguments to the
273 // function
274 lookup = fn->handle_substitions (inherit_type_args);
275 }
276 }
277 }
278 else
279 {
280 rust_assert (candidate.adjustments.size () < 2);
281
282 // lets infer the params for this we could probably fix this up by
283 // actually just performing a substitution of a single param but this
284 // seems more generic i think.
285 //
286 // this is the case where we had say Foo<&Bar>> and we have derefed to
287 // the &Bar and we are trying to match a method self of Bar which
288 // requires another deref which is matched to the deref trait impl of
289 // &&T so this requires another reference and deref call
290
291 lookup = fn->infer_substitions (UNDEF_LOCATION);
292 rust_assert (lookup->get_kind () == TyTy::TypeKind::FNDEF);
293 fn = static_cast<TyTy::FnType *> (lookup);
294
295 location_t unify_locus = mappings.lookup_location (lhs->get_ref ());
296 unify_site (lhs->get_ref (),
297 TyTy::TyWithLocation (fn->get_self_type ()),
298 TyTy::TyWithLocation (adjusted_self), unify_locus);
299
300 lookup = fn;
301 }
302 }
303
304 if (candidate.adjustments.size () > 0)
305 *requires_ref_adjustment = candidate.adjustments.at (0).get_type ();
306
307 *resolved_fn = static_cast<TyTy::FnType *> (lookup);
308
309 return true;
310 }
311
312 AutoderefCycle::AutoderefCycle (bool autoderef_flag)
313 : autoderef_flag (autoderef_flag)
314 {}
315
316 AutoderefCycle::~AutoderefCycle () {}
317
318 void
319 AutoderefCycle::try_hook (const TyTy::BaseType &)
320 {}
321
322 bool
323 AutoderefCycle::cycle (TyTy::BaseType *receiver)
324 {
325 TyTy::BaseType *r = receiver;
326 while (true)
327 {
328 rust_debug ("autoderef try 1: {%s}", r->debug_str ().c_str ());
329 if (try_autoderefed (r))
330 return true;
331
332 // 4. deref to to 1, if cannot deref then quit
333 if (autoderef_flag)
334 return false;
335
336 // try unsize
337 Adjustment unsize = Adjuster::try_unsize_type (r);
338 if (!unsize.is_error ())
339 {
340 adjustments.push_back (unsize);
341 auto unsize_r = unsize.get_expected ();
342
343 rust_debug ("autoderef try unsize: {%s}",
344 unsize_r->debug_str ().c_str ());
345 if (try_autoderefed (unsize_r))
346 return true;
347
348 adjustments.pop_back ();
349 }
350
351 bool is_ptr = receiver->get_kind () == TyTy::TypeKind::POINTER;
352 if (is_ptr)
353 {
354 // deref of raw pointers is unsafe
355 return false;
356 }
357
358 Adjustment deref = Adjuster::try_deref_type (r, LangItem::Kind::DEREF);
359 if (!deref.is_error ())
360 {
361 auto deref_r = deref.get_expected ();
362 adjustments.push_back (deref);
363
364 rust_debug ("autoderef try lang-item DEREF: {%s}",
365 deref_r->debug_str ().c_str ());
366 if (try_autoderefed (deref_r))
367 return true;
368
369 adjustments.pop_back ();
370 }
371
372 Adjustment deref_mut
373 = Adjuster::try_deref_type (r, LangItem::Kind::DEREF_MUT);
374 if (!deref_mut.is_error ())
375 {
376 auto deref_r = deref_mut.get_expected ();
377 adjustments.push_back (deref_mut);
378
379 rust_debug ("autoderef try lang-item DEREF_MUT: {%s}",
380 deref_r->debug_str ().c_str ());
381 if (try_autoderefed (deref_r))
382 return true;
383
384 adjustments.pop_back ();
385 }
386
387 if (!deref_mut.is_error ())
388 {
389 auto deref_r = deref_mut.get_expected ();
390 adjustments.push_back (deref_mut);
391 Adjustment raw_deref = Adjuster::try_raw_deref_type (deref_r);
392 adjustments.push_back (raw_deref);
393 deref_r = raw_deref.get_expected ();
394
395 if (try_autoderefed (deref_r))
396 return true;
397
398 adjustments.pop_back ();
399 adjustments.pop_back ();
400 }
401
402 if (!deref.is_error ())
403 {
404 r = deref.get_expected ();
405 adjustments.push_back (deref);
406 }
407 Adjustment raw_deref = Adjuster::try_raw_deref_type (r);
408 if (raw_deref.is_error ())
409 return false;
410
411 r = raw_deref.get_expected ();
412 adjustments.push_back (raw_deref);
413 }
414 return false;
415 }
416
417 bool
418 AutoderefCycle::try_autoderefed (TyTy::BaseType *r)
419 {
420 try_hook (*r);
421
422 // 1. try raw
423 if (select (*r))
424 return true;
425
426 // 2. try ref
427 TyTy::ReferenceType *r1
428 = new TyTy::ReferenceType (r->get_ref (), TyTy::TyVar (r->get_ref ()),
429 Mutability::Imm);
430 adjustments.push_back (
431 Adjustment (Adjustment::AdjustmentType::IMM_REF, r, r1));
432 if (select (*r1))
433 return true;
434
435 adjustments.pop_back ();
436
437 // 3. try mut ref
438 TyTy::ReferenceType *r2
439 = new TyTy::ReferenceType (r->get_ref (), TyTy::TyVar (r->get_ref ()),
440 Mutability::Mut);
441 adjustments.push_back (
442 Adjustment (Adjustment::AdjustmentType::MUT_REF, r, r2));
443 if (select (*r2))
444 return true;
445
446 adjustments.pop_back ();
447
448 return false;
449 }
450
451 } // namespace Resolver
452 } // namespace Rust