generate_ast.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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/Frontend/CompilerInstance.h"
  10. #include "clang/Frontend/CompilerInvocation.h"
  11. #include "clang/Frontend/FrontendAction.h"
  12. #include "clang/Frontend/TextDiagnostic.h"
  13. #include "clang/Lex/PreprocessorOptions.h"
  14. #include "clang/Parse/Parser.h"
  15. #include "clang/Sema/ExternalSemaSource.h"
  16. #include "clang/Sema/Sema.h"
  17. #include "common/check.h"
  18. #include "common/raw_string_ostream.h"
  19. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. #include "toolchain/check/context.h"
  23. #include "toolchain/diagnostics/diagnostic.h"
  24. #include "toolchain/diagnostics/diagnostic_emitter.h"
  25. #include "toolchain/diagnostics/format_providers.h"
  26. #include "toolchain/parse/node_ids.h"
  27. #include "toolchain/sem_ir/cpp_file.h"
  28. namespace Carbon::Check {
  29. // Add a line marker directive pointing at the location of the `import Cpp`
  30. // declaration in the Carbon source file. This will cause Clang's diagnostics
  31. // machinery to track and report the location in Carbon code where the import
  32. // was written.
  33. static auto GenerateLineMarker(Context& context, llvm::raw_ostream& out,
  34. int line) {
  35. out << "# " << line << " \""
  36. << FormatEscaped(context.tokens().source().filename()) << "\"\n";
  37. }
  38. // Generates C++ file contents to #include all requested imports.
  39. static auto GenerateCppIncludesHeaderCode(
  40. Context& context, llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  41. -> std::string {
  42. std::string code;
  43. llvm::raw_string_ostream code_stream(code);
  44. for (const Parse::Tree::PackagingNames& import : imports) {
  45. if (import.inline_body_id.has_value()) {
  46. // Expand `import Cpp inline "code";` directly into the specified code.
  47. auto code_token = context.parse_tree().node_token(import.inline_body_id);
  48. // Compute the line number on which the C++ code starts. Usually the code
  49. // is specified as a block string literal and starts on the line after the
  50. // start of the string token.
  51. // TODO: Determine if this is a block string literal without calling
  52. // `GetTokenText`, which re-lexes the string.
  53. int line = context.tokens().GetLineNumber(code_token);
  54. if (context.tokens().GetTokenText(code_token).contains('\n')) {
  55. ++line;
  56. }
  57. GenerateLineMarker(context, code_stream, line);
  58. code_stream << context.string_literal_values().Get(
  59. context.tokens().GetStringLiteralValue(code_token))
  60. << "\n";
  61. // TODO: Inject a clang pragma here to produce an error if there are
  62. // unclosed scopes at the end of this inline C++ fragment.
  63. } else if (import.library_id.has_value()) {
  64. // Translate `import Cpp library "foo.h";` into `#include "foo.h"`.
  65. GenerateLineMarker(context, code_stream,
  66. context.tokens().GetLineNumber(
  67. context.parse_tree().node_token(import.node_id)));
  68. auto name = context.string_literal_values().Get(import.library_id);
  69. if (name.starts_with('<') && name.ends_with('>')) {
  70. code_stream << "#include <"
  71. << FormatEscaped(name.drop_front().drop_back()) << ">\n";
  72. } else {
  73. code_stream << "#include \"" << FormatEscaped(name) << "\"\n";
  74. }
  75. }
  76. }
  77. // Inject a declaration of placement operator new, because the code we
  78. // generate in thunks depends on it for placement new expressions. Clang has
  79. // special-case logic for lowering a new-expression using this, so a
  80. // definition is not required.
  81. // TODO: This is a hack. We should be able to directly generate Clang AST to
  82. // construct objects in-place without this.
  83. // TODO: Once we can rely on libc++ being available, consider including
  84. // `<__new/placement_new_delete.h>` instead.
  85. code_stream << R"(# 1 "<carbon-internal>"
  86. #undef constexpr
  87. #if __cplusplus > 202302L
  88. constexpr
  89. #endif
  90. #undef void
  91. #undef operator
  92. #undef new
  93. void* operator new(__SIZE_TYPE__, void*)
  94. #if __cplusplus < 201103L
  95. #undef throw
  96. throw()
  97. #else
  98. #undef noexcept
  99. noexcept
  100. #endif
  101. ;
  102. )";
  103. return code;
  104. }
  105. // Adds the given source location and an `ImportIRInst` referring to it in
  106. // `ImportIRId::Cpp`.
  107. static auto AddImportIRInst(SemIR::File& file,
  108. clang::SourceLocation clang_source_loc)
  109. -> SemIR::ImportIRInstId {
  110. SemIR::ClangSourceLocId clang_source_loc_id =
  111. file.clang_source_locs().Add(clang_source_loc);
  112. return file.import_ir_insts().Add(SemIR::ImportIRInst(clang_source_loc_id));
  113. }
  114. namespace {
  115. // Used to convert Clang diagnostics to Carbon diagnostics.
  116. //
  117. // Handling of Clang notes is a little subtle: as far as Clang is concerned,
  118. // notes are separate diagnostics, not connected to the error or warning that
  119. // precedes them. But in Carbon's diagnostics system, notes are part of the
  120. // enclosing diagnostic. To handle this, we buffer Clang diagnostics until we
  121. // reach a point where we know we're not in the middle of a diagnostic, and then
  122. // emit a diagnostic along with all of its notes. This is triggered when adding
  123. // or removing a Carbon context note, which could otherwise get attached to the
  124. // wrong C++ diagnostics, and at the end of the Carbon program.
  125. class CarbonClangDiagnosticConsumer : public clang::DiagnosticConsumer {
  126. public:
  127. // Creates an instance with the location that triggers calling Clang. The
  128. // `context` is not stored here, and the diagnostics consumer is expected to
  129. // outlive it.
  130. explicit CarbonClangDiagnosticConsumer(
  131. Context& context, std::shared_ptr<clang::CompilerInvocation> invocation)
  132. : sem_ir_(&context.sem_ir()),
  133. emitter_(&context.emitter()),
  134. invocation_(std::move(invocation)) {
  135. emitter_->AddFlushFn([this] { EmitDiagnostics(); });
  136. }
  137. ~CarbonClangDiagnosticConsumer() override {
  138. // Do not inspect `emitter_` here; it's typically destroyed before the
  139. // consumer is.
  140. // TODO: If Clang produces diagnostics after check finishes, they'll get
  141. // added to the list of pending diagnostics and never emitted.
  142. CARBON_CHECK(diagnostic_infos_.empty(),
  143. "Missing flush before destroying diagnostic consumer");
  144. }
  145. // Generates a Carbon warning for each Clang warning and a Carbon error for
  146. // each Clang error or fatal.
  147. auto HandleDiagnostic(clang::DiagnosticsEngine::Level diag_level,
  148. const clang::Diagnostic& info) -> void override {
  149. DiagnosticConsumer::HandleDiagnostic(diag_level, info);
  150. SemIR::ImportIRInstId clang_import_ir_inst_id =
  151. AddImportIRInst(*sem_ir_, info.getLocation());
  152. llvm::SmallString<256> message;
  153. info.FormatDiagnostic(message);
  154. // Render a code snippet including any highlighted ranges and fixit hints.
  155. // TODO: Also include the #include stack and macro expansion stack in the
  156. // diagnostic output in some way.
  157. RawStringOstream snippet_stream;
  158. if (!info.hasSourceManager()) {
  159. // If we don't have a source manager, this is an error from early in the
  160. // frontend. Don't produce a snippet.
  161. CARBON_CHECK(info.getLocation().isInvalid());
  162. } else {
  163. CodeContextRenderer(snippet_stream, invocation_->getLangOpts(),
  164. invocation_->getDiagnosticOpts())
  165. .emitDiagnostic(
  166. clang::FullSourceLoc(info.getLocation(), info.getSourceManager()),
  167. diag_level, message, info.getRanges(), info.getFixItHints());
  168. }
  169. diagnostic_infos_.push_back({.level = diag_level,
  170. .import_ir_inst_id = clang_import_ir_inst_id,
  171. .message = message.str().str(),
  172. .snippet = snippet_stream.TakeStr()});
  173. }
  174. // Returns the diagnostic to use for a given Clang diagnostic level.
  175. static auto GetDiagnostic(clang::DiagnosticsEngine::Level level)
  176. -> const Diagnostics::DiagnosticBase<std::string>& {
  177. switch (level) {
  178. case clang::DiagnosticsEngine::Ignored: {
  179. CARBON_FATAL("Emitting an ignored diagnostic");
  180. break;
  181. }
  182. case clang::DiagnosticsEngine::Note: {
  183. CARBON_DIAGNOSTIC(CppInteropParseNote, Note, "{0}", std::string);
  184. return CppInteropParseNote;
  185. }
  186. case clang::DiagnosticsEngine::Remark:
  187. case clang::DiagnosticsEngine::Warning: {
  188. // TODO: Add a distinct Remark level to Carbon diagnostics, and stop
  189. // mapping remarks to warnings.
  190. CARBON_DIAGNOSTIC(CppInteropParseWarning, Warning, "{0}", std::string);
  191. return CppInteropParseWarning;
  192. }
  193. case clang::DiagnosticsEngine::Error:
  194. case clang::DiagnosticsEngine::Fatal: {
  195. CARBON_DIAGNOSTIC(CppInteropParseError, Error, "{0}", std::string);
  196. return CppInteropParseError;
  197. }
  198. }
  199. }
  200. // Outputs Carbon diagnostics based on the collected Clang diagnostics. Must
  201. // be called after the AST is set in the context.
  202. auto EmitDiagnostics() -> void {
  203. CARBON_CHECK(
  204. sem_ir_->cpp_file(),
  205. "Attempted to emit C++ diagnostics before the C++ file is set");
  206. for (size_t i = 0; i != diagnostic_infos_.size(); ++i) {
  207. const ClangDiagnosticInfo& info = diagnostic_infos_[i];
  208. auto builder = emitter_->Build(SemIR::LocId(info.import_ir_inst_id),
  209. GetDiagnostic(info.level), info.message);
  210. builder.OverrideSnippet(info.snippet);
  211. for (; i + 1 < diagnostic_infos_.size() &&
  212. diagnostic_infos_[i + 1].level == clang::DiagnosticsEngine::Note;
  213. ++i) {
  214. const ClangDiagnosticInfo& note_info = diagnostic_infos_[i + 1];
  215. builder
  216. .Note(SemIR::LocId(note_info.import_ir_inst_id),
  217. GetDiagnostic(note_info.level), note_info.message)
  218. .OverrideSnippet(note_info.snippet);
  219. }
  220. // TODO: This will apply all current Carbon annotation functions. We
  221. // should instead track how Clang's context notes and Carbon's annotation
  222. // functions are interleaved, and interleave the notes in the same order.
  223. builder.Emit();
  224. }
  225. diagnostic_infos_.clear();
  226. }
  227. private:
  228. // A diagnostics renderer based on clang's TextDiagnostic that captures just
  229. // the code context (the snippet).
  230. class CodeContextRenderer : public clang::TextDiagnostic {
  231. protected:
  232. using TextDiagnostic::TextDiagnostic;
  233. void emitDiagnosticMessage(
  234. clang::FullSourceLoc /*loc*/, clang::PresumedLoc /*ploc*/,
  235. clang::DiagnosticsEngine::Level /*level*/, llvm::StringRef /*message*/,
  236. llvm::ArrayRef<clang::CharSourceRange> /*ranges*/,
  237. clang::DiagOrStoredDiag /*info*/) override {}
  238. void emitDiagnosticLoc(
  239. clang::FullSourceLoc /*loc*/, clang::PresumedLoc /*ploc*/,
  240. clang::DiagnosticsEngine::Level /*level*/,
  241. llvm::ArrayRef<clang::CharSourceRange> /*ranges*/) override {}
  242. // emitCodeContext is inherited from clang::TextDiagnostic.
  243. void emitIncludeLocation(clang::FullSourceLoc /*loc*/,
  244. clang::PresumedLoc /*ploc*/) override {}
  245. void emitImportLocation(clang::FullSourceLoc /*loc*/,
  246. clang::PresumedLoc /*ploc*/,
  247. llvm::StringRef /*module_name*/) override {}
  248. void emitBuildingModuleLocation(clang::FullSourceLoc /*loc*/,
  249. clang::PresumedLoc /*ploc*/,
  250. llvm::StringRef /*module_name*/) override {}
  251. // beginDiagnostic and endDiagnostic are inherited from
  252. // clang::TextDiagnostic in case it wants to do any setup / teardown work.
  253. };
  254. // Information on a Clang diagnostic that can be converted to a Carbon
  255. // diagnostic.
  256. struct ClangDiagnosticInfo {
  257. // The Clang diagnostic level.
  258. clang::DiagnosticsEngine::Level level;
  259. // The ID of the ImportIR instruction referring to the Clang source
  260. // location.
  261. SemIR::ImportIRInstId import_ir_inst_id;
  262. // The Clang diagnostic textual message.
  263. std::string message;
  264. // The code snippet produced by clang.
  265. std::string snippet;
  266. };
  267. // The Carbon file that this C++ compilation is attached to.
  268. SemIR::File* sem_ir_;
  269. // The diagnostic emitter that we're emitting diagnostics into.
  270. DiagnosticEmitterBase* emitter_;
  271. // The compiler invocation that is producing the diagnostics.
  272. std::shared_ptr<clang::CompilerInvocation> invocation_;
  273. // Collects the information for all Clang diagnostics to be converted to
  274. // Carbon diagnostics after the context has been initialized with the Clang
  275. // AST.
  276. llvm::SmallVector<ClangDiagnosticInfo> diagnostic_infos_;
  277. };
  278. // A wrapper around a clang::CompilerInvocation that allows us to make a shallow
  279. // copy of most of the invocation and only make a deep copy of the parts that we
  280. // want to change.
  281. //
  282. // clang::CowCompilerInvocation almost allows this, but doesn't derive from
  283. // CompilerInvocation or support shallow copies from a CompilerInvocation, so is
  284. // not useful to us as we can't build an ASTUnit from it.
  285. class ShallowCopyCompilerInvocation : public clang::CompilerInvocation {
  286. public:
  287. explicit ShallowCopyCompilerInvocation(
  288. const clang::CompilerInvocation& invocation) {
  289. shallow_copy_assign(invocation);
  290. // Make a deep copy of options that we modify.
  291. FrontendOpts = std::make_shared<clang::FrontendOptions>(*FrontendOpts);
  292. PPOpts = std::make_shared<clang::PreprocessorOptions>(*PPOpts);
  293. }
  294. };
  295. // An AST consumer that tracks top-level declarations so they can be handed off
  296. // to code generation later.
  297. class BufferingConsumer : public clang::ASTConsumer {
  298. public:
  299. explicit BufferingConsumer(SemIR::CppFile& file) : file_(&file) {}
  300. auto HandleTopLevelDecl(clang::DeclGroupRef decl_group) -> bool override {
  301. file_->decl_groups().push_back(decl_group);
  302. return true;
  303. }
  304. private:
  305. SemIR::CppFile* file_;
  306. };
  307. // An action and a set of registered Clang callbacks used to generate an AST
  308. // from a set of Cpp imports.
  309. class GenerateASTAction : public clang::ASTFrontendAction {
  310. public:
  311. explicit GenerateASTAction(Context& context) : context_(&context) {}
  312. protected:
  313. auto CreateASTConsumer(clang::CompilerInstance& /*clang_instance*/,
  314. llvm::StringRef /*file*/)
  315. -> std::unique_ptr<clang::ASTConsumer> override {
  316. return std::make_unique<BufferingConsumer>(*context_->sem_ir().cpp_file());
  317. }
  318. auto BeginSourceFileAction(clang::CompilerInstance& /*clang_instance*/)
  319. -> bool override {
  320. // TODO: Consider creating an `ExternalSemaSource` here and attaching it to
  321. // the compilation.
  322. // TODO: `clang.getPreprocessor().enableIncrementalProcessing();` to avoid
  323. // the TU scope getting torn down before we're done parsing macros.
  324. return true;
  325. }
  326. // Parse the imports and inline C++ fragments. This is notionally very similar
  327. // to `clang::ParseAST`, which `ASTFrontendAction::ExecuteAction` calls, but
  328. // this version doesn't parse C++20 modules and stops just before reaching the
  329. // end of the translation unit.
  330. auto ExecuteAction() -> void override {
  331. clang::CompilerInstance& clang_instance = getCompilerInstance();
  332. clang_instance.createSema(getTranslationUnitKind(),
  333. /*CompletionConsumer=*/nullptr);
  334. context_->cpp_context()->set_parser(std::make_unique<clang::Parser>(
  335. clang_instance.getPreprocessor(), clang_instance.getSema(),
  336. /*SkipFunctionBodies=*/false));
  337. auto& parser = context_->cpp_context()->parser();
  338. clang_instance.getPreprocessor().EnterMainSourceFile();
  339. if (auto* source = clang_instance.getASTContext().getExternalSource()) {
  340. source->StartTranslationUnit(&clang_instance.getASTConsumer());
  341. }
  342. parser.Initialize();
  343. clang_instance.getSema().ActOnStartOfTranslationUnit();
  344. // Don't allow C++20 module declarations in inline Cpp code fragments.
  345. auto module_import_state = clang::Sema::ModuleImportState::NotACXX20Module;
  346. // Parse top-level declarations until we see EOF. Do not parse EOF, as that
  347. // will cause the parser to end the translation unit prematurely.
  348. while (parser.getCurToken().isNot(clang::tok::eof)) {
  349. clang::Parser::DeclGroupPtrTy decl_group;
  350. bool eof = parser.ParseTopLevelDecl(decl_group, module_import_state);
  351. CARBON_CHECK(!eof);
  352. if (decl_group && !clang_instance.getASTConsumer().HandleTopLevelDecl(
  353. decl_group.get())) {
  354. break;
  355. }
  356. }
  357. }
  358. private:
  359. Context* context_;
  360. };
  361. } // namespace
  362. auto GenerateAst(Context& context,
  363. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  364. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  365. std::shared_ptr<clang::CompilerInvocation> base_invocation)
  366. -> bool {
  367. CARBON_CHECK(!context.cpp_context());
  368. CARBON_CHECK(!context.sem_ir().cpp_file());
  369. auto invocation =
  370. std::make_shared<ShallowCopyCompilerInvocation>(*base_invocation);
  371. // Ask Clang to not leak memory.
  372. invocation->getFrontendOpts().DisableFree = false;
  373. // Build a diagnostics engine.
  374. llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diags(
  375. clang::CompilerInstance::createDiagnostics(
  376. *fs, invocation->getDiagnosticOpts(),
  377. new CarbonClangDiagnosticConsumer(context, invocation),
  378. /*ShouldOwnClient=*/true));
  379. // Extract the input from the frontend invocation and make sure it makes
  380. // sense.
  381. const auto& inputs = invocation->getFrontendOpts().Inputs;
  382. CARBON_CHECK(inputs.size() == 1 &&
  383. inputs[0].getKind().getLanguage() == clang::Language::CXX &&
  384. inputs[0].getKind().getFormat() == clang::InputKind::Source);
  385. llvm::StringRef file_name = inputs[0].getFile();
  386. // Remap the imports file name to the corresponding `#include`s.
  387. // TODO: Modify the frontend options to specify this memory buffer as input
  388. // instead of remapping the file.
  389. std::string includes = GenerateCppIncludesHeaderCode(context, imports);
  390. auto includes_buffer =
  391. llvm::MemoryBuffer::getMemBufferCopy(includes, file_name);
  392. invocation->getPreprocessorOpts().addRemappedFile(file_name,
  393. includes_buffer.release());
  394. clang::DiagnosticErrorTrap trap(*diags);
  395. auto clang_instance_ptr =
  396. std::make_unique<clang::CompilerInstance>(invocation);
  397. auto& clang_instance = *clang_instance_ptr;
  398. context.sem_ir().set_cpp_file(
  399. std::make_unique<SemIR::CppFile>(std::move(clang_instance_ptr)));
  400. clang_instance.setDiagnostics(diags);
  401. clang_instance.setVirtualFileSystem(fs);
  402. clang_instance.createFileManager();
  403. clang_instance.createSourceManager();
  404. if (!clang_instance.createTarget()) {
  405. return false;
  406. }
  407. context.set_cpp_context(std::make_unique<CppContext>(
  408. std::make_unique<GenerateASTAction>(context)));
  409. if (!context.cpp_context()->action().BeginSourceFile(clang_instance,
  410. inputs[0])) {
  411. return false;
  412. }
  413. if (llvm::Error error = context.cpp_context()->action().Execute()) {
  414. // `Execute` currently never fails, but its contract allows it to.
  415. context.TODO(SemIR::LocId::None, "failed to execute clang action: " +
  416. llvm::toString(std::move(error)));
  417. return false;
  418. }
  419. // Flush any diagnostics. We know we're not part-way through emitting a
  420. // diagnostic now.
  421. context.emitter().Flush();
  422. return !trap.hasErrorOccurred();
  423. }
  424. auto FinishAst(Context& context) -> void {
  425. if (!context.cpp_context()) {
  426. return;
  427. }
  428. context.cpp_context()->sema().ActOnEndOfTranslationUnit();
  429. // We don't call FrontendAction::EndSourceFile, because that destroys the AST.
  430. context.set_cpp_context(nullptr);
  431. context.emitter().Flush();
  432. }
  433. } // namespace Carbon::Check