mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-09-24 19:30:12 +01:00
Fix crash when initializing class with omitted base class (#7740)
### Description When looking up default initializers for class elements in `ConvertStructToClass`, the compiler previously assumed that every member looked up from the class scope was a `FieldDecl` and called `GetAs<SemIR::FieldDecl>` directly. For a derived class with a base class, looking up `base` returns a `BaseDecl`, which caused a `CHECK` assertion failure when casting to `FieldDecl`. Use `TryGetAs<SemIR::FieldDecl>` instead so non-`FieldDecl` entries like `BaseDecl` are recognized as having no default initializer, cleanly diagnosing that the `base` field is missing. Fixes #7722 Assisted-by: Google Deepmind Antigravity
This commit is contained in:
@@ -920,8 +920,11 @@ static auto ConvertStructToClass(Context& context, SemIR::StructType src_type,
|
||||
dest_class_scope.GetEntry(*entry_id).result.target_inst_id();
|
||||
LoadImportRef(context, field_inst_id);
|
||||
field_inst_id = context.constant_values().GetConstantInstId(field_inst_id);
|
||||
auto field_decl = context.insts().GetAs<SemIR::FieldDecl>(field_inst_id);
|
||||
auto field = context.fields().Get(field_decl.field_id);
|
||||
auto field_decl = context.insts().TryGetAs<SemIR::FieldDecl>(field_inst_id);
|
||||
if (!field_decl) {
|
||||
return SemIR::InstId::None;
|
||||
}
|
||||
auto field = context.fields().Get(field_decl->field_id);
|
||||
if (!field.initializer_id.has_value()) {
|
||||
return SemIR::InstId::None;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// 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
|
||||
//
|
||||
// INCLUDE-FILE: toolchain/testing/testdata/min_prelude/convert.carbon
|
||||
//
|
||||
// AUTOUPDATE
|
||||
// TIP: To test this file alone, run:
|
||||
// TIP: bazel test //toolchain/testing:file_test --test_arg=--file_tests=toolchain/check/testdata/class/inheritance/fail_init_missing_base.carbon
|
||||
// TIP: To dump output, run:
|
||||
// TIP: bazel run //toolchain/testing:file_test -- --dump_output --file_tests=toolchain/check/testdata/class/inheritance/fail_init_missing_base.carbon
|
||||
|
||||
base class X {}
|
||||
|
||||
class Z {
|
||||
extend base: X;
|
||||
}
|
||||
|
||||
fn Run() {
|
||||
// CHECK:STDERR: fail_init_missing_base.carbon:[[@LINE+4]]:14: error: missing value for field `base` in struct initialization [StructInitMissingFieldInLiteral]
|
||||
// CHECK:STDERR: var _: Z = {};
|
||||
// CHECK:STDERR: ^~
|
||||
// CHECK:STDERR:
|
||||
var _: Z = {};
|
||||
}
|
||||
Reference in New Issue
Block a user