generate_ast.cpp 31 KB

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