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