[Carbon/C++ interop] Add support for C++ type short (#5393)

Added support for `short`/`int16_t`. Both function parameters and return
values this type will be supported.

Demo:

```c++
// hello_short.h

#include <cstdint>
auto foo_short(int16_t a) -> int16_t;
```

```c++
// hello_short.cpp

#include "hello_short.h"
#include <cstdio>

auto foo_short(int16_t a) -> int16_t {
    printf("a = %i \n", a);
    return a;
}
```

```c++
// main.carbon

library "Main";

import Cpp library "hello_short.h";
import Core library "io";

fn Run() -> i32 {
  var a: i16 = 3;
  Cpp.foo_short(a);
  return 0;
}
```

```
$ clang -c hello_short.cpp
$ bazel-bin/toolchain/carbon compile main.carbon
$ bazel-bin/toolchain/carbon link hello_short.o main.o --output=demo
$ ./demo
a = 3 
```

Part of #5263
This commit is contained in:
Ivana Ivanovska
2025-05-09 08:51:46 +00:00
committed by GitHub
parent 71715263ce
commit f8443ae09e
2 changed files with 1664 additions and 4 deletions
+19 -4
View File
@@ -310,13 +310,28 @@ static auto MakeIntType(Context& context, IntId size_id) -> TypeExpr {
return ExprAsType(context, Parse::NodeId::None, type_inst_id);
}
// Maps a C++ type to a Carbon type. Currently only 32-bit `int` is supported.
// Maps a C++ type to a Carbon type.
// TODO: Support more types.
static auto MapType(Context& context, clang::QualType type) -> TypeExpr {
const auto* builtin_type = dyn_cast<clang::BuiltinType>(type);
if (builtin_type && builtin_type->getKind() == clang::BuiltinType::Int &&
context.ast_context().getTypeSize(type) == 32) {
return MakeIntType(context, context.ints().Add(32));
if (!builtin_type) {
return {.inst_id = SemIR::ErrorInst::TypeInstId,
.type_id = SemIR::ErrorInst::TypeId};
}
// TODO: Refactor to avoid duplication.
switch (builtin_type->getKind()) {
case clang::BuiltinType::Short:
if (context.ast_context().getTypeSize(type) == 16) {
return MakeIntType(context, context.ints().Add(16));
}
break;
case clang::BuiltinType::Int:
if (context.ast_context().getTypeSize(type) == 32) {
return MakeIntType(context, context.ints().Add(32));
}
break;
default:
break;
}
return {.inst_id = SemIR::ErrorInst::TypeInstId,
.type_id = SemIR::ErrorInst::TypeId};