Debian Codegraph @

gcc/rust/checks/errors/rust-const-checker.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-const-checker.h"
20 #include "rust-hir.h"
21 #include "rust-hir-expr.h"
22 #include "rust-hir-stmt.h"
23 #include "rust-hir-item.h"
24 #include "rust-system.h"
25 #include "rust-immutable-name-resolution-context.h"
26
27 // for flag_name_resolution_2_0
28 #include "options.h"
29
30 namespace Rust {
31 namespace HIR {
32
33 ConstChecker::ConstChecker ()
34 : resolver (*Resolver::Resolver::get ()),
35 mappings (Analysis::Mappings::get ())
36 {}
37
38 void
39 ConstChecker::go (HIR::Crate &crate)
40 {
41 for (auto &item : crate.get_items ())
42 item->accept_vis (*this);
43 }
44
45 bool
46 ConstChecker::is_const_extern_fn (HIR::ExternalFunctionItem &fn)
47 {
48 // FIXME: Is it really how we want to handle `rustc_const_stable`
49 // and `rustc_const_unstable`?
50 // TODO: Add these attributes to the attribute check and handle
51 // `stable` and `unstable` as well
52 return std::any_of (
53 fn.get_outer_attrs ().begin (), fn.get_outer_attrs ().end (),
54 [] (const AST::Attribute &attr) {
55 // `starts_with` in C++11...
56 return attr.get_path ().as_string ().rfind ("rustc_const_", 0) == 0;
57 });
58 }
59
60 const char *
61 ConstChecker::ctx_to_str (ConstGenericCtx ctx)
62 {
63 switch (ctx)
64 {
65 case ConstGenericCtx::Function:
66 return "function";
67 case ConstGenericCtx::TypeAlias:
68 return "type alias";
69 case ConstGenericCtx::Struct:
70 return "struct";
71 case ConstGenericCtx::Enum:
72 return "enum";
73 case ConstGenericCtx::Union:
74 return "union";
75 case ConstGenericCtx::Trait:
76 return "trait";
77 case ConstGenericCtx::Impl:
78 return "impl";
79 default:
80 rust_unreachable ();
81 }
82 }
83
84 bool
85 ConstChecker::ctx_allows_default (ConstGenericCtx ctx)
86 {
87 switch (ctx)
88 {
89 case ConstGenericCtx::TypeAlias:
90 case ConstGenericCtx::Struct:
91 case ConstGenericCtx::Enum:
92 case ConstGenericCtx::Trait:
93 return true;
94 default:
95 return false;
96 }
97 }
98
99 void
100 ConstChecker::check_default_const_generics (
101 std::vector<std::unique_ptr<GenericParam>> &params, ConstGenericCtx context)
102 {
103 if (ctx_allows_default (context))
104 return;
105
106 for (auto &param : params)
107 {
108 if (param->get_kind () == GenericParam::GenericKind::CONST)
109 {
110 auto const_param = static_cast<ConstGenericParam *> (param.get ());
111 if (const_param->has_default_expression ())
112 rust_error_at (
113 param->get_locus (),
114 "default values for const generic parameters are not "
115 "allowed in %qs items",
116 ctx_to_str (context));
117 }
118 }
119 }
120
121 void
122 ConstChecker::visit (Lifetime &)
123 {}
124
125 void
126 ConstChecker::visit (LifetimeParam &)
127 {}
128
129 void
130 ConstChecker::visit (PathInExpression &)
131 {}
132
133 void
134 ConstChecker::visit (TypePathSegment &)
135 {}
136
137 void
138 ConstChecker::visit (TypePathSegmentGeneric &)
139 {}
140
141 void
142 ConstChecker::visit (TypePathSegmentFunction &)
143 {}
144
145 void
146 ConstChecker::visit (TypePath &)
147 {}
148
149 void
150 ConstChecker::visit (QualifiedPathInExpression &)
151 {}
152
153 void
154 ConstChecker::visit (QualifiedPathInType &)
155 {}
156
157 void
158 ConstChecker::visit (LiteralExpr &)
159 {}
160
161 void
162 ConstChecker::visit (BorrowExpr &expr)
163 {
164 expr.get_expr ().accept_vis (*this);
165 }
166
167 void
168 ConstChecker::visit (DereferenceExpr &expr)
169 {
170 expr.get_expr ().accept_vis (*this);
171 }
172
173 void
174 ConstChecker::visit (ErrorPropagationExpr &expr)
175 {
176 expr.get_expr ().accept_vis (*this);
177 }
178
179 void
180 ConstChecker::visit (NegationExpr &expr)
181 {
182 expr.get_expr ().accept_vis (*this);
183 }
184
185 void
186 ConstChecker::visit (ArithmeticOrLogicalExpr &expr)
187 {
188 expr.get_lhs ().accept_vis (*this);
189 expr.get_rhs ().accept_vis (*this);
190 }
191
192 void
193 ConstChecker::visit (ComparisonExpr &expr)
194 {
195 expr.get_lhs ().accept_vis (*this);
196 expr.get_rhs ().accept_vis (*this);
197 }
198
199 void
200 ConstChecker::visit (LazyBooleanExpr &expr)
201 {
202 expr.get_lhs ().accept_vis (*this);
203 expr.get_rhs ().accept_vis (*this);
204 }
205
206 void
207 ConstChecker::visit (TypeCastExpr &expr)
208 {
209 expr.get_expr ().accept_vis (*this);
210 }
211
212 void
213 ConstChecker::visit (AssignmentExpr &expr)
214 {
215 expr.get_lhs ().accept_vis (*this);
216 expr.get_rhs ().accept_vis (*this);
217 }
218
219 void
220 ConstChecker::visit (CompoundAssignmentExpr &expr)
221 {
222 expr.get_lhs ().accept_vis (*this);
223 expr.get_rhs ().accept_vis (*this);
224 }
225
226 void
227 ConstChecker::visit (GroupedExpr &expr)
228 {
229 expr.get_expr_in_parens ().accept_vis (*this);
230 }
231
232 void
233 ConstChecker::visit (ArrayElemsValues &elems)
234 {
235 for (auto &elem : elems.get_values ())
236 elem->accept_vis (*this);
237 }
238
239 void
240 ConstChecker::visit (ArrayElemsCopied &elems)
241 {
242 elems.get_elem_to_copy ().accept_vis (*this);
243
244 const_context.enter (elems.get_mappings ().get_hirid ());
245
246 elems.get_num_copies_expr ().accept_vis (*this);
247
248 const_context.exit ();
249 }
250
251 void
252 ConstChecker::visit (ArrayExpr &expr)
253 {
254 expr.get_internal_elements ().accept_vis (*this);
255 }
256
257 void
258 ConstChecker::visit (ArrayIndexExpr &expr)
259 {
260 expr.get_array_expr ().accept_vis (*this);
261 expr.get_index_expr ().accept_vis (*this);
262 }
263
264 void
265 ConstChecker::visit (TupleExpr &expr)
266 {
267 for (auto &elem : expr.get_tuple_elems ())
268 elem->accept_vis (*this);
269 }
270
271 void
272 ConstChecker::visit (TupleIndexExpr &expr)
273 {
274 expr.get_tuple_expr ().accept_vis (*this);
275 }
276
277 void
278 ConstChecker::visit (StructExprStruct &)
279 {}
280
281 void
282 ConstChecker::visit (StructExprFieldIdentifier &)
283 {}
284
285 void
286 ConstChecker::visit (StructExprFieldIdentifierValue &field)
287 {
288 field.get_value ().accept_vis (*this);
289 }
290
291 void
292 ConstChecker::visit (StructExprFieldIndexValue &field)
293 {
294 field.get_value ().accept_vis (*this);
295 }
296
297 void
298 ConstChecker::visit (StructExprStructFields &expr)
299 {
300 for (auto &field : expr.get_fields ())
301 field->accept_vis (*this);
302 }
303
304 void
305 ConstChecker::visit (StructExprStructBase &)
306 {}
307
308 void
309 ConstChecker::check_function_call (HirId fn_id, location_t locus)
310 {
311 if (!const_context.is_in_context ())
312 return;
313
314 auto maybe_fn = mappings.lookup_hir_item (fn_id);
315 if (maybe_fn
316 && maybe_fn.value ()->get_item_kind () != Item::ItemKind::Function)
317 return;
318
319 // There are const extern functions (intrinsics)
320 // TODO: Should we check the ABI is only "rust intrinsics"? Is that handled
321 // elsewhere?
322 auto maybe_extern_item = mappings.lookup_hir_extern_item (fn_id);
323 if (maybe_extern_item
324 && maybe_extern_item->first->get_extern_kind ()
325 != ExternalItem::ExternKind::Function)
326 return;
327
328 auto is_error = false;
329 if (maybe_fn)
330 {
331 auto fn = static_cast<Function *> (*maybe_fn);
332 if (!fn->get_qualifiers ().is_const ())
333 is_error = true;
334 }
335
336 if (maybe_extern_item)
337 {
338 {
339 auto fn
340 = static_cast<ExternalFunctionItem *> (maybe_extern_item->first);
341 if (!is_const_extern_fn (*fn))
342 is_error = true;
343 }
344 }
345
346 if (is_error)
347 rust_error_at (locus, ErrorCode::E0015,
348 "only functions marked as %<const%> are allowed to be "
349 "called from constant contexts");
350 }
351
352 void
353 ConstChecker::visit (CallExpr &expr)
354 {
355 if (!expr.has_fnexpr ())
356 return;
357
358 NodeId ast_node_id = expr.get_fnexpr ().get_mappings ().get_nodeid ();
359 NodeId ref_node_id;
360
361 if (flag_name_resolution_2_0)
362 {
363 auto &nr_ctx
364 = Resolver2_0::ImmutableNameResolutionContext::get ().resolver ();
365
366 if (auto id = nr_ctx.lookup (ast_node_id))
367 ref_node_id = *id;
368 else
369 return;
370 }
371 // We don't care about types here
372 else if (!resolver.lookup_resolved_name (ast_node_id, &ref_node_id))
373 return;
374
375 if (auto definition_id = mappings.lookup_node_to_hir (ref_node_id))
376 {
377 check_function_call (*definition_id, expr.get_locus ());
378
379 for (auto &arg : expr.get_arguments ())
380 arg->accept_vis (*this);
381 }
382 else
383 {
384 rust_unreachable ();
385 }
386 }
387
388 void
389 ConstChecker::visit (MethodCallExpr &expr)
390 {
391 expr.get_receiver ().accept_vis (*this);
392
393 for (auto &arg : expr.get_arguments ())
394 arg->accept_vis (*this);
395 }
396
397 void
398 ConstChecker::visit (FieldAccessExpr &expr)
399 {
400 expr.get_receiver_expr ().accept_vis (*this);
401 }
402
403 void
404 ConstChecker::visit (ClosureExpr &expr)
405 {
406 expr.get_expr ().accept_vis (*this);
407 }
408
409 void
410 ConstChecker::visit (BlockExpr &expr)
411 {
412 for (auto &stmt : expr.get_statements ())
413 stmt->accept_vis (*this);
414
415 if (expr.has_expr ())
416 expr.get_final_expr ().accept_vis (*this);
417 }
418
419 void
420 ConstChecker::visit (ContinueExpr &)
421 {}
422
423 void
424 ConstChecker::visit (BreakExpr &expr)
425 {
426 if (expr.has_break_expr ())
427 expr.get_expr ().accept_vis (*this);
428 }
429
430 void
431 ConstChecker::visit (RangeFromToExpr &expr)
432 {
433 expr.get_from_expr ().accept_vis (*this);
434 expr.get_to_expr ().accept_vis (*this);
435 }
436
437 void
438 ConstChecker::visit (RangeFromExpr &expr)
439 {
440 expr.get_from_expr ().accept_vis (*this);
441 }
442
443 void
444 ConstChecker::visit (RangeToExpr &expr)
445 {
446 expr.get_to_expr ().accept_vis (*this);
447 }
448
449 void
450 ConstChecker::visit (RangeFullExpr &)
451 {}
452
453 void
454 ConstChecker::visit (RangeFromToInclExpr &expr)
455 {
456 expr.get_from_expr ().accept_vis (*this);
457 expr.get_to_expr ().accept_vis (*this);
458 }
459
460 void
461 ConstChecker::visit (RangeToInclExpr &)
462 {
463 // FIXME: Visit to_expr
464 }
465
466 void
467 ConstChecker::visit (ReturnExpr &expr)
468 {
469 if (expr.has_return_expr ())
470 expr.get_expr ().accept_vis (*this);
471 }
472
473 void
474 ConstChecker::visit (UnsafeBlockExpr &expr)
475 {
476 expr.get_block_expr ().accept_vis (*this);
477 }
478
479 void
480 ConstChecker::visit (LoopExpr &expr)
481 {
482 expr.get_loop_block ().accept_vis (*this);
483 }
484
485 void
486 ConstChecker::visit (WhileLoopExpr &expr)
487 {
488 expr.get_predicate_expr ().accept_vis (*this);
489 expr.get_loop_block ().accept_vis (*this);
490 }
491
492 void
493 ConstChecker::visit (WhileLetLoopExpr &expr)
494 {
495 expr.get_cond ().accept_vis (*this);
496 expr.get_loop_block ().accept_vis (*this);
497 }
498
499 void
500 ConstChecker::visit (IfExpr &expr)
501 {
502 expr.get_if_condition ().accept_vis (*this);
503 expr.get_if_block ().accept_vis (*this);
504 }
505
506 void
507 ConstChecker::visit (IfExprConseqElse &expr)
508 {
509 expr.get_if_condition ().accept_vis (*this);
510 expr.get_if_block ().accept_vis (*this);
511 expr.get_else_block ().accept_vis (*this);
512 }
513
514 void
515 ConstChecker::visit (MatchExpr &expr)
516 {
517 expr.get_scrutinee_expr ().accept_vis (*this);
518
519 for (auto &match_arm : expr.get_match_cases ())
520 match_arm.get_expr ().accept_vis (*this);
521 }
522
523 void
524 ConstChecker::visit (AwaitExpr &)
525 {
526 // TODO: Visit expression
527 }
528
529 void
530 ConstChecker::visit (AsyncBlockExpr &)
531 {
532 // TODO: Visit block expression
533 }
534
535 void
536 ConstChecker::visit (InlineAsm &)
537 {}
538
539 void
540 ConstChecker::visit (TypeParam &)
541 {}
542
543 void
544 ConstChecker::visit (ConstGenericParam &)
545 {}
546
547 void
548 ConstChecker::visit (LifetimeWhereClauseItem &)
549 {}
550
551 void
552 ConstChecker::visit (TypeBoundWhereClauseItem &)
553 {}
554
555 void
556 ConstChecker::visit (Module &module)
557 {
558 for (auto &item : module.get_items ())
559 item->accept_vis (*this);
560 }
561
562 void
563 ConstChecker::visit (ExternCrate &)
564 {}
565
566 void
567 ConstChecker::visit (UseTreeGlob &)
568 {}
569
570 void
571 ConstChecker::visit (UseTreeList &)
572 {}
573
574 void
575 ConstChecker::visit (UseTreeRebind &)
576 {}
577
578 void
579 ConstChecker::visit (UseDeclaration &)
580 {}
581
582 void
583 ConstChecker::visit (Function &function)
584 {
585 auto const_fn = function.get_qualifiers ().is_const ();
586 if (const_fn)
587 const_context.enter (function.get_mappings ().get_hirid ());
588
589 check_default_const_generics (function.get_generic_params (),
590 ConstGenericCtx::Function);
591
592 for (auto &param : function.get_function_params ())
593 param.get_type ().accept_vis (*this);
594
595 function.get_definition ().accept_vis (*this);
596
597 if (const_fn)
598 const_context.exit ();
599 }
600
601 void
602 ConstChecker::visit (TypeAlias &type_alias)
603 {
604 check_default_const_generics (type_alias.get_generic_params (),
605 ConstGenericCtx::TypeAlias);
606 }
607
608 void
609 ConstChecker::visit (StructStruct &struct_item)
610 {
611 check_default_const_generics (struct_item.get_generic_params (),
612 ConstGenericCtx::Struct);
613 }
614
615 void
616 ConstChecker::visit (TupleStruct &tuple_struct)
617 {
618 check_default_const_generics (tuple_struct.get_generic_params (),
619 ConstGenericCtx::Struct);
620 }
621
622 void
623 ConstChecker::visit (EnumItem &)
624 {}
625
626 void
627 ConstChecker::visit (EnumItemTuple &)
628 {}
629
630 void
631 ConstChecker::visit (EnumItemStruct &)
632 {}
633
634 void
635 ConstChecker::visit (EnumItemDiscriminant &item)
636 {
637 const_context.enter (item.get_mappings ().get_hirid ());
638
639 item.get_discriminant_expression ().accept_vis (*this);
640
641 const_context.exit ();
642 }
643
644 void
645 ConstChecker::visit (Enum &enum_item)
646 {
647 check_default_const_generics (enum_item.get_generic_params (),
648 ConstGenericCtx::Enum);
649
650 for (auto &item : enum_item.get_variants ())
651 item->accept_vis (*this);
652 }
653
654 void
655 ConstChecker::visit (Union &union_item)
656 {
657 check_default_const_generics (union_item.get_generic_params (),
658 ConstGenericCtx::Union);
659 }
660
661 void
662 ConstChecker::visit (ConstantItem &const_item)
663 {
664 const_context.enter (const_item.get_mappings ().get_hirid ());
665
666 const_item.get_expr ().accept_vis (*this);
667
668 const_context.exit ();
669 }
670
671 void
672 ConstChecker::visit (StaticItem &static_item)
673 {
674 const_context.enter (static_item.get_mappings ().get_hirid ());
675
676 static_item.get_expr ().accept_vis (*this);
677
678 const_context.exit ();
679 }
680
681 void
682 ConstChecker::visit (TraitItemFunc &item)
683 {
684 if (item.has_definition ())
685 item.get_block_expr ().accept_vis (*this);
686 }
687
688 void
689 ConstChecker::visit (TraitItemConst &item)
690 {
691 if (item.has_expr ())
692 item.get_expr ().accept_vis (*this);
693 }
694
695 void
696 ConstChecker::visit (TraitItemType &)
697 {}
698
699 void
700 ConstChecker::visit (Trait &trait)
701 {
702 check_default_const_generics (trait.get_generic_params (),
703 ConstGenericCtx::Trait);
704
705 for (auto &item : trait.get_trait_items ())
706 item->accept_vis (*this);
707 }
708
709 void
710 ConstChecker::visit (ImplBlock &impl)
711 {
712 check_default_const_generics (impl.get_generic_params (),
713 ConstGenericCtx::Impl);
714
715 for (auto &item : impl.get_impl_items ())
716 item->accept_vis (*this);
717 }
718
719 void
720 ConstChecker::visit (ExternalStaticItem &)
721 {}
722
723 void
724 ConstChecker::visit (ExternalFunctionItem &)
725 {}
726
727 void
728 ConstChecker::visit (ExternalTypeItem &)
729 {}
730
731 void
732 ConstChecker::visit (ExternBlock &block)
733 {
734 // FIXME: Do we need to do this?
735 for (auto &item : block.get_extern_items ())
736 item->accept_vis (*this);
737 }
738
739 void
740 ConstChecker::visit (LiteralPattern &)
741 {}
742
743 void
744 ConstChecker::visit (IdentifierPattern &)
745 {}
746
747 void
748 ConstChecker::visit (WildcardPattern &)
749 {}
750
751 void
752 ConstChecker::visit (RangePatternBoundLiteral &)
753 {}
754
755 void
756 ConstChecker::visit (RangePatternBoundPath &)
757 {}
758
759 void
760 ConstChecker::visit (RangePatternBoundQualPath &)
761 {}
762
763 void
764 ConstChecker::visit (RangePattern &)
765 {}
766
767 void
768 ConstChecker::visit (ReferencePattern &)
769 {}
770
771 void
772 ConstChecker::visit (StructPatternFieldTuplePat &)
773 {}
774
775 void
776 ConstChecker::visit (StructPatternFieldIdentPat &)
777 {}
778
779 void
780 ConstChecker::visit (StructPatternFieldIdent &)
781 {}
782
783 void
784 ConstChecker::visit (StructPattern &)
785 {}
786
787 void
788 ConstChecker::visit (TupleStructItemsNoRange &)
789 {}
790
791 void
792 ConstChecker::visit (TupleStructItemsRange &)
793 {}
794
795 void
796 ConstChecker::visit (TupleStructPattern &)
797 {}
798
799 void
800 ConstChecker::visit (TuplePatternItemsMultiple &)
801 {}
802
803 void
804 ConstChecker::visit (TuplePatternItemsRanged &)
805 {}
806
807 void
808 ConstChecker::visit (TuplePattern &)
809 {}
810
811 void
812 ConstChecker::visit (SlicePattern &)
813 {}
814
815 void
816 ConstChecker::visit (AltPattern &)
817 {}
818
819 void
820 ConstChecker::visit (EmptyStmt &)
821 {}
822
823 void
824 ConstChecker::visit (LetStmt &stmt)
825 {
826 if (stmt.has_init_expr ())
827 stmt.get_init_expr ().accept_vis (*this);
828 }
829
830 void
831 ConstChecker::visit (ExprStmt &stmt)
832 {
833 stmt.get_expr ().accept_vis (*this);
834 }
835
836 void
837 ConstChecker::visit (TraitBound &)
838 {}
839
840 void
841 ConstChecker::visit (ImplTraitType &)
842 {}
843
844 void
845 ConstChecker::visit (TraitObjectType &)
846 {}
847
848 void
849 ConstChecker::visit (ParenthesisedType &)
850 {}
851
852 void
853 ConstChecker::visit (TupleType &)
854 {}
855
856 void
857 ConstChecker::visit (NeverType &)
858 {}
859
860 void
861 ConstChecker::visit (RawPointerType &)
862 {}
863
864 void
865 ConstChecker::visit (ReferenceType &type)
866 {
867 if (const_context.is_in_context () && type.is_mut ())
868 rust_error_at (type.get_locus (), ErrorCode::E0658,
869 "mutable references are not allowed in constant functions");
870 }
871
872 void
873 ConstChecker::visit (ArrayType &type)
874 {
875 const_context.enter (type.get_mappings ().get_hirid ());
876
877 type.get_size_expr ().accept_vis (*this);
878
879 const_context.exit ();
880 }
881
882 void
883 ConstChecker::visit (SliceType &)
884 {}
885
886 void
887 ConstChecker::visit (InferredType &)
888 {}
889
890 void
891 ConstChecker::visit (BareFunctionType &)
892 {}
893
894 } // namespace HIR
895 } // namespace Rust