generate_ast.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  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. #include "toolchain/sem_ir/mangler.h"
  36. namespace Carbon::Check {
  37. // Add a line marker directive pointing at the location of the `import Cpp`
  38. // declaration in the Carbon source file. This will cause Clang's diagnostics
  39. // machinery to track and report the location in Carbon code where the import
  40. // was written.
  41. static auto GenerateLineMarker(Context& context, llvm::raw_ostream& out,
  42. int line) {
  43. out << "# " << line << " \""
  44. << FormatEscaped(context.tokens().source().filename()) << "\"\n";
  45. }
  46. // Appends a line marker and the specified `code` to `out`, adjusting the
  47. // `line` number if the `code_token` represents a block string literal.
  48. static auto AppendInlineCode(Context& context, llvm::raw_ostream& out,
  49. Lex::TokenIndex code_token, llvm::StringRef code)
  50. -> void {
  51. // Compute the line number on which the C++ code starts. Usually the code
  52. // is specified as a block string literal and starts on the line after the
  53. // start of the string token.
  54. // TODO: Determine if this is a block string literal without calling
  55. // `GetTokenText`, which re-lexes the string.
  56. int line = context.tokens().GetLineNumber(code_token);
  57. if (context.tokens().GetTokenText(code_token).contains('\n')) {
  58. ++line;
  59. }
  60. GenerateLineMarker(context, out, line);
  61. out << code << "\n";
  62. }
  63. // Generates C++ file contents to #include all requested imports.
  64. static auto GenerateCppIncludesHeaderCode(
  65. Context& context, llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  66. -> std::string {
  67. RawStringOstream code_stream;
  68. for (const Parse::Tree::PackagingNames& import : imports) {
  69. if (import.inline_body_id.has_value()) {
  70. // Expand `import Cpp inline "code";` directly into the specified code.
  71. auto code_token = context.parse_tree().node_token(import.inline_body_id);
  72. AppendInlineCode(context, code_stream, code_token,
  73. context.string_literal_values().Get(
  74. context.tokens().GetStringLiteralValue(code_token)));
  75. // TODO: Inject a clang pragma here to produce an error if there are
  76. // unclosed scopes at the end of this inline C++ fragment.
  77. } else if (import.library_id.has_value()) {
  78. // Translate `import Cpp library "foo.h";` into `#include "foo.h"`.
  79. GenerateLineMarker(context, code_stream,
  80. context.tokens().GetLineNumber(
  81. context.parse_tree().node_token(import.node_id)));
  82. auto name = context.string_literal_values().Get(import.library_id);
  83. if (name.starts_with('<') && name.ends_with('>')) {
  84. code_stream << "#include <"
  85. << FormatEscaped(name.drop_front().drop_back()) << ">\n";
  86. } else {
  87. code_stream << "#include \"" << FormatEscaped(name) << "\"\n";
  88. }
  89. }
  90. }
  91. return code_stream.TakeStr();
  92. }
  93. // Adds the given source location and an `ImportIRInst` referring to it in
  94. // `ImportIRId::Cpp`.
  95. static auto AddImportIRInst(SemIR::File& file,
  96. clang::SourceLocation clang_source_loc)
  97. -> SemIR::ImportIRInstId {
  98. SemIR::ClangSourceLocId clang_source_loc_id =
  99. file.clang_source_locs().Add(clang_source_loc);
  100. return file.import_ir_insts().Add(SemIR::ImportIRInst(clang_source_loc_id));
  101. }
  102. namespace {
  103. // Used to convert Clang diagnostics to Carbon diagnostics.
  104. //
  105. // Handling of Clang notes is a little subtle: as far as Clang is concerned,
  106. // notes are separate diagnostics, not connected to the error or warning that
  107. // precedes them. But in Carbon's diagnostics system, notes are part of the
  108. // enclosing diagnostic. To handle this, we buffer Clang diagnostics until we
  109. // reach a point where we know we're not in the middle of a diagnostic, and then
  110. // emit a diagnostic along with all of its notes. This is triggered when adding
  111. // or removing a Carbon context note, which could otherwise get attached to the
  112. // wrong C++ diagnostics, and at the end of the Carbon program.
  113. class CarbonClangDiagnosticConsumer : public clang::DiagnosticConsumer {
  114. public:
  115. // Creates an instance with the location that triggers calling Clang. The
  116. // `context` is not stored here, and the diagnostics consumer is expected to
  117. // outlive it.
  118. explicit CarbonClangDiagnosticConsumer(
  119. Context& context, std::shared_ptr<clang::CompilerInvocation> invocation)
  120. : sem_ir_(&context.sem_ir()),
  121. emitter_(&context.emitter()),
  122. invocation_(std::move(invocation)) {
  123. emitter_->AddFlushFn([this] { EmitDiagnostics(); });
  124. }
  125. ~CarbonClangDiagnosticConsumer() override {
  126. // Do not inspect `emitter_` here; it's typically destroyed before the
  127. // consumer is.
  128. // TODO: If Clang produces diagnostics after check finishes, they'll get
  129. // added to the list of pending diagnostics and never emitted.
  130. CARBON_CHECK(diagnostic_infos_.empty(),
  131. "Missing flush before destroying diagnostic consumer");
  132. }
  133. // Generates a Carbon warning for each Clang warning and a Carbon error for
  134. // each Clang error or fatal.
  135. auto HandleDiagnostic(clang::DiagnosticsEngine::Level diag_level,
  136. const clang::Diagnostic& info) -> void override {
  137. DiagnosticConsumer::HandleDiagnostic(diag_level, info);
  138. SemIR::ImportIRInstId clang_import_ir_inst_id =
  139. AddImportIRInst(*sem_ir_, info.getLocation());
  140. llvm::SmallString<256> message;
  141. info.FormatDiagnostic(message);
  142. // Render a code snippet including any highlighted ranges and fixit hints.
  143. // TODO: Also include the #include stack and macro expansion stack in the
  144. // diagnostic output in some way.
  145. RawStringOstream snippet_stream;
  146. if (!info.hasSourceManager()) {
  147. // If we don't have a source manager, this is an error from early in the
  148. // frontend. Don't produce a snippet.
  149. CARBON_CHECK(info.getLocation().isInvalid());
  150. } else {
  151. CodeContextRenderer(snippet_stream, invocation_->getLangOpts(),
  152. invocation_->getDiagnosticOpts())
  153. .emitDiagnostic(
  154. clang::FullSourceLoc(info.getLocation(), info.getSourceManager()),
  155. diag_level, message, info.getRanges(), info.getFixItHints());
  156. }
  157. diagnostic_infos_.push_back({.level = diag_level,
  158. .import_ir_inst_id = clang_import_ir_inst_id,
  159. .message = message.str().str(),
  160. .snippet = snippet_stream.TakeStr()});
  161. }
  162. // Returns the diagnostic to use for a given Clang diagnostic level.
  163. static auto GetDiagnostic(clang::DiagnosticsEngine::Level level)
  164. -> const Diagnostics::DiagnosticBase<std::string>& {
  165. switch (level) {
  166. case clang::DiagnosticsEngine::Ignored: {
  167. CARBON_FATAL("Emitting an ignored diagnostic");
  168. break;
  169. }
  170. case clang::DiagnosticsEngine::Note: {
  171. CARBON_DIAGNOSTIC(CppInteropParseNote, Note, "{0}", std::string);
  172. return CppInteropParseNote;
  173. }
  174. case clang::DiagnosticsEngine::Remark:
  175. case clang::DiagnosticsEngine::Warning: {
  176. // TODO: Add a distinct Remark level to Carbon diagnostics, and stop
  177. // mapping remarks to warnings.
  178. CARBON_DIAGNOSTIC(CppInteropParseWarning, Warning, "{0}", std::string);
  179. return CppInteropParseWarning;
  180. }
  181. case clang::DiagnosticsEngine::Error:
  182. case clang::DiagnosticsEngine::Fatal: {
  183. CARBON_DIAGNOSTIC(CppInteropParseError, Error, "{0}", std::string);
  184. return CppInteropParseError;
  185. }
  186. }
  187. }
  188. // Outputs Carbon diagnostics based on the collected Clang diagnostics. Must
  189. // be called after the AST is set in the context.
  190. auto EmitDiagnostics() -> void {
  191. CARBON_CHECK(
  192. sem_ir_->cpp_file(),
  193. "Attempted to emit C++ diagnostics before the C++ file is set");
  194. for (size_t i = 0; i != diagnostic_infos_.size(); ++i) {
  195. const ClangDiagnosticInfo& info = diagnostic_infos_[i];
  196. auto builder = emitter_->Build(SemIR::LocId(info.import_ir_inst_id),
  197. GetDiagnostic(info.level), info.message);
  198. builder.OverrideSnippet(info.snippet);
  199. for (; i + 1 < diagnostic_infos_.size() &&
  200. diagnostic_infos_[i + 1].level == clang::DiagnosticsEngine::Note;
  201. ++i) {
  202. const ClangDiagnosticInfo& note_info = diagnostic_infos_[i + 1];
  203. builder
  204. .Note(SemIR::LocId(note_info.import_ir_inst_id),
  205. GetDiagnostic(note_info.level), note_info.message)
  206. .OverrideSnippet(note_info.snippet);
  207. }
  208. // TODO: This will apply all current Carbon annotation functions. We
  209. // should instead track how Clang's context notes and Carbon's annotation
  210. // functions are interleaved, and interleave the notes in the same order.
  211. builder.Emit();
  212. }
  213. diagnostic_infos_.clear();
  214. }
  215. private:
  216. // A diagnostics renderer based on clang's TextDiagnostic that captures just
  217. // the code context (the snippet).
  218. class CodeContextRenderer : public clang::TextDiagnostic {
  219. protected:
  220. using TextDiagnostic::TextDiagnostic;
  221. void emitDiagnosticMessage(
  222. clang::FullSourceLoc /*loc*/, clang::PresumedLoc /*ploc*/,
  223. clang::DiagnosticsEngine::Level /*level*/, llvm::StringRef /*message*/,
  224. llvm::ArrayRef<clang::CharSourceRange> /*ranges*/,
  225. clang::DiagOrStoredDiag /*info*/) override {}
  226. void emitDiagnosticLoc(
  227. clang::FullSourceLoc /*loc*/, clang::PresumedLoc /*ploc*/,
  228. clang::DiagnosticsEngine::Level /*level*/,
  229. llvm::ArrayRef<clang::CharSourceRange> /*ranges*/) override {}
  230. // emitCodeContext is inherited from clang::TextDiagnostic.
  231. void emitIncludeLocation(clang::FullSourceLoc /*loc*/,
  232. clang::PresumedLoc /*ploc*/) override {}
  233. void emitImportLocation(clang::FullSourceLoc /*loc*/,
  234. clang::PresumedLoc /*ploc*/,
  235. llvm::StringRef /*module_name*/) override {}
  236. void emitBuildingModuleLocation(clang::FullSourceLoc /*loc*/,
  237. clang::PresumedLoc /*ploc*/,
  238. llvm::StringRef /*module_name*/) override {}
  239. // beginDiagnostic and endDiagnostic are inherited from
  240. // clang::TextDiagnostic in case it wants to do any setup / teardown work.
  241. };
  242. // Information on a Clang diagnostic that can be converted to a Carbon
  243. // diagnostic.
  244. struct ClangDiagnosticInfo {
  245. // The Clang diagnostic level.
  246. clang::DiagnosticsEngine::Level level;
  247. // The ID of the ImportIR instruction referring to the Clang source
  248. // location.
  249. SemIR::ImportIRInstId import_ir_inst_id;
  250. // The Clang diagnostic textual message.
  251. std::string message;
  252. // The code snippet produced by clang.
  253. std::string snippet;
  254. };
  255. // The Carbon file that this C++ compilation is attached to.
  256. SemIR::File* sem_ir_;
  257. // The diagnostic emitter that we're emitting diagnostics into.
  258. DiagnosticEmitterBase* emitter_;
  259. // The compiler invocation that is producing the diagnostics.
  260. std::shared_ptr<clang::CompilerInvocation> invocation_;
  261. // Collects the information for all Clang diagnostics to be converted to
  262. // Carbon diagnostics after the context has been initialized with the Clang
  263. // AST.
  264. llvm::SmallVector<ClangDiagnosticInfo> diagnostic_infos_;
  265. };
  266. // A wrapper around a clang::CompilerInvocation that allows us to make a shallow
  267. // copy of most of the invocation and only make a deep copy of the parts that we
  268. // want to change.
  269. //
  270. // clang::CowCompilerInvocation almost allows this, but doesn't derive from
  271. // CompilerInvocation or support shallow copies from a CompilerInvocation, so is
  272. // not useful to us as we can't build an ASTUnit from it.
  273. class ShallowCopyCompilerInvocation : public clang::CompilerInvocation {
  274. public:
  275. explicit ShallowCopyCompilerInvocation(
  276. const clang::CompilerInvocation& invocation) {
  277. shallow_copy_assign(invocation);
  278. // Make a deep copy of options that we modify.
  279. FrontendOpts = std::make_shared<clang::FrontendOptions>(*FrontendOpts);
  280. PPOpts = std::make_shared<clang::PreprocessorOptions>(*PPOpts);
  281. }
  282. };
  283. // Provides clang AST nodes representing Carbon SemIR entities.
  284. class CarbonExternalASTSource : public clang::ExternalASTSource {
  285. public:
  286. explicit CarbonExternalASTSource(Context* context,
  287. clang::ASTContext* ast_context)
  288. : context_(context), ast_context_(ast_context) {}
  289. // Look up decls for `decl_name` inside `decl_context`, adding the decls to
  290. // `decl_context`. Returns true if any decls were added.
  291. auto FindExternalVisibleDeclsByName(
  292. const clang::DeclContext* decl_context, clang::DeclarationName decl_name,
  293. const clang::DeclContext* original_decl_context) -> bool override;
  294. // See clang::ExternalASTSource.
  295. auto StartTranslationUnit(clang::ASTConsumer* consumer) -> void override;
  296. private:
  297. // Map a Carbon entity to a Clang NamedDecl. Returns null if the entity cannot
  298. // currently be represented in C++.
  299. auto MapInstIdToClangDecl(clang::DeclContext& decl_context,
  300. LookupResult lookup) -> clang::NamedDecl*;
  301. Check::Context* context_;
  302. clang::ASTContext* ast_context_;
  303. // The association between clang DeclContexts and the corresponding
  304. // SemIR::Namespaces in Carbon.
  305. // TODO: reuse the SemIR::File::ClangDeclStore to avoid duplicates, and to
  306. // enable roundtripping through forward and reverse interop (once we have
  307. // syntax/support for that).
  308. Map<clang::DeclContext*, SemIR::InstId> scope_map_;
  309. // Has the "Carbon" C++ namespace been created yet
  310. // (this could be replaced with `!scope_map_.empty()` if Carbon::Map supported
  311. // `empty()`)
  312. bool root_scope_initialized_ = false;
  313. };
  314. } // namespace
  315. void CarbonExternalASTSource::StartTranslationUnit(
  316. clang::ASTConsumer* /*Consumer*/) {
  317. auto& translation_unit = *ast_context_->getTranslationUnitDecl();
  318. // Mark the translation unit as having external storage so we get a query for
  319. // the `Carbon` namespace in the top level/translation unit scope.
  320. translation_unit.setHasExternalVisibleStorage();
  321. }
  322. auto CarbonExternalASTSource::MapInstIdToClangDecl(
  323. clang::DeclContext& decl_context, LookupResult lookup)
  324. -> clang::NamedDecl* {
  325. auto target_inst_id = lookup.scope_result.target_inst_id();
  326. auto target_constant =
  327. context_->constant_values().GetConstantInstId(target_inst_id);
  328. auto target_inst = context_->insts().Get(target_constant);
  329. CARBON_KIND_SWITCH(target_inst) {
  330. case CARBON_KIND(SemIR::Namespace namespace_info): {
  331. auto& name_scope =
  332. context_->name_scopes().Get(namespace_info.name_scope_id);
  333. auto* identifier_info =
  334. GetClangIdentifierInfo(*context_, name_scope.name_id());
  335. // TODO: Don't immediately use the decl_context - build any intermediate
  336. // namespaces iteratively.
  337. // Eventually add a mapping and use that/populate it/keep it up to date.
  338. // decl_context could be prepopulated in that mapping and not passed
  339. // explicitly to MapInstIdToClangDecl.
  340. auto* namespace_decl = clang::NamespaceDecl::Create(
  341. *ast_context_, &decl_context, false, clang::SourceLocation(),
  342. clang::SourceLocation(), identifier_info, nullptr, false);
  343. auto result = scope_map_.Insert(namespace_decl->getPrimaryContext(),
  344. target_inst_id);
  345. CARBON_CHECK(result.is_inserted(), "Inserting over an existing entry.");
  346. namespace_decl->setHasExternalVisibleStorage();
  347. return namespace_decl;
  348. }
  349. case CARBON_KIND(SemIR::ClassType class_type): {
  350. const auto& class_info = context_->classes().Get(class_type.class_id);
  351. auto* identifier_info =
  352. GetClangIdentifierInfo(*context_, class_info.name_id);
  353. return clang::CXXRecordDecl::Create(
  354. *ast_context_, clang::TagTypeKind::Class, &decl_context,
  355. clang::SourceLocation(), clang::SourceLocation(), identifier_info);
  356. }
  357. case SemIR::StructValue::Kind: {
  358. auto callee = GetCallee(context_->sem_ir(), target_constant);
  359. auto* callee_function = std::get_if<SemIR::CalleeFunction>(&callee);
  360. if (!callee_function) {
  361. return nullptr;
  362. }
  363. const SemIR::Function& function =
  364. context_->functions().Get(callee_function->function_id);
  365. auto* identifier_info =
  366. GetClangIdentifierInfo(*context_, function.name_id);
  367. if (function.call_param_ranges.explicit_size() != 0) {
  368. context_->TODO(target_inst_id,
  369. "unsupported: C++ calling a Carbon function with "
  370. "parameters");
  371. return nullptr;
  372. }
  373. if (function.return_type_inst_id != SemIR::TypeInstId::None) {
  374. context_->TODO(target_inst_id,
  375. "unsupported: C++ calling a Carbon function with "
  376. "return type other than `()`");
  377. return nullptr;
  378. }
  379. // TODO: support non-empty parameter lists.
  380. llvm::SmallVector<clang::QualType> cpp_param_types;
  381. // TODO: support non-void return types.
  382. auto cpp_return_type = ast_context_->VoidTy;
  383. auto cpp_function_type = ast_context_->getFunctionType(
  384. cpp_return_type, cpp_param_types,
  385. clang::FunctionProtoType::ExtProtoInfo());
  386. auto* function_decl = clang::FunctionDecl::Create(
  387. *ast_context_, &decl_context,
  388. /*StartLoc=*/clang::SourceLocation(),
  389. /*NLoc=*/clang::SourceLocation(),
  390. clang::DeclarationName(identifier_info), cpp_function_type,
  391. /*TInfo=*/nullptr, clang::SC_Extern);
  392. // Mangle the function name and attach it to the `FunctionDecl`.
  393. SemIR::Mangler m(context_->sem_ir(), context_->total_ir_count());
  394. std::string mangled_name =
  395. m.Mangle(callee_function->function_id, SemIR::SpecificId::None);
  396. function_decl->addAttr(
  397. clang::AsmLabelAttr::Create(*ast_context_, mangled_name));
  398. return function_decl;
  399. }
  400. default:
  401. return nullptr;
  402. }
  403. }
  404. auto CarbonExternalASTSource::FindExternalVisibleDeclsByName(
  405. const clang::DeclContext* decl_context, clang::DeclarationName decl_name,
  406. const clang::DeclContext* /*OriginalDC*/) -> bool {
  407. if (decl_context->getDeclKind() == clang::Decl::Kind::TranslationUnit) {
  408. // If the context doesn't already have a mapping between C++ and Carbon,
  409. // check if this is the root mapping (for the "Carbon" namespace in the
  410. // translation unit scope) and if so, create that mapping.
  411. if (root_scope_initialized_) {
  412. return false;
  413. }
  414. static const llvm::StringLiteral carbon_namespace_name = "Carbon";
  415. if (auto* identifier = decl_name.getAsIdentifierInfo();
  416. !identifier || !identifier->isStr(carbon_namespace_name)) {
  417. return false;
  418. }
  419. // Build the top level 'Carbon' namespace
  420. auto& ast_context = decl_context->getParentASTContext();
  421. auto& mutable_tu_decl_context = *ast_context.getTranslationUnitDecl();
  422. auto* carbon_cpp_namespace = clang::NamespaceDecl::Create(
  423. ast_context, &mutable_tu_decl_context, false, clang::SourceLocation(),
  424. clang::SourceLocation(), &ast_context.Idents.get(carbon_namespace_name),
  425. nullptr, false);
  426. carbon_cpp_namespace->setHasExternalVisibleStorage();
  427. auto result = scope_map_.Insert(carbon_cpp_namespace->getPrimaryContext(),
  428. SemIR::Namespace::PackageInstId);
  429. CARBON_CHECK(result.is_inserted(), "Inserting over an existing entry.");
  430. SetExternalVisibleDeclsForName(decl_context, decl_name,
  431. {carbon_cpp_namespace});
  432. root_scope_initialized_ = true;
  433. return true;
  434. }
  435. auto decl_context_inst_id =
  436. scope_map_.Lookup(decl_context->getPrimaryContext());
  437. CARBON_CHECK(
  438. decl_context_inst_id,
  439. "The DeclContext should already be associated with a Carbon InstId.");
  440. llvm::SmallVector<Check::LookupScope> lookup_scopes;
  441. // LocId::None seems fine here because we shouldn't produce any diagnostics
  442. // here - completeness should've been checked by clang before this point.
  443. if (!AppendLookupScopesForConstant(
  444. *context_, SemIR::LocId::None,
  445. context_->constant_values().Get(decl_context_inst_id.value()),
  446. SemIR::ConstantId::None, &lookup_scopes)) {
  447. return false;
  448. }
  449. auto* identifier = decl_name.getAsIdentifierInfo();
  450. if (!identifier) {
  451. // Only supporting identifiers for now.
  452. return false;
  453. }
  454. auto name_id = AddIdentifierName(*context_, identifier->getName());
  455. // `required=false` so Carbon doesn't diagnose a failure, let Clang diagnose
  456. // it or even SFINAE.
  457. LookupResult result =
  458. LookupQualifiedName(*context_, SemIR::LocId::None, name_id, lookup_scopes,
  459. /*required=*/false);
  460. if (!result.scope_result.is_found()) {
  461. return false;
  462. }
  463. // Map the found Carbon entity to a Clang NamedDecl.
  464. // Use the key to reach the owned, mutable copy of decl_context.
  465. auto* clang_decl = MapInstIdToClangDecl(*decl_context_inst_id.key(), result);
  466. if (!clang_decl) {
  467. return false;
  468. }
  469. SetExternalVisibleDeclsForName(decl_context, decl_name, {clang_decl});
  470. return true;
  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. if (auto* source = clang_instance.getASTContext().getExternalSource()) {
  539. source->StartTranslationUnit(&clang_instance.getASTConsumer());
  540. }
  541. parser.Initialize();
  542. clang_instance.getSema().ActOnStartOfTranslationUnit();
  543. context_->set_cpp_context(
  544. std::make_unique<CppContext>(clang_instance, std::move(parser_ptr)));
  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, &ast));
  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