generate_ast.cpp 30 KB

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