Factor out common pattern of trying to complete a type then falling back to an error type if that fails. (#3454)

As requested in [review of
#3450](https://github.com/carbon-language/carbon-lang/pull/3450#discussion_r1414220143).
This commit is contained in:
Richard Smith
2023-12-07 01:53:30 +00:00
committed by GitHub
parent fe6f7b4330
commit 18d7ba9542
4 changed files with 48 additions and 45 deletions
+18 -22
View File
@@ -67,18 +67,16 @@ auto HandleBindingPattern(Context& context, Parse::NodeId parse_node) -> bool {
case Parse::NodeKind::VariableIntroducer: {
// A `var` declaration at class scope introduces a field.
auto enclosing_class_decl = context.GetCurrentScopeAs<SemIR::ClassDecl>();
if (!context.TryToCompleteType(cast_type_id, [&] {
CARBON_DIAGNOSTIC(IncompleteTypeInVarDecl, Error,
"{0} has incomplete type `{1}`.",
llvm::StringLiteral, std::string);
return context.emitter().Build(
type_node_copy, IncompleteTypeInVarDecl,
enclosing_class_decl ? llvm::StringLiteral("Field")
: llvm::StringLiteral("Variable"),
context.sem_ir().StringifyType(cast_type_id));
})) {
cast_type_id = SemIR::TypeId::Error;
}
cast_type_id = context.AsCompleteType(cast_type_id, [&] {
CARBON_DIAGNOSTIC(IncompleteTypeInVarDecl, Error,
"{0} has incomplete type `{1}`.", llvm::StringLiteral,
std::string);
return context.emitter().Build(
type_node_copy, IncompleteTypeInVarDecl,
enclosing_class_decl ? llvm::StringLiteral("Field")
: llvm::StringLiteral("Variable"),
context.sem_ir().StringifyType(cast_type_id));
});
SemIR::InstId value_id = SemIR::InstId::Invalid;
SemIR::TypeId value_type_id = cast_type_id;
if (context_parse_node_kind == Parse::NodeKind::ReturnedModifier) {
@@ -126,16 +124,14 @@ auto HandleBindingPattern(Context& context, Parse::NodeId parse_node) -> bool {
break;
case Parse::NodeKind::LetIntroducer:
if (!context.TryToCompleteType(cast_type_id, [&] {
CARBON_DIAGNOSTIC(IncompleteTypeInLetDecl, Error,
"`let` binding has incomplete type `{0}`.",
std::string);
return context.emitter().Build(
type_node_copy, IncompleteTypeInLetDecl,
context.sem_ir().StringifyType(cast_type_id));
})) {
cast_type_id = SemIR::TypeId::Error;
}
cast_type_id = context.AsCompleteType(cast_type_id, [&] {
CARBON_DIAGNOSTIC(IncompleteTypeInLetDecl, Error,
"`let` binding has incomplete type `{0}`.",
std::string);
return context.emitter().Build(
type_node_copy, IncompleteTypeInLetDecl,
context.sem_ir().StringifyType(cast_type_id));
});
// Create the instruction, but don't add it to a block until after we've
// formed its initializer.
// TODO: For general pattern parsing, we'll need to create a block to hold