generate_ast.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/check/cpp/generate_ast.h"
  5. #include <memory>
  6. #include <string>
  7. #include "clang/AST/ASTContext.h"
  8. #include "clang/AST/Decl.h"
  9. #include "clang/Basic/FileManager.h"
  10. #include "clang/CodeGen/ModuleBuilder.h"
  11. #include "clang/Frontend/CompilerInstance.h"
  12. #include "clang/Frontend/CompilerInvocation.h"
  13. #include "clang/Frontend/FrontendAction.h"
  14. #include "clang/Frontend/TextDiagnostic.h"
  15. #include "clang/Lex/PreprocessorOptions.h"
  16. #include "clang/Parse/Parser.h"
  17. #include "clang/Sema/ExternalSemaSource.h"
  18. #include "clang/Sema/MultiplexExternalSemaSource.h"
  19. #include "clang/Sema/Sema.h"
  20. #include "common/check.h"
  21. #include "common/map.h"
  22. #include "common/raw_string_ostream.h"
  23. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include "toolchain/base/kind_switch.h"
  27. #include "toolchain/check/context.h"
  28. #include "toolchain/check/cpp/export.h"
  29. #include "toolchain/check/cpp/import.h"
  30. #include "toolchain/check/import_ref.h"
  31. #include "toolchain/check/name_lookup.h"
  32. #include "toolchain/diagnostics/diagnostic.h"
  33. #include "toolchain/diagnostics/emitter.h"
  34. #include "toolchain/diagnostics/format_providers.h"
  35. #include "toolchain/parse/node_ids.h"
  36. #include "toolchain/sem_ir/cpp_file.h"
  37. namespace Carbon::Check {
  38. // Add a line marker directive pointing at the location of the `import Cpp`
  39. // declaration in the Carbon source file. This will cause Clang's diagnostics
  40. // machinery to track and report the location in Carbon code where the import
  41. // was written.
  42. static auto GenerateLineMarker(Context& context, llvm::raw_ostream& out,
  43. int line) {
  44. out << "# " << line << " \""
  45. << FormatEscaped(context.tokens().source().filename()) << "\"\n";
  46. }
  47. // Appends a line marker and the specified `code` to `out`, adjusting the
  48. // `line` number if the `code_token` represents a block string literal.
  49. static auto AppendInlineCode(Context& context, llvm::raw_ostream& out,
  50. Lex::TokenIndex code_token, llvm::StringRef code)
  51. -> void {
  52. // Compute the line number on which the C++ code starts. Usually the code
  53. // is specified as a block string literal and starts on the line after the
  54. // start of the string token.
  55. // TODO: Determine if this is a block string literal without calling
  56. // `GetTokenText`, which re-lexes the string.
  57. int line = context.tokens().GetLineNumber(code_token);
  58. if (context.tokens().GetTokenText(code_token).contains('\n')) {
  59. ++line;
  60. }
  61. GenerateLineMarker(context, out, line);
  62. out << code << "\n";
  63. }
  64. // Generates C++ file contents to #include all requested imports.
  65. static auto GenerateCppIncludesHeaderCode(
  66. Context& context, llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  67. -> std::string {
  68. RawStringOstream code_stream;
  69. for (const Parse::Tree::PackagingNames& import : imports) {
  70. if (import.inline_body_id.has_value()) {
  71. // Expand `import Cpp inline "code";` directly into the specified code.
  72. auto code_token = context.parse_tree().node_token(import.inline_body_id);
  73. AppendInlineCode(context, code_stream, code_token,
  74. context.string_literal_values().Get(
  75. context.tokens().GetStringLiteralValue(code_token)));
  76. // TODO: Inject a clang pragma here to produce an error if there are
  77. // unclosed scopes at the end of this inline C++ fragment.
  78. } else if (import.library_id.has_value()) {
  79. // Translate `import Cpp library "foo.h";` into `#include "foo.h"`.
  80. GenerateLineMarker(context, code_stream,
  81. context.tokens().GetLineNumber(
  82. context.parse_tree().node_token(import.node_id)));
  83. auto name = context.string_literal_values().Get(import.library_id);
  84. if (name.starts_with('<') && name.ends_with('>')) {
  85. code_stream << "#include <"
  86. << FormatEscaped(name.drop_front().drop_back()) << ">\n";
  87. } else {
  88. code_stream << "#include \"" << FormatEscaped(name) << "\"\n";
  89. }
  90. }
  91. }
  92. return code_stream.TakeStr();
  93. }
  94. // Adds the given source location and an `ImportIRInst` referring to it in
  95. // `ImportIRId::Cpp`.
  96. static auto AddImportIRInst(SemIR::File& file,
  97. clang::SourceLocation clang_source_loc)
  98. -> SemIR::ImportIRInstId {
  99. SemIR::ClangSourceLocId clang_source_loc_id =
  100. file.clang_source_locs().Add(clang_source_loc);
  101. return file.import_ir_insts().Add(SemIR::ImportIRInst(clang_source_loc_id));
  102. }
  103. namespace {
  104. // Used to convert Clang diagnostics to Carbon diagnostics.
  105. //
  106. // Handling of Clang notes is a little subtle: as far as Clang is concerned,
  107. // notes are separate diagnostics, not connected to the error or warning that
  108. // precedes them. But in Carbon's diagnostics system, notes are part of the
  109. // enclosing diagnostic. To handle this, we buffer Clang diagnostics until we
  110. // reach a point where we know we're not in the middle of a diagnostic, and then
  111. // emit a diagnostic along with all of its notes. This is triggered when adding
  112. // or removing a Carbon context note, which could otherwise get attached to the
  113. // wrong C++ diagnostics, and at the end of the Carbon program.
  114. class CarbonClangDiagnosticConsumer : public clang::DiagnosticConsumer {
  115. public:
  116. // Creates an instance with the location that triggers calling Clang. The
  117. // `context` is not stored here, and the diagnostics consumer is expected to
  118. // outlive it.
  119. explicit CarbonClangDiagnosticConsumer(
  120. Context& context, std::shared_ptr<clang::CompilerInvocation> invocation)
  121. : sem_ir_(&context.sem_ir()),
  122. emitter_(&context.emitter()),
  123. invocation_(std::move(invocation)) {
  124. emitter_->AddFlushFn([this] { EmitDiagnostics(); });
  125. }
  126. ~CarbonClangDiagnosticConsumer() override {
  127. // Do not inspect `emitter_` here; it's typically destroyed before the
  128. // consumer is.
  129. // TODO: If Clang produces diagnostics after check finishes, they'll get
  130. // added to the list of pending diagnostics and never emitted.
  131. CARBON_CHECK(diagnostic_infos_.empty(),
  132. "Missing flush before destroying diagnostic consumer");
  133. }
  134. // Generates a Carbon warning for each Clang warning and a Carbon error for
  135. // each Clang error or fatal.
  136. auto HandleDiagnostic(clang::DiagnosticsEngine::Level diag_level,
  137. const clang::Diagnostic& info) -> void override {
  138. DiagnosticConsumer::HandleDiagnostic(diag_level, info);
  139. SemIR::ImportIRInstId clang_import_ir_inst_id =
  140. AddImportIRInst(*sem_ir_, info.getLocation());
  141. llvm::SmallString<256> message;
  142. info.FormatDiagnostic(message);
  143. // Render a code snippet including any highlighted ranges and fixit hints.
  144. // TODO: Also include the #include stack and macro expansion stack in the
  145. // diagnostic output in some way.
  146. RawStringOstream snippet_stream;
  147. if (!info.hasSourceManager()) {
  148. // If we don't have a source manager, this is an error from early in the
  149. // frontend. Don't produce a snippet.
  150. CARBON_CHECK(info.getLocation().isInvalid());
  151. } else {
  152. CodeContextRenderer(snippet_stream, invocation_->getLangOpts(),
  153. invocation_->getDiagnosticOpts())
  154. .emitDiagnostic(
  155. clang::FullSourceLoc(info.getLocation(), info.getSourceManager()),
  156. diag_level, message, info.getRanges(), info.getFixItHints());
  157. }
  158. diagnostic_infos_.push_back({.level = diag_level,
  159. .import_ir_inst_id = clang_import_ir_inst_id,
  160. .message = message.str().str(),
  161. .snippet = snippet_stream.TakeStr()});
  162. }
  163. // Returns the diagnostic to use for a given Clang diagnostic level.
  164. static auto GetDiagnostic(clang::DiagnosticsEngine::Level level)
  165. -> const Diagnostics::DiagnosticBase<std::string>& {
  166. switch (level) {
  167. case clang::DiagnosticsEngine::Ignored: {
  168. CARBON_FATAL("Emitting an ignored diagnostic");
  169. break;
  170. }
  171. case clang::DiagnosticsEngine::Note: {
  172. CARBON_DIAGNOSTIC(CppInteropParseNote, Note, "{0}", std::string);
  173. return CppInteropParseNote;
  174. }
  175. case clang::DiagnosticsEngine::Remark:
  176. case clang::DiagnosticsEngine::Warning: {
  177. // TODO: Add a distinct Remark level to Carbon diagnostics, and stop
  178. // mapping remarks to warnings.
  179. CARBON_DIAGNOSTIC(CppInteropParseWarning, Warning, "{0}", std::string);
  180. return CppInteropParseWarning;
  181. }
  182. case clang::DiagnosticsEngine::Error:
  183. case clang::DiagnosticsEngine::Fatal: {
  184. CARBON_DIAGNOSTIC(CppInteropParseError, Error, "{0}", std::string);
  185. return CppInteropParseError;
  186. }
  187. }
  188. }
  189. // Outputs Carbon diagnostics based on the collected Clang diagnostics. Must
  190. // be called after the AST is set in the context.
  191. auto EmitDiagnostics() -> void {
  192. CARBON_CHECK(
  193. sem_ir_->cpp_file(),
  194. "Attempted to emit C++ diagnostics before the C++ file is set");
  195. for (size_t i = 0; i != diagnostic_infos_.size(); ++i) {
  196. const ClangDiagnosticInfo& info = diagnostic_infos_[i];
  197. auto builder = emitter_->Build(SemIR::LocId(info.import_ir_inst_id),
  198. GetDiagnostic(info.level), info.message);
  199. builder.OverrideSnippet(info.snippet);
  200. for (; i + 1 < diagnostic_infos_.size() &&
  201. diagnostic_infos_[i + 1].level == clang::DiagnosticsEngine::Note;
  202. ++i) {
  203. const ClangDiagnosticInfo& note_info = diagnostic_infos_[i + 1];
  204. builder
  205. .Note(SemIR::LocId(note_info.import_ir_inst_id),
  206. GetDiagnostic(note_info.level), note_info.message)
  207. .OverrideSnippet(note_info.snippet);
  208. }
  209. // TODO: This will apply all current Carbon annotation functions. We
  210. // should instead track how Clang's context notes and Carbon's annotation
  211. // functions are interleaved, and interleave the notes in the same order.
  212. builder.Emit();
  213. }
  214. diagnostic_infos_.clear();
  215. }
  216. private:
  217. // A diagnostics renderer based on clang's TextDiagnostic that captures just
  218. // the code context (the snippet).
  219. class CodeContextRenderer : public clang::TextDiagnostic {
  220. protected:
  221. using TextDiagnostic::TextDiagnostic;
  222. void emitDiagnosticMessage(
  223. clang::FullSourceLoc /*loc*/, clang::PresumedLoc /*ploc*/,
  224. clang::DiagnosticsEngine::Level /*level*/, llvm::StringRef /*message*/,
  225. llvm::ArrayRef<clang::CharSourceRange> /*ranges*/,
  226. clang::DiagOrStoredDiag /*info*/) override {}
  227. void emitDiagnosticLoc(
  228. clang::FullSourceLoc /*loc*/, clang::PresumedLoc /*ploc*/,
  229. clang::DiagnosticsEngine::Level /*level*/,
  230. llvm::ArrayRef<clang::CharSourceRange> /*ranges*/) override {}
  231. // emitCodeContext is inherited from clang::TextDiagnostic.
  232. void emitIncludeLocation(clang::FullSourceLoc /*loc*/,
  233. clang::PresumedLoc /*ploc*/) override {}
  234. void emitImportLocation(clang::FullSourceLoc /*loc*/,
  235. clang::PresumedLoc /*ploc*/,
  236. llvm::StringRef /*module_name*/) override {}
  237. void emitBuildingModuleLocation(clang::FullSourceLoc /*loc*/,
  238. clang::PresumedLoc /*ploc*/,
  239. llvm::StringRef /*module_name*/) override {}
  240. // beginDiagnostic and endDiagnostic are inherited from
  241. // clang::TextDiagnostic in case it wants to do any setup / teardown work.
  242. };
  243. // Information on a Clang diagnostic that can be converted to a Carbon
  244. // diagnostic.
  245. struct ClangDiagnosticInfo {
  246. // The Clang diagnostic level.
  247. clang::DiagnosticsEngine::Level level;
  248. // The ID of the ImportIR instruction referring to the Clang source
  249. // location.
  250. SemIR::ImportIRInstId import_ir_inst_id;
  251. // The Clang diagnostic textual message.
  252. std::string message;
  253. // The code snippet produced by clang.
  254. std::string snippet;
  255. };
  256. // The Carbon file that this C++ compilation is attached to.
  257. SemIR::File* sem_ir_;
  258. // The diagnostic emitter that we're emitting diagnostics into.
  259. DiagnosticEmitterBase* emitter_;
  260. // The compiler invocation that is producing the diagnostics.
  261. std::shared_ptr<clang::CompilerInvocation> invocation_;
  262. // Collects the information for all Clang diagnostics to be converted to
  263. // Carbon diagnostics after the context has been initialized with the Clang
  264. // AST.
  265. llvm::SmallVector<ClangDiagnosticInfo> diagnostic_infos_;
  266. };
  267. // A wrapper around a clang::CompilerInvocation that allows us to make a shallow
  268. // copy of most of the invocation and only make a deep copy of the parts that we
  269. // want to change.
  270. //
  271. // clang::CowCompilerInvocation almost allows this, but doesn't derive from
  272. // CompilerInvocation or support shallow copies from a CompilerInvocation, so is
  273. // not useful to us as we can't build an ASTUnit from it.
  274. class ShallowCopyCompilerInvocation : public clang::CompilerInvocation {
  275. public:
  276. explicit ShallowCopyCompilerInvocation(
  277. const clang::CompilerInvocation& invocation) {
  278. shallow_copy_assign(invocation);
  279. // Make a deep copy of options that we modify.
  280. FrontendOpts = std::make_shared<clang::FrontendOptions>(*FrontendOpts);
  281. PPOpts = std::make_shared<clang::PreprocessorOptions>(*PPOpts);
  282. }
  283. };
  284. // Provides clang AST nodes representing Carbon SemIR entities.
  285. class CarbonExternalASTSource : public clang::ExternalASTSource {
  286. public:
  287. explicit CarbonExternalASTSource(Context* context,
  288. clang::ASTContext* ast_context)
  289. : context_(context), ast_context_(ast_context) {}
  290. // Look up decls for `decl_name` inside `decl_context`, adding the decls to
  291. // `decl_context`. Returns true if any decls were added.
  292. auto FindExternalVisibleDeclsByName(
  293. const clang::DeclContext* decl_context, clang::DeclarationName decl_name,
  294. const clang::DeclContext* original_decl_context) -> bool override;
  295. // See clang::ExternalASTSource.
  296. auto StartTranslationUnit(clang::ASTConsumer* consumer) -> void override;
  297. private:
  298. // Map a Carbon entity to a Clang NamedDecl. Returns null if the entity cannot
  299. // currently be represented in C++.
  300. auto MapInstIdToClangDecl(clang::DeclContext& decl_context,
  301. LookupResult lookup) -> clang::NamedDecl*;
  302. Check::Context* context_;
  303. clang::ASTContext* ast_context_;
  304. // Has the "Carbon" C++ namespace been created yet
  305. // (this could be replaced with `!scope_map_.empty()` if Carbon::Map supported
  306. // `empty()`)
  307. bool root_scope_initialized_ = false;
  308. };
  309. } // namespace
  310. void CarbonExternalASTSource::StartTranslationUnit(
  311. clang::ASTConsumer* /*Consumer*/) {
  312. auto& translation_unit = *ast_context_->getTranslationUnitDecl();
  313. // Mark the translation unit as having external storage so we get a query for
  314. // the `Carbon` namespace in the top level/translation unit scope.
  315. translation_unit.setHasExternalVisibleStorage();
  316. }
  317. // If the given name scope was produced by importing a C++ declaration, return
  318. // the corresponding Clang declaration.
  319. static auto GetClangDeclForScope(Context& context, SemIR::NameScopeId scope_id)
  320. -> clang::NamedDecl* {
  321. if (!scope_id.has_value()) {
  322. return nullptr;
  323. }
  324. auto& scope = context.name_scopes().Get(scope_id);
  325. if (!scope.is_cpp_scope()) {
  326. return nullptr;
  327. }
  328. return dyn_cast<clang::NamedDecl>(
  329. context.clang_decls().Get(scope.clang_decl_context_id()).key.decl);
  330. }
  331. auto CarbonExternalASTSource::MapInstIdToClangDecl(
  332. clang::DeclContext& decl_context, LookupResult lookup)
  333. -> clang::NamedDecl* {
  334. auto target_inst_id = lookup.scope_result.target_inst_id();
  335. auto target_constant =
  336. context_->constant_values().GetConstantInstId(target_inst_id);
  337. auto target_inst = context_->insts().Get(target_constant);
  338. CARBON_KIND_SWITCH(target_inst) {
  339. case CARBON_KIND(SemIR::Namespace namespace_info): {
  340. if (auto* decl =
  341. GetClangDeclForScope(*context_, namespace_info.name_scope_id)) {
  342. return decl;
  343. }
  344. auto& name_scope =
  345. context_->name_scopes().Get(namespace_info.name_scope_id);
  346. auto* identifier_info =
  347. GetClangIdentifierInfo(*context_, name_scope.name_id());
  348. if (!identifier_info) {
  349. // TODO: Handle keyword package names like `Cpp` and `Core`. These can
  350. // be named from C++ via an alias.
  351. context_->TODO(SemIR::LocId(target_inst_id),
  352. "interop with non-identifier package name");
  353. return nullptr;
  354. }
  355. // TODO: Don't immediately use the decl_context - build any intermediate
  356. // namespaces iteratively.
  357. // Eventually add a mapping and use that/populate it/keep it up to date.
  358. // decl_context could be prepopulated in that mapping and not passed
  359. // explicitly to MapInstIdToClangDecl.
  360. auto* namespace_decl = clang::NamespaceDecl::Create(
  361. *ast_context_, &decl_context, false, clang::SourceLocation(),
  362. clang::SourceLocation(), identifier_info, nullptr, false);
  363. auto key = SemIR::ClangDeclKey::ForNonFunctionDecl(namespace_decl);
  364. context_->clang_decls().Add({.key = key, .inst_id = target_inst_id});
  365. namespace_decl->setHasExternalVisibleStorage();
  366. return namespace_decl;
  367. }
  368. case CARBON_KIND(SemIR::ClassType class_type): {
  369. const auto& class_info = context_->classes().Get(class_type.class_id);
  370. if (auto* decl = GetClangDeclForScope(*context_, class_info.scope_id)) {
  371. return decl;
  372. }
  373. auto* identifier_info =
  374. GetClangIdentifierInfo(*context_, class_info.name_id);
  375. CARBON_CHECK(identifier_info, "class with non-identifier name {0}",
  376. class_info.name_id);
  377. auto* record_decl = clang::CXXRecordDecl::Create(
  378. *ast_context_, clang::TagTypeKind::Class, &decl_context,
  379. clang::SourceLocation(), clang::SourceLocation(), identifier_info);
  380. auto key = SemIR::ClangDeclKey::ForNonFunctionDecl(record_decl);
  381. context_->clang_decls().Add({.key = key, .inst_id = target_inst_id});
  382. return record_decl;
  383. }
  384. case SemIR::StructValue::Kind: {
  385. auto callee = GetCallee(context_->sem_ir(), target_constant);
  386. auto* callee_function = std::get_if<SemIR::CalleeFunction>(&callee);
  387. if (!callee_function) {
  388. return nullptr;
  389. }
  390. const SemIR::Function& function =
  391. context_->functions().Get(callee_function->function_id);
  392. if (function.clang_decl_id.has_value()) {
  393. return cast<clang::NamedDecl>(
  394. context_->clang_decls().Get(function.clang_decl_id).key.decl);
  395. }
  396. return GetReverseInteropFunctionDecl(
  397. *context_, SemIR::LocId(target_inst_id), decl_context,
  398. callee_function->function_id);
  399. }
  400. default:
  401. return nullptr;
  402. }
  403. }
  404. auto CarbonExternalASTSource::FindExternalVisibleDeclsByName(
  405. const clang::DeclContext* decl_context, clang::DeclarationName decl_name,
  406. const clang::DeclContext* /*OriginalDC*/) -> bool {
  407. if (decl_context->getDeclKind() == clang::Decl::Kind::TranslationUnit) {
  408. // If the context doesn't already have a mapping between C++ and Carbon,
  409. // check if this is the root mapping (for the "Carbon" namespace in the
  410. // translation unit scope) and if so, create that mapping.
  411. if (root_scope_initialized_) {
  412. return false;
  413. }
  414. static const llvm::StringLiteral carbon_namespace_name = "Carbon";
  415. if (auto* identifier = decl_name.getAsIdentifierInfo();
  416. !identifier || !identifier->isStr(carbon_namespace_name)) {
  417. return false;
  418. }
  419. // Build the top level 'Carbon' namespace
  420. auto& ast_context = decl_context->getParentASTContext();
  421. auto& mutable_tu_decl_context = *ast_context.getTranslationUnitDecl();
  422. auto* carbon_cpp_namespace = clang::NamespaceDecl::Create(
  423. ast_context, &mutable_tu_decl_context, false, clang::SourceLocation(),
  424. clang::SourceLocation(), &ast_context.Idents.get(carbon_namespace_name),
  425. nullptr, false);
  426. carbon_cpp_namespace->setHasExternalVisibleStorage();
  427. auto key = SemIR::ClangDeclKey::ForNonFunctionDecl(carbon_cpp_namespace);
  428. context_->clang_decls().Add(
  429. {.key = key, .inst_id = SemIR::Namespace::PackageInstId});
  430. SetExternalVisibleDeclsForName(decl_context, decl_name,
  431. {carbon_cpp_namespace});
  432. root_scope_initialized_ = true;
  433. return true;
  434. }
  435. // Find the Carbon declaration corresponding to this Clang declaration.
  436. auto* decl = cast<clang::Decl>(
  437. const_cast<clang::DeclContext*>(decl_context->getPrimaryContext()));
  438. auto key = SemIR::ClangDeclKey::ForNonFunctionDecl(decl);
  439. auto decl_id = context_->clang_decls().Lookup(key);
  440. CARBON_CHECK(
  441. decl_id.has_value(),
  442. "The DeclContext should already be associated with a Carbon InstId.");
  443. auto decl_context_inst_id = context_->clang_decls().Get(decl_id).inst_id;
  444. llvm::SmallVector<Check::LookupScope> lookup_scopes;
  445. // LocId::None seems fine here because we shouldn't produce any diagnostics
  446. // here - completeness should've been checked by clang before this point.
  447. if (!AppendLookupScopesForConstant(
  448. *context_, SemIR::LocId::None,
  449. context_->constant_values().Get(decl_context_inst_id),
  450. SemIR::ConstantId::None, &lookup_scopes)) {
  451. return false;
  452. }
  453. auto* identifier = decl_name.getAsIdentifierInfo();
  454. if (!identifier) {
  455. // Only supporting identifiers for now.
  456. return false;
  457. }
  458. auto name_id = AddIdentifierName(*context_, identifier->getName());
  459. // `required=false` so Carbon doesn't diagnose a failure, let Clang diagnose
  460. // it or even SFINAE.
  461. LookupResult result =
  462. LookupQualifiedName(*context_, SemIR::LocId::None, name_id, lookup_scopes,
  463. /*required=*/false);
  464. if (!result.scope_result.is_found()) {
  465. return false;
  466. }
  467. // Map the found Carbon entity to a Clang NamedDecl.
  468. // TODO: Stop passing in the `DeclContext` here; the context in which we
  469. // performed the lookup that first found the Carbon declaration should not
  470. // affect the Clang declaration we produce.
  471. auto* clang_decl = MapInstIdToClangDecl(
  472. *const_cast<clang::DeclContext*>(decl_context), result);
  473. if (!clang_decl) {
  474. return false;
  475. }
  476. SetExternalVisibleDeclsForName(decl_context, decl_name, {clang_decl});
  477. return true;
  478. }
  479. // Parses a sequence of top-level declarations and forms a corresponding
  480. // representation in the Clang AST. Unlike clang::ParseAST, does not finish the
  481. // translation unit when EOF is reached.
  482. static auto ParseTopLevelDecls(clang::Parser& parser,
  483. clang::ASTConsumer& consumer) -> void {
  484. // Don't allow C++20 module declarations in inline Cpp code fragments.
  485. auto module_import_state = clang::Sema::ModuleImportState::NotACXX20Module;
  486. // Parse top-level declarations until we see EOF. Do not parse EOF, as that
  487. // will cause the parser to end the translation unit prematurely.
  488. while (parser.getCurToken().isNot(clang::tok::eof)) {
  489. clang::Parser::DeclGroupPtrTy decl_group;
  490. bool eof = parser.ParseTopLevelDecl(decl_group, module_import_state);
  491. CARBON_CHECK(!eof, "Should not parse decls at EOF");
  492. if (decl_group && !consumer.HandleTopLevelDecl(decl_group.get())) {
  493. // If the consumer rejects the declaration, bail out of parsing.
  494. //
  495. // TODO: In this case, we shouldn't parse any more declarations even in
  496. // separate inline C++ fragments. But our current AST consumer only ever
  497. // returns true.
  498. break;
  499. }
  500. }
  501. }
  502. namespace {
  503. // An action and a set of registered Clang callbacks used to generate an AST
  504. // from a set of Cpp imports.
  505. class GenerateASTAction : public clang::ASTFrontendAction {
  506. public:
  507. explicit GenerateASTAction(Context& context) : context_(&context) {}
  508. protected:
  509. auto CreateASTConsumer(clang::CompilerInstance& clang_instance,
  510. llvm::StringRef /*file*/)
  511. -> std::unique_ptr<clang::ASTConsumer> override {
  512. auto& cpp_file = *context_->sem_ir().cpp_file();
  513. if (!cpp_file.llvm_context()) {
  514. return std::make_unique<clang::ASTConsumer>();
  515. }
  516. auto code_generator =
  517. std::unique_ptr<clang::CodeGenerator>(clang::CreateLLVMCodeGen(
  518. cpp_file.diagnostics(), context_->sem_ir().filename(),
  519. clang_instance.getVirtualFileSystemPtr(),
  520. clang_instance.getHeaderSearchOpts(),
  521. clang_instance.getPreprocessorOpts(),
  522. clang_instance.getCodeGenOpts(), *cpp_file.llvm_context()));
  523. cpp_file.SetCodeGenerator(code_generator.get());
  524. return code_generator;
  525. }
  526. auto BeginSourceFileAction(clang::CompilerInstance& /*clang_instance*/)
  527. -> bool override {
  528. // TODO: `clang.getPreprocessor().enableIncrementalProcessing();` to avoid
  529. // the TU scope getting torn down before we're done parsing macros.
  530. return true;
  531. }
  532. // Parse the imports and inline C++ fragments. This is notionally very similar
  533. // to `clang::ParseAST`, which `ASTFrontendAction::ExecuteAction` calls, but
  534. // this version doesn't parse C++20 modules and stops just before reaching the
  535. // end of the translation unit.
  536. auto ExecuteAction() -> void override {
  537. clang::CompilerInstance& clang_instance = getCompilerInstance();
  538. clang_instance.createSema(getTranslationUnitKind(),
  539. /*CompletionConsumer=*/nullptr);
  540. auto parser_ptr = std::make_unique<clang::Parser>(
  541. clang_instance.getPreprocessor(), clang_instance.getSema(),
  542. /*SkipFunctionBodies=*/false);
  543. auto& parser = *parser_ptr;
  544. clang_instance.getPreprocessor().EnterMainSourceFile();
  545. if (auto* source = clang_instance.getASTContext().getExternalSource()) {
  546. source->StartTranslationUnit(&clang_instance.getASTConsumer());
  547. }
  548. parser.Initialize();
  549. clang_instance.getSema().ActOnStartOfTranslationUnit();
  550. context_->set_cpp_context(
  551. std::make_unique<CppContext>(clang_instance, std::move(parser_ptr)));
  552. ParseTopLevelDecls(parser, clang_instance.getASTConsumer());
  553. }
  554. private:
  555. Context* context_;
  556. };
  557. } // namespace
  558. auto GenerateAst(Context& context,
  559. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  560. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  561. llvm::LLVMContext* llvm_context,
  562. std::shared_ptr<clang::CompilerInvocation> base_invocation)
  563. -> bool {
  564. CARBON_CHECK(!context.cpp_context());
  565. CARBON_CHECK(!context.sem_ir().cpp_file());
  566. auto invocation =
  567. std::make_shared<ShallowCopyCompilerInvocation>(*base_invocation);
  568. // Ask Clang to not leak memory.
  569. invocation->getFrontendOpts().DisableFree = false;
  570. // Build a diagnostics engine.
  571. llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diags(
  572. clang::CompilerInstance::createDiagnostics(
  573. *fs, invocation->getDiagnosticOpts(),
  574. new CarbonClangDiagnosticConsumer(context, invocation),
  575. /*ShouldOwnClient=*/true));
  576. // Extract the input from the frontend invocation and make sure it makes
  577. // sense.
  578. const auto& inputs = invocation->getFrontendOpts().Inputs;
  579. CARBON_CHECK(inputs.size() == 1 &&
  580. inputs[0].getKind().getLanguage() == clang::Language::CXX &&
  581. inputs[0].getKind().getFormat() == clang::InputKind::Source);
  582. llvm::StringRef file_name = inputs[0].getFile();
  583. // Remap the imports file name to the corresponding `#include`s.
  584. // TODO: Modify the frontend options to specify this memory buffer as input
  585. // instead of remapping the file.
  586. std::string includes = GenerateCppIncludesHeaderCode(context, imports);
  587. auto includes_buffer =
  588. llvm::MemoryBuffer::getMemBufferCopy(includes, file_name);
  589. invocation->getPreprocessorOpts().addRemappedFile(file_name,
  590. includes_buffer.release());
  591. auto clang_instance_ptr =
  592. std::make_unique<clang::CompilerInstance>(invocation);
  593. auto& clang_instance = *clang_instance_ptr;
  594. context.sem_ir().set_cpp_file(std::make_unique<SemIR::CppFile>(
  595. std::move(clang_instance_ptr), llvm_context));
  596. clang_instance.setDiagnostics(diags);
  597. clang_instance.setVirtualFileSystem(fs);
  598. clang_instance.createFileManager();
  599. clang_instance.createSourceManager();
  600. if (!clang_instance.createTarget()) {
  601. return false;
  602. }
  603. GenerateASTAction action(context);
  604. if (!action.BeginSourceFile(clang_instance, inputs[0])) {
  605. return false;
  606. }
  607. auto& ast = clang_instance.getASTContext();
  608. // TODO: Clang's modules support is implemented as an ExternalASTSource
  609. // (ASTReader) and there's no multiplexing support for ExternalASTSources at
  610. // the moment - so registering CarbonExternalASTSource breaks Clang modules
  611. // support. Implement multiplexing support (possibly in Clang) to restore
  612. // modules functionality.
  613. ast.setExternalSource(
  614. llvm::makeIntrusiveRefCnt<CarbonExternalASTSource>(&context, &ast));
  615. if (llvm::Error error = action.Execute()) {
  616. // `Execute` currently never fails, but its contract allows it to.
  617. context.TODO(SemIR::LocId::None, "failed to execute clang action: " +
  618. llvm::toString(std::move(error)));
  619. return false;
  620. }
  621. // Flush any diagnostics. We know we're not part-way through emitting a
  622. // diagnostic now.
  623. context.emitter().Flush();
  624. return true;
  625. }
  626. auto InjectAstFromInlineCode(Context& context, SemIR::LocId loc_id,
  627. llvm::StringRef source_code) -> void {
  628. auto* cpp_context = context.cpp_context();
  629. CARBON_CHECK(cpp_context);
  630. clang::Sema& sema = cpp_context->sema();
  631. clang::Preprocessor& preprocessor = sema.getPreprocessor();
  632. clang::Parser& parser = cpp_context->parser();
  633. RawStringOstream code_stream;
  634. AppendInlineCode(context, code_stream,
  635. context.parse_tree().node_token(loc_id.node_id()),
  636. source_code);
  637. auto buffer = llvm::MemoryBuffer::getMemBufferCopy(code_stream.TakeStr(),
  638. "<inline c++>");
  639. clang::FileID file_id =
  640. preprocessor.getSourceManager().createFileID(std::move(buffer));
  641. if (preprocessor.EnterSourceFile(file_id, nullptr, clang::SourceLocation())) {
  642. // Clang will have generated a suitable error. There's nothing more to do
  643. // here.
  644. return;
  645. }
  646. // The parser will typically have an EOF as its cached current token; consume
  647. // that so we can reach the newly-injected tokens.
  648. if (parser.getCurToken().is(clang::tok::eof)) {
  649. parser.ConsumeToken();
  650. }
  651. ParseTopLevelDecls(parser, sema.getASTConsumer());
  652. }
  653. auto FinishAst(Context& context) -> void {
  654. if (!context.cpp_context()) {
  655. return;
  656. }
  657. context.cpp_context()->sema().ActOnEndOfTranslationUnit();
  658. // We don't call FrontendAction::EndSourceFile, because that destroys the AST.
  659. context.set_cpp_context(nullptr);
  660. context.emitter().Flush();
  661. }
  662. } // namespace Carbon::Check