mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-10-05 22:02:55 +01:00
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:
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user