Add support for importing C++ namespaces (#5103)

This adds support for having different C++ `NameScope`s (and not just
the main `Cpp` scope), and we keep a pointer to `clang::DeclContext`
these scopes so we can look up C++ names in the right part of the AST.

C++ Interop Demo with a namespace:

```c++
// hello_world.h

namespace some_namespace {

void hello_world();

}  // namespace some_namespace
```

```c++
// hello_world.cpp

#include <cstdio>

namespace some_namespace {

void hello_world() { printf("Hello World!\n"); }

}  // namespace some_namespace
```

```carbon
// main.carbon

library "Main";

import Cpp library "hello_world.h";

fn Run() -> i32 {
  Cpp.some_namespace.hello_world();
  return 0;
}
```

```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
Hello World!
```

Closes #5102
This commit is contained in:
Boaz Brickner
2025-03-15 20:41:48 +00:00
committed by GitHub
parent fdedbb037d
commit fcd38a4d7f
15 changed files with 585 additions and 88 deletions
+7 -1
View File
@@ -663,7 +663,8 @@ class FormatterImpl {
const auto& scope = sem_ir_->name_scopes().Get(id);
if (scope.entries().empty() && scope.extended_scopes().empty() &&
scope.import_ir_scopes().empty() && !scope.has_error()) {
scope.import_ir_scopes().empty() && !scope.is_cpp_scope() &&
!scope.has_error()) {
// Name scope is empty.
return;
}
@@ -723,6 +724,11 @@ class FormatterImpl {
out_ << "import " << label << "\n";
}
if (scope.is_cpp_scope()) {
Indent();
out_ << "import Cpp//...\n";
}
if (scope.has_error()) {
Indent();
out_ << "has_error\n";