Преглед изворни кода

Fix explorer crash - Assign different struct types (#2345)

* fix issue-1392

* run pre-commit

* run pre-commit

* Update explorer/interpreter/type_checker.cpp

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>

* change test file

* change test file

* remove size check

* Update explorer/interpreter/type_checker.cpp

Co-authored-by: Jon Ross-Perkins <jperkins@google.com>

Co-authored-by: m new <michael.burzan@outlook.de>
Co-authored-by: Jon Ross-Perkins <jperkins@google.com>
pmqtt пре 3 година
родитељ
комит
c68cced1fb

+ 7 - 2
explorer/interpreter/type_checker.cpp

@@ -353,8 +353,13 @@ auto TypeChecker::FieldTypesImplicitlyConvertible(
     llvm::ArrayRef<NamedValue> source_fields,
     llvm::ArrayRef<NamedValue> destination_fields,
     const ImplScope& impl_scope) const -> bool {
-  if (source_fields.size() != destination_fields.size()) {
-    return false;
+  // TODO: If default fields are implemented, the
+  // code must be adapted to skip them.
+  // Ensure every field name exists in the destination.
+  for (const auto& dest_field : destination_fields) {
+    if (!FindField(source_fields, dest_field.name)) {
+      return false;
+    }
   }
   for (const auto& source_field : source_fields) {
     std::optional<NamedValue> destination_field =

+ 16 - 0
explorer/testdata/struct/fail_assign_different_types.carbon

@@ -0,0 +1,16 @@
+// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
+// Exceptions. See /LICENSE for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+// AUTOUPDATE
+// RUN: %{not} %{explorer-run}
+// RUN: %{not} %{explorer-run-trace}
+
+package ExplorerTest api;
+
+fn Main() -> i32 {
+  var p: auto = {.x = 0, .y = 0};
+  // CHECK:STDERR: COMPILATION ERROR: {{.*}}/explorer/testdata/struct/fail_assign_different_types.carbon:[[@LINE+1]]: type error in assignment: '{.y: i32}' is not implicitly convertible to '{.x: i32, .y: i32}'
+  p = {.y = 0};
+  return 0;
+}