generate_ast.cpp 28 KB

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