From 0dc80bac01acc21e15e72cf4ac060efa8a61bb59 Mon Sep 17 00:00:00 2001 From: Amr Hesham Date: Sat, 8 Apr 2023 02:37:08 +0200 Subject: [PATCH] Explorer: Report compiletime error when global variable type is abstract (#2748) Add concrete type check for Variable Declaration to report a compile time error when the variable type is abstract Closes #2747 --- explorer/interpreter/type_checker.cpp | 17 +++++++++++++++++ .../fail_instantiate_global_abstract.carbon | 19 +++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 explorer/testdata/global_variable/fail_instantiate_global_abstract.carbon diff --git a/explorer/interpreter/type_checker.cpp b/explorer/interpreter/type_checker.cpp index a760d9cfc4ed..51969acc8c01 100644 --- a/explorer/interpreter/type_checker.cpp +++ b/explorer/interpreter/type_checker.cpp @@ -309,6 +309,21 @@ static auto ExpectCompleteType(SourceLocation source_loc, << "incomplete type `" << *type << "` used in " << context; } +// Expect that a type is concrete. Issue a diagnostic if not. +static auto ExpectConcreteType(SourceLocation source_loc, + Nonnull type) -> ErrorOr { + CARBON_CHECK(IsType(type)); + + if (const auto* dest_class = dyn_cast(type)) { + if (dest_class->declaration().extensibility() == + ClassExtensibility::Abstract) { + return ProgramError(source_loc) << "Cannot instantiate abstract class " + << dest_class->declaration().name(); + } + } + return Success(); +} + // Returns whether *value represents the type of a Carbon value, as // opposed to a type pattern or a non-type value. static auto TypeContainsAuto(Nonnull type) -> bool { @@ -6134,6 +6149,8 @@ auto TypeChecker::DeclareDeclaration(Nonnull d, var.expression_category())); CARBON_RETURN_IF_ERROR(ExpectCompleteType( var.source_loc(), "type of variable", &var.binding().static_type())); + CARBON_RETURN_IF_ERROR( + ExpectConcreteType(var.source_loc(), &var.binding().static_type())); var.set_static_type(&var.binding().static_type()); break; } diff --git a/explorer/testdata/global_variable/fail_instantiate_global_abstract.carbon b/explorer/testdata/global_variable/fail_instantiate_global_abstract.carbon new file mode 100644 index 000000000000..c10f031cebb2 --- /dev/null +++ b/explorer/testdata/global_variable/fail_instantiate_global_abstract.carbon @@ -0,0 +1,19 @@ +// 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; + +abstract class B { +} + +// CHECK:STDERR: COMPILATION ERROR: {{.*}}/explorer/testdata/global_variable/fail_instantiate_global_abstract.carbon:[[@LINE+1]]: Cannot instantiate abstract class B +var b: B = {}; + +fn Main() -> i32 { + return 0; +}