Add support for using C++ bool type in imported function declarations. (#5860)

C++ in

C++ Interop Demo:

```c++
// hello_world.h

auto hello_world(bool x) -> bool;
```

```c++
// hello_world.cpp

#include "hello_world.h"

#include <cstdio>

auto hello_world(bool x) -> bool {
  printf("bool: %d\n", x);
  return !x;
}
```

```carbon
// main.carbon

library "Main";

import Cpp library "hello_world.h";

fn Run() -> i32 {
  let x: bool = Cpp.hello_world(false);
  if (x) {
    return 0;
  } else {
    return 1;
  }
}
```

```shell
$ clang -c hello_world.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link hello_world.o main.o --output=demo
$ ./demo
bool: 0
```

Before this change (bool is interpreted as a 1 bit integer):
```shell
$ bazel-bin/toolchain/carbon compile main.carbon
... CRASH! ...
clang/include/clang/AST/Type.h:952: const ExtQualsTypeCommonBase *clang::QualType::getCommonPtr() const: Assertion `!isNull() && "Cannot retrieve a NULL type pointer"' failed.
```

Part of #5263.
This commit is contained in:
Boaz Brickner
2025-07-29 06:56:45 +00:00
committed by GitHub
parent 432ee89dda
commit 6d6e0d0418
2 changed files with 165 additions and 5 deletions
+10 -4
View File
@@ -752,12 +752,18 @@ static auto MakeIntType(Context& context, IntId size_id, bool is_signed)
// TODO: Support more builtin types.
static auto MapBuiltinType(Context& context, clang::QualType qual_type,
const clang::BuiltinType& type) -> TypeExpr {
clang::ASTContext& ast_context = context.ast_context();
if (type.isBooleanType()) {
CARBON_CHECK(ast_context.hasSameType(qual_type, ast_context.BoolTy));
return ExprAsType(context, Parse::NodeId::None,
context.types().GetInstId(GetSingletonType(
context, SemIR::BoolType::TypeInstId)));
}
if (type.isInteger()) {
auto width = context.ast_context().getIntWidth(qual_type);
auto width = ast_context.getIntWidth(qual_type);
bool is_signed = type.isSignedInteger();
auto int_n_type =
context.ast_context().getIntTypeForBitwidth(width, is_signed);
if (context.ast_context().hasSameType(qual_type, int_n_type)) {
auto int_n_type = ast_context.getIntTypeForBitwidth(width, is_signed);
if (ast_context.hasSameType(qual_type, int_n_type)) {
return MakeIntType(context, context.ints().Add(width), is_signed);
}
// TODO: Handle integer types that map to named aliases.