import_cpp.cpp 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823
  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/import_cpp.h"
  5. #include <memory>
  6. #include <optional>
  7. #include <string>
  8. #include <tuple>
  9. #include <utility>
  10. #include "clang/AST/ASTContext.h"
  11. #include "clang/AST/RecordLayout.h"
  12. #include "clang/Basic/FileManager.h"
  13. #include "clang/Frontend/ASTUnit.h"
  14. #include "clang/Frontend/CompilerInstance.h"
  15. #include "clang/Frontend/CompilerInvocation.h"
  16. #include "clang/Frontend/TextDiagnostic.h"
  17. #include "clang/Lex/PreprocessorOptions.h"
  18. #include "clang/Sema/Lookup.h"
  19. #include "common/check.h"
  20. #include "common/ostream.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/class.h"
  27. #include "toolchain/check/context.h"
  28. #include "toolchain/check/convert.h"
  29. #include "toolchain/check/cpp_thunk.h"
  30. #include "toolchain/check/diagnostic_helpers.h"
  31. #include "toolchain/check/eval.h"
  32. #include "toolchain/check/function.h"
  33. #include "toolchain/check/import.h"
  34. #include "toolchain/check/inst.h"
  35. #include "toolchain/check/literal.h"
  36. #include "toolchain/check/pattern.h"
  37. #include "toolchain/check/pattern_match.h"
  38. #include "toolchain/check/type.h"
  39. #include "toolchain/check/type_completion.h"
  40. #include "toolchain/diagnostics/diagnostic.h"
  41. #include "toolchain/diagnostics/diagnostic_emitter.h"
  42. #include "toolchain/diagnostics/format_providers.h"
  43. #include "toolchain/parse/node_ids.h"
  44. #include "toolchain/sem_ir/clang_decl.h"
  45. #include "toolchain/sem_ir/class.h"
  46. #include "toolchain/sem_ir/function.h"
  47. #include "toolchain/sem_ir/ids.h"
  48. #include "toolchain/sem_ir/inst.h"
  49. #include "toolchain/sem_ir/name_scope.h"
  50. #include "toolchain/sem_ir/typed_insts.h"
  51. namespace Carbon::Check {
  52. // Add a line marker directive pointing at the location of the `import Cpp`
  53. // declaration in the Carbon source file. This will cause Clang's diagnostics
  54. // machinery to track and report the location in Carbon code where the import
  55. // was written.
  56. static auto GenerateLineMarker(Context& context, llvm::raw_ostream& out,
  57. int line) {
  58. out << "# " << line << " \""
  59. << FormatEscaped(context.tokens().source().filename()) << "\"\n";
  60. }
  61. // Generates C++ file contents to #include all requested imports.
  62. static auto GenerateCppIncludesHeaderCode(
  63. Context& context, llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  64. -> std::string {
  65. std::string code;
  66. llvm::raw_string_ostream code_stream(code);
  67. for (const Parse::Tree::PackagingNames& import : imports) {
  68. if (import.inline_body_id.has_value()) {
  69. // Expand `import Cpp inline "code";` directly into the specified code.
  70. auto code_token = context.parse_tree().node_token(import.inline_body_id);
  71. // Compute the line number on which the C++ code starts. Usually the code
  72. // is specified as a block string literal and starts on the line after the
  73. // start of the string token.
  74. // TODO: Determine if this is a block string literal without calling
  75. // `GetTokenText`, which re-lexes the string.
  76. int line = context.tokens().GetLineNumber(code_token);
  77. if (context.tokens().GetTokenText(code_token).contains('\n')) {
  78. ++line;
  79. }
  80. GenerateLineMarker(context, code_stream, line);
  81. code_stream << context.string_literal_values().Get(
  82. context.tokens().GetStringLiteralValue(code_token))
  83. << "\n";
  84. // TODO: Inject a clang pragma here to produce an error if there are
  85. // unclosed scopes at the end of this inline C++ fragment.
  86. } else {
  87. // Translate `import Cpp library "foo.h";` into `#include "foo.h"`.
  88. GenerateLineMarker(context, code_stream,
  89. context.tokens().GetLineNumber(
  90. context.parse_tree().node_token(import.node_id)));
  91. code_stream << "#include \""
  92. << FormatEscaped(
  93. context.string_literal_values().Get(import.library_id))
  94. << "\"\n";
  95. }
  96. }
  97. return code;
  98. }
  99. // Adds the name to the scope with the given `access_kind` and `inst_id`.
  100. // `inst_id` must have a value.
  101. static auto AddNameToScope(Context& context, SemIR::NameScopeId scope_id,
  102. SemIR::NameId name_id, SemIR::AccessKind access_kind,
  103. SemIR::InstId inst_id) -> void {
  104. CARBON_CHECK(inst_id.has_value());
  105. context.name_scopes().Get(scope_id).AddRequired(
  106. {.name_id = name_id,
  107. .result = SemIR::ScopeLookupResult::MakeFound(inst_id, access_kind)});
  108. }
  109. // Maps a Clang name to a Carbon `NameId`.
  110. static auto AddIdentifierName(Context& context, llvm::StringRef name)
  111. -> SemIR::NameId {
  112. return SemIR::NameId::ForIdentifier(context.identifiers().Add(name));
  113. }
  114. // Adds the given source location and an `ImportIRInst` referring to it in
  115. // `ImportIRId::Cpp`.
  116. static auto AddImportIRInst(SemIR::File& file,
  117. clang::SourceLocation clang_source_loc)
  118. -> SemIR::ImportIRInstId {
  119. SemIR::ClangSourceLocId clang_source_loc_id =
  120. file.clang_source_locs().Add(clang_source_loc);
  121. return file.import_ir_insts().Add(SemIR::ImportIRInst(clang_source_loc_id));
  122. }
  123. namespace {
  124. // Used to convert Clang diagnostics to Carbon diagnostics.
  125. //
  126. // Handling of Clang notes is a little subtle: as far as Clang is concerned,
  127. // notes are separate diagnostics, not connected to the error or warning that
  128. // precedes them. But in Carbon's diagnostics system, notes are part of the
  129. // enclosing diagnostic. To handle this, we buffer Clang diagnostics until we
  130. // reach a point where we know we're not in the middle of a diagnostic, and then
  131. // emit a diagnostic along with all of its notes. This is triggered when adding
  132. // or removing a Carbon context note, which could otherwise get attached to the
  133. // wrong C++ diagnostics, and at the end of the Carbon program.
  134. class CarbonClangDiagnosticConsumer : public clang::DiagnosticConsumer {
  135. public:
  136. // Creates an instance with the location that triggers calling Clang. The
  137. // `context` is not stored here, and the diagnostics consumer is expected to
  138. // outlive it.
  139. explicit CarbonClangDiagnosticConsumer(
  140. Context& context, std::shared_ptr<clang::CompilerInvocation> invocation)
  141. : sem_ir_(&context.sem_ir()),
  142. emitter_(&context.emitter()),
  143. invocation_(std::move(invocation)) {
  144. emitter_->AddFlushFn([this] { EmitDiagnostics(); });
  145. }
  146. ~CarbonClangDiagnosticConsumer() override {
  147. // Do not inspect `emitter_` here; it's typically destroyed before the
  148. // consumer is.
  149. // TODO: If Clang produces diagnostics after check finishes, they'll get
  150. // added to the list of pending diagnostics and never emitted.
  151. CARBON_CHECK(diagnostic_infos_.empty(),
  152. "Missing flush before destroying diagnostic consumer");
  153. }
  154. // Generates a Carbon warning for each Clang warning and a Carbon error for
  155. // each Clang error or fatal.
  156. auto HandleDiagnostic(clang::DiagnosticsEngine::Level diag_level,
  157. const clang::Diagnostic& info) -> void override {
  158. DiagnosticConsumer::HandleDiagnostic(diag_level, info);
  159. SemIR::ImportIRInstId clang_import_ir_inst_id =
  160. AddImportIRInst(*sem_ir_, info.getLocation());
  161. llvm::SmallString<256> message;
  162. info.FormatDiagnostic(message);
  163. // Render a code snippet including any highlighted ranges and fixit hints.
  164. // TODO: Also include the #include stack and macro expansion stack in the
  165. // diagnostic output in some way.
  166. RawStringOstream snippet_stream;
  167. if (!info.hasSourceManager()) {
  168. // If we don't have a source manager, this is an error from early in the
  169. // frontend. Don't produce a snippet.
  170. CARBON_CHECK(info.getLocation().isInvalid());
  171. } else {
  172. CodeContextRenderer(snippet_stream, invocation_->getLangOpts(),
  173. invocation_->getDiagnosticOpts())
  174. .emitDiagnostic(
  175. clang::FullSourceLoc(info.getLocation(), info.getSourceManager()),
  176. diag_level, message, info.getRanges(), info.getFixItHints());
  177. }
  178. diagnostic_infos_.push_back({.level = diag_level,
  179. .import_ir_inst_id = clang_import_ir_inst_id,
  180. .message = message.str().str(),
  181. .snippet = snippet_stream.TakeStr()});
  182. }
  183. // Returns the diagnostic to use for a given Clang diagnostic level.
  184. static auto GetDiagnostic(clang::DiagnosticsEngine::Level level)
  185. -> const Diagnostics::DiagnosticBase<std::string>& {
  186. switch (level) {
  187. case clang::DiagnosticsEngine::Ignored: {
  188. CARBON_FATAL("Emitting an ignored diagnostic");
  189. break;
  190. }
  191. case clang::DiagnosticsEngine::Note: {
  192. CARBON_DIAGNOSTIC(CppInteropParseNote, Note, "{0}", std::string);
  193. return CppInteropParseNote;
  194. }
  195. case clang::DiagnosticsEngine::Remark:
  196. case clang::DiagnosticsEngine::Warning: {
  197. // TODO: Add a distinct Remark level to Carbon diagnostics, and stop
  198. // mapping remarks to warnings.
  199. CARBON_DIAGNOSTIC(CppInteropParseWarning, Warning, "{0}", std::string);
  200. return CppInteropParseWarning;
  201. }
  202. case clang::DiagnosticsEngine::Error:
  203. case clang::DiagnosticsEngine::Fatal: {
  204. CARBON_DIAGNOSTIC(CppInteropParseError, Error, "{0}", std::string);
  205. return CppInteropParseError;
  206. }
  207. }
  208. }
  209. // Outputs Carbon diagnostics based on the collected Clang diagnostics. Must
  210. // be called after the AST is set in the context.
  211. auto EmitDiagnostics() -> void {
  212. CARBON_CHECK(sem_ir_->clang_ast_unit(),
  213. "Attempted to emit diagnostics before the AST Unit is loaded");
  214. for (size_t i = 0; i != diagnostic_infos_.size(); ++i) {
  215. const ClangDiagnosticInfo& info = diagnostic_infos_[i];
  216. auto builder = emitter_->Build(SemIR::LocId(info.import_ir_inst_id),
  217. GetDiagnostic(info.level), info.message);
  218. builder.OverrideSnippet(info.snippet);
  219. for (; i + 1 < diagnostic_infos_.size() &&
  220. diagnostic_infos_[i + 1].level == clang::DiagnosticsEngine::Note;
  221. ++i) {
  222. const ClangDiagnosticInfo& note_info = diagnostic_infos_[i + 1];
  223. builder
  224. .Note(SemIR::LocId(note_info.import_ir_inst_id),
  225. GetDiagnostic(note_info.level), note_info.message)
  226. .OverrideSnippet(note_info.snippet);
  227. }
  228. // TODO: This will apply all current Carbon annotation functions. We
  229. // should instead track how Clang's context notes and Carbon's annotation
  230. // functions are interleaved, and interleave the notes in the same order.
  231. builder.Emit();
  232. }
  233. diagnostic_infos_.clear();
  234. }
  235. private:
  236. // A diagnostics renderer based on clang's TextDiagnostic that captures just
  237. // the code context (the snippet).
  238. class CodeContextRenderer : public clang::TextDiagnostic {
  239. public:
  240. using TextDiagnostic::TextDiagnostic;
  241. void emitDiagnosticMessage(
  242. clang::FullSourceLoc /*loc*/, clang::PresumedLoc /*ploc*/,
  243. clang::DiagnosticsEngine::Level /*level*/, llvm::StringRef /*message*/,
  244. llvm::ArrayRef<clang::CharSourceRange> /*ranges*/,
  245. clang::DiagOrStoredDiag /*info*/) override {}
  246. void emitDiagnosticLoc(
  247. clang::FullSourceLoc /*loc*/, clang::PresumedLoc /*ploc*/,
  248. clang::DiagnosticsEngine::Level /*level*/,
  249. llvm::ArrayRef<clang::CharSourceRange> /*ranges*/) override {}
  250. // emitCodeContext is inherited from clang::TextDiagnostic.
  251. void emitIncludeLocation(clang::FullSourceLoc /*loc*/,
  252. clang::PresumedLoc /*ploc*/) override {}
  253. void emitImportLocation(clang::FullSourceLoc /*loc*/,
  254. clang::PresumedLoc /*ploc*/,
  255. llvm::StringRef /*module_name*/) override {}
  256. void emitBuildingModuleLocation(clang::FullSourceLoc /*loc*/,
  257. clang::PresumedLoc /*ploc*/,
  258. llvm::StringRef /*module_name*/) override {}
  259. // beginDiagnostic and endDiagnostic are inherited from
  260. // clang::TextDiagnostic in case it wants to do any setup / teardown work.
  261. };
  262. // Information on a Clang diagnostic that can be converted to a Carbon
  263. // diagnostic.
  264. struct ClangDiagnosticInfo {
  265. // The Clang diagnostic level.
  266. clang::DiagnosticsEngine::Level level;
  267. // The ID of the ImportIR instruction referring to the Clang source
  268. // location.
  269. SemIR::ImportIRInstId import_ir_inst_id;
  270. // The Clang diagnostic textual message.
  271. std::string message;
  272. // The code snippet produced by clang.
  273. std::string snippet;
  274. };
  275. // The Carbon file that this C++ compilation is attached to.
  276. SemIR::File* sem_ir_;
  277. // The diagnostic emitter that we're emitting diagnostics into.
  278. DiagnosticEmitterBase* emitter_;
  279. // The compiler invocation that is producing the diagnostics.
  280. std::shared_ptr<clang::CompilerInvocation> invocation_;
  281. // Collects the information for all Clang diagnostics to be converted to
  282. // Carbon diagnostics after the context has been initialized with the Clang
  283. // AST.
  284. llvm::SmallVector<ClangDiagnosticInfo> diagnostic_infos_;
  285. };
  286. // A wrapper around a clang::CompilerInvocation that allows us to make a shallow
  287. // copy of most of the invocation and only make a deep copy of the parts that we
  288. // want to change.
  289. //
  290. // clang::CowCompilerInvocation almost allows this, but doesn't derive from
  291. // CompilerInvocation or support shallow copies from a CompilerInvocation, so is
  292. // not useful to us as we can't build an ASTUnit from it.
  293. class ShallowCopyCompilerInvocation : public clang::CompilerInvocation {
  294. public:
  295. explicit ShallowCopyCompilerInvocation(
  296. const clang::CompilerInvocation& invocation) {
  297. shallow_copy_assign(invocation);
  298. // The preprocessor options are modified to hold a replacement includes
  299. // buffer, so make our own version of those options.
  300. PPOpts = std::make_shared<clang::PreprocessorOptions>(*PPOpts);
  301. }
  302. };
  303. } // namespace
  304. // Returns an AST for the C++ imports and a bool that represents whether
  305. // compilation errors where encountered or the generated AST is null due to an
  306. // error. Sets the AST in the context's `sem_ir`.
  307. // TODO: Consider to always have a (non-null) AST.
  308. static auto GenerateAst(
  309. Context& context, llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  310. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  311. std::shared_ptr<clang::CompilerInvocation> base_invocation)
  312. -> std::pair<std::unique_ptr<clang::ASTUnit>, bool> {
  313. auto invocation =
  314. std::make_shared<ShallowCopyCompilerInvocation>(*base_invocation);
  315. // Build a diagnostics engine.
  316. llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diags(
  317. clang::CompilerInstance::createDiagnostics(
  318. *fs, invocation->getDiagnosticOpts(),
  319. new CarbonClangDiagnosticConsumer(context, invocation),
  320. /*ShouldOwnClient=*/true));
  321. // Extract the input from the frontend invocation and make sure it makes
  322. // sense.
  323. const auto& inputs = invocation->getFrontendOpts().Inputs;
  324. CARBON_CHECK(inputs.size() == 1 &&
  325. inputs[0].getKind().getLanguage() == clang::Language::CXX &&
  326. inputs[0].getKind().getFormat() == clang::InputKind::Source);
  327. llvm::StringRef file_name = inputs[0].getFile();
  328. // Remap the imports file name to the corresponding `#include`s.
  329. // TODO: Modify the frontend options to specify this memory buffer as input
  330. // instead of remapping the file.
  331. std::string includes = GenerateCppIncludesHeaderCode(context, imports);
  332. auto includes_buffer =
  333. llvm::MemoryBuffer::getMemBufferCopy(includes, file_name);
  334. invocation->getPreprocessorOpts().addRemappedFile(file_name,
  335. includes_buffer.release());
  336. clang::DiagnosticErrorTrap trap(*diags);
  337. // Create the AST unit.
  338. auto ast = clang::ASTUnit::LoadFromCompilerInvocation(
  339. invocation, std::make_shared<clang::PCHContainerOperations>(), nullptr,
  340. diags, new clang::FileManager(invocation->getFileSystemOpts(), fs));
  341. // Attach the AST to SemIR. This needs to be done before we can emit any
  342. // diagnostics, so their locations can be properly interpreted by our
  343. // diagnostics machinery.
  344. context.sem_ir().set_clang_ast_unit(ast.get());
  345. // Emit any diagnostics we queued up while building the AST.
  346. context.emitter().Flush();
  347. return {std::move(ast), !ast || trap.hasErrorOccurred()};
  348. }
  349. // Adds a namespace for the `Cpp` import and returns its `NameScopeId`.
  350. static auto AddNamespace(Context& context, PackageNameId cpp_package_id,
  351. llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  352. -> SemIR::NameScopeId {
  353. auto& import_cpps = context.sem_ir().import_cpps();
  354. import_cpps.Reserve(imports.size());
  355. for (const Parse::Tree::PackagingNames& import : imports) {
  356. import_cpps.Add({.node_id = context.parse_tree().As<Parse::ImportDeclId>(
  357. import.node_id),
  358. .library_id = import.library_id});
  359. }
  360. return AddImportNamespaceToScope(
  361. context,
  362. GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  363. SemIR::NameId::ForPackageName(cpp_package_id),
  364. SemIR::NameScopeId::Package,
  365. /*diagnose_duplicate_namespace=*/false,
  366. [&]() {
  367. return AddInst<SemIR::ImportCppDecl>(
  368. context,
  369. context.parse_tree().As<Parse::ImportDeclId>(
  370. imports.front().node_id),
  371. {});
  372. })
  373. .add_result.name_scope_id;
  374. }
  375. auto ImportCppFiles(Context& context,
  376. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  377. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  378. std::shared_ptr<clang::CompilerInvocation> invocation)
  379. -> std::unique_ptr<clang::ASTUnit> {
  380. if (imports.empty()) {
  381. return nullptr;
  382. }
  383. CARBON_CHECK(!context.sem_ir().clang_ast_unit());
  384. PackageNameId package_id = imports.front().package_id;
  385. CARBON_CHECK(
  386. llvm::all_of(imports, [&](const Parse::Tree::PackagingNames& import) {
  387. return import.package_id == package_id;
  388. }));
  389. auto name_scope_id = AddNamespace(context, package_id, imports);
  390. auto [generated_ast, ast_has_error] =
  391. GenerateAst(context, imports, fs, std::move(invocation));
  392. SemIR::NameScope& name_scope = context.name_scopes().Get(name_scope_id);
  393. name_scope.set_is_closed_import(true);
  394. name_scope.set_clang_decl_context_id(context.sem_ir().clang_decls().Add(
  395. {.decl = generated_ast->getASTContext().getTranslationUnitDecl(),
  396. .inst_id = name_scope.inst_id()}));
  397. if (ast_has_error) {
  398. name_scope.set_has_error();
  399. }
  400. return std::move(generated_ast);
  401. }
  402. // Looks up the given name in the Clang AST in a specific scope. Returns the
  403. // lookup result if lookup was successful.
  404. static auto ClangLookupName(Context& context, SemIR::NameScopeId scope_id,
  405. SemIR::NameId name_id)
  406. -> std::optional<clang::LookupResult> {
  407. std::optional<llvm::StringRef> name =
  408. context.names().GetAsStringIfIdentifier(name_id);
  409. if (!name) {
  410. // Special names never exist in C++ code.
  411. return std::nullopt;
  412. }
  413. clang::ASTUnit* ast = context.sem_ir().clang_ast_unit();
  414. CARBON_CHECK(ast);
  415. clang::Sema& sema = ast->getSema();
  416. // TODO: Map the LocId of the lookup to a clang SourceLocation and provide it
  417. // here so that clang's diagnostics can point into the carbon code that uses
  418. // the name.
  419. clang::LookupResult lookup(
  420. sema,
  421. clang::DeclarationNameInfo(
  422. clang::DeclarationName(
  423. sema.getPreprocessor().getIdentifierInfo(*name)),
  424. clang::SourceLocation()),
  425. clang::Sema::LookupNameKind::LookupOrdinaryName);
  426. auto scope_clang_decl_context_id =
  427. context.name_scopes().Get(scope_id).clang_decl_context_id();
  428. bool found = sema.LookupQualifiedName(
  429. lookup, dyn_cast<clang::DeclContext>(context.sem_ir()
  430. .clang_decls()
  431. .Get(scope_clang_decl_context_id)
  432. .decl));
  433. if (!found) {
  434. return std::nullopt;
  435. }
  436. return lookup;
  437. }
  438. // Looks up for constructors in the class scope and returns the lookup result.
  439. static auto ClangConstructorLookup(const Context& context,
  440. SemIR::NameScopeId scope_id)
  441. -> clang::DeclContextLookupResult {
  442. const SemIR::NameScope& scope = context.sem_ir().name_scopes().Get(scope_id);
  443. clang::Sema& sema = context.sem_ir().clang_ast_unit()->getSema();
  444. clang::Decl* decl =
  445. context.sem_ir().clang_decls().Get(scope.clang_decl_context_id()).decl;
  446. return sema.LookupConstructors(cast<clang::CXXRecordDecl>(decl));
  447. }
  448. // Returns true if the given Clang declaration is the implicit injected class
  449. // name within the class.
  450. static auto IsDeclInjectedClassName(const Context& context,
  451. SemIR::NameScopeId scope_id,
  452. SemIR::NameId name_id,
  453. const clang::NamedDecl* named_decl)
  454. -> bool {
  455. if (!named_decl->isImplicit()) {
  456. return false;
  457. }
  458. const auto* record_decl = dyn_cast<clang::CXXRecordDecl>(named_decl);
  459. if (!record_decl) {
  460. return false;
  461. }
  462. const SemIR::ClangDecl& clang_decl = context.sem_ir().clang_decls().Get(
  463. context.sem_ir().name_scopes().Get(scope_id).clang_decl_context_id());
  464. const auto* scope_record_decl = cast<clang::CXXRecordDecl>(clang_decl.decl);
  465. const clang::ASTContext& ast_context =
  466. context.sem_ir().clang_ast_unit()->getASTContext();
  467. CARBON_CHECK(
  468. ast_context.getCanonicalType(
  469. ast_context.getRecordType(scope_record_decl)) ==
  470. ast_context.getCanonicalType(ast_context.getRecordType(record_decl)));
  471. auto class_decl =
  472. context.sem_ir().insts().GetAs<SemIR::ClassDecl>(clang_decl.inst_id);
  473. CARBON_CHECK(name_id ==
  474. context.sem_ir().classes().Get(class_decl.class_id).name_id);
  475. return true;
  476. }
  477. // Looks up the given name in the Clang AST in a specific scope, and returns the
  478. // found declaration and its access. If the found declaration is the injected
  479. // class name, looks up constructors instead. If not found, returns `nullopt`.
  480. // If there's not a single result, returns `nullptr` and default access.
  481. // Otherwise, returns the single declaration and its access.
  482. static auto ClangLookup(Context& context, SemIR::LocId loc_id,
  483. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  484. -> std::optional<std::tuple<clang::NamedDecl*, clang::AccessSpecifier>> {
  485. auto lookup = ClangLookupName(context, scope_id, name_id);
  486. if (!lookup) {
  487. return std::nullopt;
  488. }
  489. std::tuple<clang::NamedDecl*, clang::AccessSpecifier> result{
  490. nullptr, clang::AccessSpecifier::AS_none};
  491. // Access checks are performed separately by the Carbon name lookup logic.
  492. lookup->suppressAccessDiagnostics();
  493. if (!lookup->isSingleResult()) {
  494. // Clang will diagnose ambiguous lookup results for us.
  495. if (!lookup->isAmbiguous()) {
  496. context.TODO(loc_id,
  497. llvm::formatv("Unsupported: Lookup succeeded but couldn't "
  498. "find a single result; LookupResultKind: {0}",
  499. static_cast<int>(lookup->getResultKind())));
  500. }
  501. return result;
  502. }
  503. if (!IsDeclInjectedClassName(context, scope_id, name_id,
  504. lookup->getFoundDecl())) {
  505. result = {lookup->getFoundDecl(), lookup->begin().getAccess()};
  506. return result;
  507. }
  508. clang::DeclContextLookupResult constructors_lookup =
  509. ClangConstructorLookup(context, scope_id);
  510. llvm::SmallVector<clang::CXXConstructorDecl*> constructors;
  511. for (clang::Decl* decl : constructors_lookup) {
  512. auto* constructor = cast<clang::CXXConstructorDecl>(decl);
  513. if (constructor->isDeleted() || constructor->isCopyOrMoveConstructor()) {
  514. continue;
  515. }
  516. constructors.push_back(constructor);
  517. }
  518. if (constructors.size() != 1) {
  519. context.TODO(
  520. loc_id,
  521. llvm::formatv("Unsupported: Constructors lookup succeeded but couldn't "
  522. "find a single result; Found {0} constructors",
  523. constructors.size()));
  524. return result;
  525. }
  526. result = {constructors[0], constructors[0]->getAccess()};
  527. return result;
  528. }
  529. // Returns whether `decl` already mapped to an instruction.
  530. static auto IsClangDeclImported(const Context& context, clang::Decl* decl)
  531. -> bool {
  532. return context.sem_ir()
  533. .clang_decls()
  534. .Lookup(decl->getCanonicalDecl())
  535. .has_value();
  536. }
  537. // If `decl` already mapped to an instruction, returns that instruction.
  538. // Otherwise returns `None`.
  539. static auto LookupClangDeclInstId(const Context& context, clang::Decl* decl)
  540. -> SemIR::InstId {
  541. const auto& clang_decls = context.sem_ir().clang_decls();
  542. if (auto context_clang_decl_id = clang_decls.Lookup(decl->getCanonicalDecl());
  543. context_clang_decl_id.has_value()) {
  544. return clang_decls.Get(context_clang_decl_id).inst_id;
  545. }
  546. return SemIR::InstId::None;
  547. }
  548. // Returns the parent of the given declaration. Skips declaration types we
  549. // ignore.
  550. static auto GetParentDecl(clang::Decl* clang_decl) -> clang::Decl* {
  551. return cast<clang::Decl>(
  552. clang_decl->getDeclContext()->getNonTransparentContext());
  553. }
  554. // Returns the given declaration's parent scope. Assumes the parent declaration
  555. // was already imported.
  556. static auto GetParentNameScopeId(Context& context, clang::Decl* clang_decl)
  557. -> SemIR::NameScopeId {
  558. SemIR::InstId parent_inst_id =
  559. LookupClangDeclInstId(context, GetParentDecl(clang_decl));
  560. CARBON_CHECK(parent_inst_id.has_value());
  561. CARBON_KIND_SWITCH(context.insts().Get(parent_inst_id)) {
  562. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  563. return context.classes().Get(class_decl.class_id).scope_id;
  564. }
  565. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  566. return context.interfaces().Get(interface_decl.interface_id).scope_id;
  567. }
  568. case CARBON_KIND(SemIR::Namespace namespace_inst): {
  569. return namespace_inst.name_scope_id;
  570. }
  571. default: {
  572. CARBON_FATAL("Unexpected parent instruction kind");
  573. }
  574. }
  575. }
  576. // Imports a namespace declaration from Clang to Carbon. If successful, returns
  577. // the new Carbon namespace declaration `InstId`. If the declaration was already
  578. // imported, returns the mapped instruction.
  579. static auto ImportNamespaceDecl(Context& context,
  580. clang::NamespaceDecl* clang_decl)
  581. -> SemIR::InstId {
  582. // Check if the declaration is already mapped.
  583. if (SemIR::InstId existing_inst_id =
  584. LookupClangDeclInstId(context, clang_decl);
  585. existing_inst_id.has_value()) {
  586. return existing_inst_id;
  587. }
  588. auto result = AddImportNamespace(
  589. context, GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  590. AddIdentifierName(context, clang_decl->getName()),
  591. GetParentNameScopeId(context, clang_decl),
  592. /*import_id=*/SemIR::InstId::None);
  593. context.name_scopes()
  594. .Get(result.name_scope_id)
  595. .set_clang_decl_context_id(context.sem_ir().clang_decls().Add(
  596. {.decl = clang_decl->getCanonicalDecl(), .inst_id = result.inst_id}));
  597. return result.inst_id;
  598. }
  599. static auto ImportTypeAndDependencies(Context& context, SemIR::LocId loc_id,
  600. clang::QualType type) -> TypeExpr;
  601. // Creates a class declaration for the given class name in the given scope.
  602. // Returns the `InstId` for the declaration.
  603. static auto BuildClassDecl(Context& context,
  604. SemIR::ImportIRInstId import_ir_inst_id,
  605. SemIR::NameScopeId parent_scope_id,
  606. SemIR::NameId name_id)
  607. -> std::tuple<SemIR::ClassId, SemIR::TypeInstId> {
  608. // Add the class declaration.
  609. auto class_decl = SemIR::ClassDecl{.type_id = SemIR::TypeType::TypeId,
  610. .class_id = SemIR::ClassId::None,
  611. .decl_block_id = SemIR::InstBlockId::None};
  612. auto class_decl_id = AddPlaceholderInstInNoBlock(
  613. context,
  614. SemIR::LocIdAndInst::UncheckedLoc(import_ir_inst_id, class_decl));
  615. context.imports().push_back(class_decl_id);
  616. SemIR::Class class_info = {
  617. {.name_id = name_id,
  618. .parent_scope_id = parent_scope_id,
  619. .generic_id = SemIR::GenericId::None,
  620. .first_param_node_id = Parse::NodeId::None,
  621. .last_param_node_id = Parse::NodeId::None,
  622. .pattern_block_id = SemIR::InstBlockId::None,
  623. .implicit_param_patterns_id = SemIR::InstBlockId::None,
  624. .param_patterns_id = SemIR::InstBlockId::None,
  625. .is_extern = false,
  626. .extern_library_id = SemIR::LibraryNameId::None,
  627. .non_owning_decl_id = SemIR::InstId::None,
  628. .first_owning_decl_id = class_decl_id},
  629. {// `.self_type_id` depends on the ClassType, so is set below.
  630. .self_type_id = SemIR::TypeId::None,
  631. // TODO: Support Dynamic classes.
  632. // TODO: Support Final classes.
  633. .inheritance_kind = SemIR::Class::Base}};
  634. class_decl.class_id = context.classes().Add(class_info);
  635. // Write the class ID into the ClassDecl.
  636. ReplaceInstBeforeConstantUse(context, class_decl_id, class_decl);
  637. SetClassSelfType(context, class_decl.class_id);
  638. return {class_decl.class_id, context.types().GetAsTypeInstId(class_decl_id)};
  639. }
  640. // Imports a record declaration from Clang to Carbon. If successful, returns
  641. // the new Carbon class declaration `InstId`.
  642. static auto ImportCXXRecordDecl(Context& context,
  643. clang::CXXRecordDecl* clang_decl)
  644. -> SemIR::InstId {
  645. auto import_ir_inst_id =
  646. AddImportIRInst(context.sem_ir(), clang_decl->getLocation());
  647. auto [class_id, class_inst_id] = BuildClassDecl(
  648. context, import_ir_inst_id, GetParentNameScopeId(context, clang_decl),
  649. AddIdentifierName(context, clang_decl->getName()));
  650. // TODO: The caller does the same lookup. Avoid doing it twice.
  651. auto clang_decl_id = context.sem_ir().clang_decls().Add(
  652. {.decl = clang_decl->getCanonicalDecl(), .inst_id = class_inst_id});
  653. // Name lookup into the Carbon class looks in the C++ class definition.
  654. auto& class_info = context.classes().Get(class_id);
  655. class_info.scope_id = context.name_scopes().Add(
  656. class_inst_id, SemIR::NameId::None, class_info.parent_scope_id);
  657. context.name_scopes()
  658. .Get(class_info.scope_id)
  659. .set_clang_decl_context_id(clang_decl_id);
  660. return class_inst_id;
  661. }
  662. // Determines the Carbon inheritance kind to use for a C++ class definition.
  663. static auto GetInheritanceKind(clang::CXXRecordDecl* class_def)
  664. -> SemIR::Class::InheritanceKind {
  665. if (class_def->isUnion()) {
  666. // Treat all unions as final classes to match their C++ semantics. While we
  667. // could support this, the author of a C++ union has no way to mark their
  668. // type as `final` to prevent it, and so we assume the intent was to
  669. // disallow inheritance.
  670. return SemIR::Class::Final;
  671. }
  672. if (class_def->hasAttr<clang::FinalAttr>()) {
  673. // The class is final in C++; don't allow Carbon types to derive from it.
  674. // Note that such a type might also be abstract in C++; we treat final as
  675. // taking precedence.
  676. //
  677. // We could also treat classes with a final destructor as being final, as
  678. // Clang does when determining whether a class is "effectively final", but
  679. // to keep our rules simpler we do not.
  680. return SemIR::Class::Final;
  681. }
  682. if (class_def->isAbstract()) {
  683. // If the class has any abstract members, it's abstract.
  684. return SemIR::Class::Abstract;
  685. }
  686. // Allow inheritance from any other C++ class type.
  687. return SemIR::Class::Base;
  688. }
  689. // Checks that the specified finished class definition is valid and builds and
  690. // returns a corresponding complete type witness instruction.
  691. static auto ImportClassObjectRepr(Context& context, SemIR::ClassId class_id,
  692. SemIR::ImportIRInstId import_ir_inst_id,
  693. SemIR::TypeInstId class_type_inst_id,
  694. const clang::CXXRecordDecl* clang_def)
  695. -> SemIR::TypeInstId {
  696. // For now, if the class is empty, produce an empty struct as the object
  697. // representation. This allows our tests to continue to pass while we don't
  698. // properly support initializing imported C++ classes.
  699. // TODO: Remove this.
  700. if (clang_def->isEmpty() && !clang_def->getNumBases()) {
  701. return context.types().GetAsTypeInstId(AddInst(
  702. context,
  703. MakeImportedLocIdAndInst(
  704. context, import_ir_inst_id,
  705. SemIR::StructType{.type_id = SemIR::TypeType::TypeId,
  706. .fields_id = SemIR::StructTypeFieldsId::Empty})));
  707. }
  708. const auto& clang_layout =
  709. context.ast_context().getASTRecordLayout(clang_def);
  710. llvm::SmallVector<uint64_t> layout;
  711. llvm::SmallVector<SemIR::StructTypeField> fields;
  712. static_assert(SemIR::CustomLayoutId::SizeIndex == 0);
  713. layout.push_back(clang_layout.getSize().getQuantity());
  714. static_assert(SemIR::CustomLayoutId::AlignIndex == 1);
  715. layout.push_back(clang_layout.getAlignment().getQuantity());
  716. static_assert(SemIR::CustomLayoutId::FirstFieldIndex == 2);
  717. // TODO: Import vptr(s).
  718. // Import bases.
  719. for (const auto& base : clang_def->bases()) {
  720. CARBON_CHECK(!base.isVirtual(),
  721. "Should not import definition for class with a virtual base");
  722. auto [base_type_inst_id, base_type_id] =
  723. ImportTypeAndDependencies(context, import_ir_inst_id, base.getType());
  724. if (!base_type_id.has_value()) {
  725. // TODO: If the base class's type can't be mapped, skip it.
  726. continue;
  727. }
  728. auto base_decl_id = AddInst(
  729. context,
  730. MakeImportedLocIdAndInst(
  731. context, import_ir_inst_id,
  732. SemIR::BaseDecl{.type_id = GetUnboundElementType(
  733. context, class_type_inst_id, base_type_inst_id),
  734. .base_type_inst_id = base_type_inst_id,
  735. .index = SemIR::ElementIndex(fields.size())}));
  736. // If there's exactly one base class, treat it as a Carbon base class too.
  737. // TODO: Improve handling for the case where the class has multiple base
  738. // classes.
  739. if (clang_def->getNumBases() == 1) {
  740. auto& class_info = context.classes().Get(class_id);
  741. CARBON_CHECK(!class_info.base_id.has_value());
  742. class_info.base_id = base_decl_id;
  743. }
  744. auto* base_class = base.getType()->getAsCXXRecordDecl();
  745. CARBON_CHECK(base_class, "Base class {0} is not a class",
  746. base.getType().getAsString());
  747. auto base_offset = base.isVirtual()
  748. ? clang_layout.getVBaseClassOffset(base_class)
  749. : clang_layout.getBaseClassOffset(base_class);
  750. layout.push_back(base_offset.getQuantity());
  751. fields.push_back(
  752. {.name_id = SemIR::NameId::Base, .type_inst_id = base_type_inst_id});
  753. }
  754. // Import fields.
  755. for (auto* decl : clang_def->decls()) {
  756. auto* field = dyn_cast<clang::FieldDecl>(decl);
  757. // Track the chain of fields from the class to this field. This chain is
  758. // only one element long unless the field is a member of an anonymous struct
  759. // or union.
  760. clang::NamedDecl* single_field_chain[1] = {field};
  761. llvm::ArrayRef<clang::NamedDecl*> chain = single_field_chain;
  762. // If this isn't a field, it might be an indirect field in an anonymous
  763. // struct or union.
  764. if (!field) {
  765. auto* indirect_field = dyn_cast<clang::IndirectFieldDecl>(decl);
  766. if (!indirect_field) {
  767. continue;
  768. }
  769. chain = indirect_field->chain();
  770. field = indirect_field->getAnonField();
  771. }
  772. if (field->isBitField()) {
  773. // TODO: Add a representation for named bitfield members.
  774. continue;
  775. }
  776. if (field->isAnonymousStructOrUnion()) {
  777. // Fields within an anonymous structure or union will be added via their
  778. // IndirectFieldDecls.
  779. continue;
  780. }
  781. auto field_name_id = AddIdentifierName(context, field->getName());
  782. auto [field_type_inst_id, field_type_id] =
  783. ImportTypeAndDependencies(context, import_ir_inst_id, field->getType());
  784. if (!field_type_inst_id.has_value()) {
  785. // TODO: For now, just skip over fields whose types we can't map.
  786. continue;
  787. }
  788. // Create a field now, as we know the index to use.
  789. // TODO: Consider doing this lazily instead.
  790. auto field_decl_id = AddInst(
  791. context, MakeImportedLocIdAndInst(
  792. context, import_ir_inst_id,
  793. SemIR::FieldDecl{
  794. .type_id = GetUnboundElementType(
  795. context, class_type_inst_id, field_type_inst_id),
  796. .name_id = field_name_id,
  797. .index = SemIR::ElementIndex(fields.size())}));
  798. context.sem_ir().clang_decls().Add(
  799. {.decl = decl->getCanonicalDecl(), .inst_id = field_decl_id});
  800. // Compute the offset to the field that appears directly in the class.
  801. uint64_t offset = clang_layout.getFieldOffset(
  802. cast<clang::FieldDecl>(chain.front())->getFieldIndex());
  803. // If this is an indirect field, walk the path and accumulate the offset to
  804. // the named field.
  805. for (auto* inner_decl : chain.drop_front()) {
  806. auto* inner_field = cast<clang::FieldDecl>(inner_decl);
  807. const auto& inner_layout =
  808. context.ast_context().getASTRecordLayout(inner_field->getParent());
  809. offset += inner_layout.getFieldOffset(inner_field->getFieldIndex());
  810. }
  811. layout.push_back(
  812. context.ast_context().toCharUnitsFromBits(offset).getQuantity());
  813. fields.push_back(
  814. {.name_id = field_name_id, .type_inst_id = field_type_inst_id});
  815. }
  816. // TODO: Add a field to prevent tail padding reuse if necessary.
  817. return AddTypeInst<SemIR::CustomLayoutType>(
  818. context, import_ir_inst_id,
  819. {.type_id = SemIR::TypeType::TypeId,
  820. .fields_id = context.struct_type_fields().Add(fields),
  821. .layout_id = context.custom_layouts().Add(layout)});
  822. }
  823. // Creates a class definition based on the information in the given Clang
  824. // declaration, which is assumed to be for a class definition.
  825. static auto BuildClassDefinition(Context& context,
  826. SemIR::ImportIRInstId import_ir_inst_id,
  827. SemIR::ClassId class_id,
  828. SemIR::TypeInstId class_inst_id,
  829. clang::CXXRecordDecl* clang_def) -> void {
  830. auto& class_info = context.classes().Get(class_id);
  831. CARBON_CHECK(!class_info.has_definition_started());
  832. class_info.definition_id = class_inst_id;
  833. context.inst_block_stack().Push();
  834. class_info.inheritance_kind = GetInheritanceKind(clang_def);
  835. // Compute the class's object representation.
  836. auto object_repr_id = ImportClassObjectRepr(
  837. context, class_id, import_ir_inst_id, class_inst_id, clang_def);
  838. class_info.complete_type_witness_id = AddInst<SemIR::CompleteTypeWitness>(
  839. context, import_ir_inst_id,
  840. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  841. .object_repr_type_inst_id = object_repr_id});
  842. class_info.body_block_id = context.inst_block_stack().Pop();
  843. }
  844. auto ImportCppClassDefinition(Context& context, SemIR::LocId loc_id,
  845. SemIR::ClassId class_id,
  846. SemIR::ClangDeclId clang_decl_id) -> bool {
  847. clang::ASTUnit* ast = context.sem_ir().clang_ast_unit();
  848. CARBON_CHECK(ast);
  849. auto* clang_decl = cast<clang::CXXRecordDecl>(
  850. context.sem_ir().clang_decls().Get(clang_decl_id).decl);
  851. auto class_inst_id = context.types().GetAsTypeInstId(
  852. context.classes().Get(class_id).first_owning_decl_id);
  853. // TODO: Map loc_id into a clang location and use it for diagnostics if
  854. // instantiation fails, instead of annotating the diagnostic with another
  855. // location.
  856. clang::SourceLocation loc = clang_decl->getLocation();
  857. Diagnostics::AnnotationScope annotate_diagnostics(
  858. &context.emitter(), [&](auto& builder) {
  859. CARBON_DIAGNOSTIC(InCppTypeCompletion, Note,
  860. "while completing C++ class type {0}", SemIR::TypeId);
  861. builder.Note(loc_id, InCppTypeCompletion,
  862. context.classes().Get(class_id).self_type_id);
  863. });
  864. // Ask Clang whether the type is complete. This triggers template
  865. // instantiation if necessary.
  866. clang::DiagnosticErrorTrap trap(ast->getDiagnostics());
  867. if (!ast->getSema().isCompleteType(
  868. loc, context.ast_context().getRecordType(clang_decl))) {
  869. // Type is incomplete. Nothing more to do, but tell the caller if we
  870. // produced an error.
  871. return !trap.hasErrorOccurred();
  872. }
  873. clang::CXXRecordDecl* clang_def = clang_decl->getDefinition();
  874. CARBON_CHECK(clang_def, "Complete type has no definition");
  875. if (clang_def->getNumVBases()) {
  876. // TODO: Handle virtual bases. We don't actually know where they go in the
  877. // layout. We may also want to use a different size in the layout for
  878. // `partial C`, excluding the virtual base. It's also not entirely safe to
  879. // just skip over the virtual base, as the type we would construct would
  880. // have a misleading size. For now, treat a C++ class with vbases as
  881. // incomplete in Carbon.
  882. context.TODO(loc_id, "class with virtual bases");
  883. return false;
  884. }
  885. auto import_ir_inst_id =
  886. context.insts().GetCanonicalLocId(class_inst_id).import_ir_inst_id();
  887. BuildClassDefinition(context, import_ir_inst_id, class_id, class_inst_id,
  888. clang_def);
  889. return true;
  890. }
  891. // Mark the given `Decl` as failed in `clang_decls`.
  892. static auto MarkFailedDecl(Context& context, clang::Decl* clang_decl) {
  893. context.sem_ir().clang_decls().Add({.decl = clang_decl->getCanonicalDecl(),
  894. .inst_id = SemIR::ErrorInst::InstId});
  895. }
  896. // Creates an integer type of the given size.
  897. static auto MakeIntType(Context& context, IntId size_id, bool is_signed)
  898. -> TypeExpr {
  899. auto type_inst_id = MakeIntTypeLiteral(
  900. context, Parse::NodeId::None,
  901. is_signed ? SemIR::IntKind::Signed : SemIR::IntKind::Unsigned, size_id);
  902. return ExprAsType(context, Parse::NodeId::None, type_inst_id);
  903. }
  904. // Maps a C++ builtin type to a Carbon type.
  905. // TODO: Support more builtin types.
  906. static auto MapBuiltinType(Context& context, SemIR::LocId loc_id,
  907. clang::QualType qual_type,
  908. const clang::BuiltinType& type) -> TypeExpr {
  909. clang::ASTContext& ast_context = context.ast_context();
  910. if (type.isBooleanType()) {
  911. CARBON_CHECK(ast_context.hasSameType(qual_type, ast_context.BoolTy));
  912. return ExprAsType(context, Parse::NodeId::None,
  913. context.types().GetInstId(GetSingletonType(
  914. context, SemIR::BoolType::TypeInstId)));
  915. }
  916. if (type.isInteger()) {
  917. unsigned width = context.ast_context().getIntWidth(qual_type);
  918. bool is_signed = type.isSignedInteger();
  919. auto int_n_type =
  920. context.ast_context().getIntTypeForBitwidth(width, is_signed);
  921. if (context.ast_context().hasSameType(qual_type, int_n_type)) {
  922. TypeExpr type_expr =
  923. MakeIntType(context, context.ints().Add(width), is_signed);
  924. // Try to make sure signed integer of 32 or 64 bits are complete so we can
  925. // check against them when deciding whether we need to generate a thunk.
  926. if (is_signed && (width == 32 || width == 64)) {
  927. SemIR::TypeId type_id = type_expr.type_id;
  928. if (!context.types().IsComplete(type_id)) {
  929. TryToCompleteType(context, type_id, loc_id);
  930. }
  931. }
  932. return type_expr;
  933. }
  934. // TODO: Handle integer types that map to named aliases.
  935. } else if (type.isFloatingPoint()) {
  936. if (type.isFloat16Type() || type.isFloat32Type() || type.isDoubleType() ||
  937. type.isFloat128Type()) {
  938. return ExprAsType(
  939. context, Parse::NodeId::None,
  940. MakeFloatTypeLiteral(
  941. context, Parse::NodeId::None,
  942. context.ints().Add(ast_context.getTypeSize(qual_type))));
  943. }
  944. // TODO: Handle floating-point types that map to named aliases.
  945. }
  946. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  947. }
  948. // Maps a C++ record type to a Carbon type.
  949. static auto MapRecordType(Context& context, const clang::RecordType& type)
  950. -> TypeExpr {
  951. auto* record_decl = dyn_cast<clang::CXXRecordDecl>(type.getDecl());
  952. if (!record_decl) {
  953. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  954. }
  955. // Check if the declaration is already mapped.
  956. SemIR::InstId record_inst_id = LookupClangDeclInstId(context, record_decl);
  957. if (!record_inst_id.has_value()) {
  958. record_inst_id = ImportCXXRecordDecl(context, record_decl);
  959. }
  960. SemIR::TypeInstId record_type_inst_id =
  961. context.types().GetAsTypeInstId(record_inst_id);
  962. return {
  963. .inst_id = record_type_inst_id,
  964. .type_id = context.types().GetTypeIdForTypeInstId(record_type_inst_id)};
  965. }
  966. // Maps a C++ type that is not a wrapper type such as a pointer to a Carbon
  967. // type.
  968. // TODO: Support more types.
  969. static auto MapNonWrapperType(Context& context, SemIR::LocId loc_id,
  970. clang::QualType type) -> TypeExpr {
  971. if (const auto* builtin_type = type->getAs<clang::BuiltinType>()) {
  972. return MapBuiltinType(context, loc_id, type, *builtin_type);
  973. }
  974. if (const auto* record_type = type->getAs<clang::RecordType>()) {
  975. return MapRecordType(context, *record_type);
  976. }
  977. CARBON_CHECK(!type.hasQualifiers() && !type->isPointerType(),
  978. "Should not see wrapper types here");
  979. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  980. }
  981. // Maps a qualified C++ type to a Carbon type.
  982. static auto MapQualifiedType(Context& context, clang::QualType type,
  983. TypeExpr type_expr) -> TypeExpr {
  984. auto quals = type.getQualifiers();
  985. if (quals.hasConst()) {
  986. auto type_id = GetConstType(context, type_expr.inst_id);
  987. type_expr = {.inst_id = context.types().GetInstId(type_id),
  988. .type_id = type_id};
  989. quals.removeConst();
  990. }
  991. // TODO: Support other qualifiers.
  992. if (!quals.empty()) {
  993. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  994. }
  995. return type_expr;
  996. }
  997. // Maps a C++ pointer type to a Carbon pointer type.
  998. static auto MapPointerType(Context& context, clang::QualType type,
  999. TypeExpr pointee_type_expr) -> TypeExpr {
  1000. CARBON_CHECK(type->isPointerType());
  1001. if (auto nullability = type->getNullability();
  1002. !nullability.has_value() ||
  1003. *nullability != clang::NullabilityKind::NonNull) {
  1004. // TODO: Support nullable pointers.
  1005. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  1006. }
  1007. SemIR::TypeId pointer_type_id =
  1008. GetPointerType(context, pointee_type_expr.inst_id);
  1009. return {.inst_id = context.types().GetInstId(pointer_type_id),
  1010. .type_id = pointer_type_id};
  1011. }
  1012. // Maps a C++ type to a Carbon type. `type` should not be canonicalized because
  1013. // we check for pointer nullability and nullability will be lost by
  1014. // canonicalization.
  1015. static auto MapType(Context& context, SemIR::LocId loc_id, clang::QualType type)
  1016. -> TypeExpr {
  1017. // Unwrap any type modifiers and wrappers.
  1018. llvm::SmallVector<clang::QualType> wrapper_types;
  1019. while (true) {
  1020. clang::QualType orig_type = type;
  1021. if (type.hasQualifiers()) {
  1022. type = type.getUnqualifiedType();
  1023. } else if (type->isPointerType()) {
  1024. type = type->getPointeeType();
  1025. } else {
  1026. break;
  1027. }
  1028. wrapper_types.push_back(orig_type);
  1029. }
  1030. auto mapped = MapNonWrapperType(context, loc_id, type);
  1031. for (auto wrapper : llvm::reverse(wrapper_types)) {
  1032. if (!mapped.inst_id.has_value() ||
  1033. mapped.type_id == SemIR::ErrorInst::TypeId) {
  1034. break;
  1035. }
  1036. if (wrapper.hasQualifiers()) {
  1037. mapped = MapQualifiedType(context, wrapper, mapped);
  1038. } else if (wrapper->isPointerType()) {
  1039. mapped = MapPointerType(context, wrapper, mapped);
  1040. } else {
  1041. CARBON_FATAL("Unexpected wrapper type {0}", wrapper.getAsString());
  1042. }
  1043. }
  1044. return mapped;
  1045. }
  1046. // Returns a block for the implicit parameters of the given function
  1047. // declaration. Because function templates are not yet supported, this currently
  1048. // only contains the `self` parameter. On error, produces a diagnostic and
  1049. // returns None.
  1050. static auto MakeImplicitParamPatternsBlockId(
  1051. Context& context, SemIR::LocId loc_id,
  1052. const clang::FunctionDecl& clang_decl) -> SemIR::InstBlockId {
  1053. const auto* method_decl = dyn_cast<clang::CXXMethodDecl>(&clang_decl);
  1054. if (!method_decl || method_decl->isStatic() ||
  1055. isa<clang::CXXConstructorDecl>(clang_decl)) {
  1056. return SemIR::InstBlockId::Empty;
  1057. }
  1058. // Build a `self` parameter from the object parameter.
  1059. BeginSubpattern(context);
  1060. // Perform some special-case mapping for the object parameter:
  1061. //
  1062. // - If it's a const reference to T, produce a by-value `self: T` parameter.
  1063. // - If it's a non-const reference to T, produce an `addr self: T*`
  1064. // parameter.
  1065. // - Otherwise, map it directly, which will currently fail for `&&`-qualified
  1066. // methods.
  1067. //
  1068. // TODO: Some of this mapping should be performed for all parameters.
  1069. clang::QualType param_type =
  1070. method_decl->getFunctionObjectParameterReferenceType();
  1071. bool addr_self = false;
  1072. if (param_type->isLValueReferenceType()) {
  1073. param_type = param_type.getNonReferenceType();
  1074. if (param_type.isConstQualified()) {
  1075. // TODO: Consider only doing this if `const` is the only qualifier. For
  1076. // now, any other qualifier will fail when mapping the type.
  1077. auto split_type = param_type.getSplitUnqualifiedType();
  1078. split_type.Quals.removeConst();
  1079. param_type = method_decl->getASTContext().getQualifiedType(split_type);
  1080. } else {
  1081. addr_self = true;
  1082. }
  1083. }
  1084. auto [type_inst_id, type_id] = MapType(context, loc_id, param_type);
  1085. SemIR::ExprRegionId type_expr_region_id =
  1086. EndSubpatternAsExpr(context, type_inst_id);
  1087. if (!type_id.has_value()) {
  1088. context.TODO(loc_id,
  1089. llvm::formatv("Unsupported: object parameter type: {0}",
  1090. param_type.getAsString()));
  1091. return SemIR::InstBlockId::None;
  1092. }
  1093. // TODO: Fill in a location once available.
  1094. auto pattern_id =
  1095. addr_self ? AddAddrSelfParamPattern(context, SemIR::LocId::None,
  1096. type_expr_region_id, type_inst_id)
  1097. : AddSelfParamPattern(context, SemIR::LocId::None,
  1098. type_expr_region_id, type_id);
  1099. return context.inst_blocks().Add({pattern_id});
  1100. }
  1101. // Returns a block id for the explicit parameters of the given function
  1102. // declaration. If the function declaration has no parameters, it returns
  1103. // `SemIR::InstBlockId::Empty`. In the case of an unsupported parameter type, it
  1104. // produces an error and returns `SemIR::InstBlockId::None`.
  1105. // TODO: Consider refactoring to extract and reuse more logic from
  1106. // `HandleAnyBindingPattern()`.
  1107. static auto MakeParamPatternsBlockId(Context& context, SemIR::LocId loc_id,
  1108. const clang::FunctionDecl& clang_decl)
  1109. -> SemIR::InstBlockId {
  1110. if (clang_decl.parameters().empty()) {
  1111. return SemIR::InstBlockId::Empty;
  1112. }
  1113. llvm::SmallVector<SemIR::InstId> params;
  1114. params.reserve(clang_decl.parameters().size());
  1115. for (const clang::ParmVarDecl* param : clang_decl.parameters()) {
  1116. // TODO: Get the parameter type from the function, not from the
  1117. // `ParmVarDecl`. The type of the `ParmVarDecl` is the type within the
  1118. // function, and isn't in general the same as the type that's exposed to
  1119. // callers. In particular, the parameter type exposed to callers will never
  1120. // be cv-qualified.
  1121. clang::QualType param_type = param->getType();
  1122. // Mark the start of a region of insts, needed for the type expression
  1123. // created later with the call of `EndSubpatternAsExpr()`.
  1124. BeginSubpattern(context);
  1125. auto [type_inst_id, type_id] = MapType(context, loc_id, param_type);
  1126. // Type expression of the binding pattern - a single-entry/single-exit
  1127. // region that allows control flow in the type expression e.g. fn F(x: if C
  1128. // then i32 else i64).
  1129. SemIR::ExprRegionId type_expr_region_id =
  1130. EndSubpatternAsExpr(context, type_inst_id);
  1131. if (!type_id.has_value()) {
  1132. context.TODO(loc_id, llvm::formatv("Unsupported: parameter type: {0}",
  1133. param_type.getAsString()));
  1134. return SemIR::InstBlockId::None;
  1135. }
  1136. llvm::StringRef param_name = param->getName();
  1137. SemIR::NameId name_id =
  1138. param_name.empty()
  1139. // Translate an unnamed parameter to an underscore to
  1140. // match Carbon's naming of unnamed/unused function params.
  1141. ? SemIR::NameId::Underscore
  1142. : AddIdentifierName(context, param_name);
  1143. // TODO: Fix this once templates are supported.
  1144. bool is_template = false;
  1145. // TODO: Fix this once generics are supported.
  1146. bool is_generic = false;
  1147. SemIR::InstId binding_pattern_id =
  1148. // TODO: Fill in a location once available.
  1149. AddBindingPattern(context, SemIR::LocId::None, name_id, type_id,
  1150. type_expr_region_id, is_generic, is_template)
  1151. .pattern_id;
  1152. SemIR::InstId var_pattern_id = AddPatternInst(
  1153. context,
  1154. // TODO: Fill in a location once available.
  1155. SemIR::LocIdAndInst::NoLoc(SemIR::ValueParamPattern(
  1156. {.type_id = context.insts().Get(binding_pattern_id).type_id(),
  1157. .subpattern_id = binding_pattern_id,
  1158. .index = SemIR::CallParamIndex::None})));
  1159. params.push_back(var_pattern_id);
  1160. }
  1161. return context.inst_blocks().Add(params);
  1162. }
  1163. // Returns the return `TypeExpr` of the given function declaration. In case of
  1164. // an unsupported return type, returns `SemIR::ErrorInst::InstId`. Constructors
  1165. // are treated as returning a class instance.
  1166. // TODO: Support more return types.
  1167. static auto GetReturnTypeExpr(Context& context, SemIR::LocId loc_id,
  1168. clang::FunctionDecl* clang_decl) -> TypeExpr {
  1169. clang::QualType ret_type = clang_decl->getReturnType();
  1170. if (!ret_type->isVoidType()) {
  1171. TypeExpr mapped_type = MapType(context, loc_id, ret_type);
  1172. if (!mapped_type.inst_id.has_value()) {
  1173. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1174. .type_id = SemIR::ErrorInst::TypeId};
  1175. }
  1176. return mapped_type;
  1177. }
  1178. if (!isa<clang::CXXConstructorDecl>(clang_decl)) {
  1179. // void.
  1180. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  1181. }
  1182. // TODO: Make this a `PartialType`.
  1183. SemIR::TypeInstId record_type_inst_id = context.types().GetAsTypeInstId(
  1184. context.sem_ir()
  1185. .clang_decls()
  1186. .Get(context.sem_ir().clang_decls().Lookup(
  1187. cast<clang::Decl>(clang_decl->getParent())))
  1188. .inst_id);
  1189. return {
  1190. .inst_id = record_type_inst_id,
  1191. .type_id = context.types().GetTypeIdForTypeInstId(record_type_inst_id)};
  1192. }
  1193. // Returns the return pattern of the given function declaration. In case of an
  1194. // unsupported return type, it produces a diagnostic and returns
  1195. // `SemIR::ErrorInst::InstId`. Constructors are treated as returning a class
  1196. // instance.
  1197. static auto GetReturnPattern(Context& context, SemIR::LocId loc_id,
  1198. clang::FunctionDecl* clang_decl) -> SemIR::InstId {
  1199. auto [type_inst_id, type_id] = GetReturnTypeExpr(context, loc_id, clang_decl);
  1200. if (!type_inst_id.has_value()) {
  1201. // void.
  1202. return SemIR::InstId::None;
  1203. }
  1204. if (type_inst_id == SemIR::ErrorInst::TypeInstId) {
  1205. context.TODO(loc_id,
  1206. llvm::formatv("Unsupported: return type: {0}",
  1207. clang_decl->getReturnType().getAsString()));
  1208. return SemIR::ErrorInst::InstId;
  1209. }
  1210. auto pattern_type_id = GetPatternType(context, type_id);
  1211. SemIR::InstId return_slot_pattern_id = AddPatternInst(
  1212. // TODO: Fill in a location for the return type once available.
  1213. context,
  1214. SemIR::LocIdAndInst::NoLoc(SemIR::ReturnSlotPattern(
  1215. {.type_id = pattern_type_id, .type_inst_id = type_inst_id})));
  1216. SemIR::InstId param_pattern_id = AddPatternInst(
  1217. // TODO: Fill in a location for the return type once available.
  1218. context, SemIR::LocIdAndInst::NoLoc(SemIR::OutParamPattern(
  1219. {.type_id = pattern_type_id,
  1220. .subpattern_id = return_slot_pattern_id,
  1221. .index = SemIR::CallParamIndex::None})));
  1222. return param_pattern_id;
  1223. }
  1224. namespace {
  1225. // Represents the parameter patterns block id, the return slot pattern id and
  1226. // the call parameters block id for a function declaration.
  1227. struct FunctionParamsInsts {
  1228. SemIR::InstBlockId implicit_param_patterns_id;
  1229. SemIR::InstBlockId param_patterns_id;
  1230. SemIR::InstId return_slot_pattern_id;
  1231. SemIR::InstBlockId call_params_id;
  1232. };
  1233. } // namespace
  1234. // Creates a block containing the parameter pattern instructions for the
  1235. // explicit parameters, a parameter pattern instruction for the return type and
  1236. // a block containing the call parameters of the function. Emits a callee
  1237. // pattern-match for the explicit parameter patterns and the return slot pattern
  1238. // to create the Call parameters instructions block. Currently the implicit
  1239. // parameter patterns are not taken into account. Returns the parameter patterns
  1240. // block id, the return slot pattern id, and the call parameters block id.
  1241. // Produces a diagnostic and returns `std::nullopt` if the function declaration
  1242. // has an unsupported parameter type.
  1243. static auto CreateFunctionParamsInsts(Context& context, SemIR::LocId loc_id,
  1244. clang::FunctionDecl* clang_decl)
  1245. -> std::optional<FunctionParamsInsts> {
  1246. if (isa<clang::CXXDestructorDecl>(clang_decl)) {
  1247. context.TODO(loc_id, "Unsupported: Destructor");
  1248. return std::nullopt;
  1249. }
  1250. auto implicit_param_patterns_id =
  1251. MakeImplicitParamPatternsBlockId(context, loc_id, *clang_decl);
  1252. if (!implicit_param_patterns_id.has_value()) {
  1253. return std::nullopt;
  1254. }
  1255. auto param_patterns_id =
  1256. MakeParamPatternsBlockId(context, loc_id, *clang_decl);
  1257. if (!param_patterns_id.has_value()) {
  1258. return std::nullopt;
  1259. }
  1260. auto return_slot_pattern_id = GetReturnPattern(context, loc_id, clang_decl);
  1261. if (SemIR::ErrorInst::InstId == return_slot_pattern_id) {
  1262. return std::nullopt;
  1263. }
  1264. auto call_params_id =
  1265. CalleePatternMatch(context, implicit_param_patterns_id, param_patterns_id,
  1266. return_slot_pattern_id);
  1267. return {{.implicit_param_patterns_id = implicit_param_patterns_id,
  1268. .param_patterns_id = param_patterns_id,
  1269. .return_slot_pattern_id = return_slot_pattern_id,
  1270. .call_params_id = call_params_id}};
  1271. }
  1272. // Creates a `FunctionDecl` and a `Function` without C++ thunk information.
  1273. // Returns std::nullopt on failure. The given Clang declaration is assumed to:
  1274. // * Have not been imported before.
  1275. // * Be of supported type (ignoring parameters).
  1276. static auto ImportFunction(Context& context, SemIR::LocId loc_id,
  1277. clang::FunctionDecl* clang_decl)
  1278. -> std::optional<SemIR::FunctionId> {
  1279. context.scope_stack().PushForDeclName();
  1280. context.inst_block_stack().Push();
  1281. context.pattern_block_stack().Push();
  1282. auto function_params_insts =
  1283. CreateFunctionParamsInsts(context, loc_id, clang_decl);
  1284. auto pattern_block_id = context.pattern_block_stack().Pop();
  1285. auto decl_block_id = context.inst_block_stack().Pop();
  1286. context.scope_stack().Pop();
  1287. if (!function_params_insts.has_value()) {
  1288. return std::nullopt;
  1289. }
  1290. auto function_decl = SemIR::FunctionDecl{
  1291. SemIR::TypeId::None, SemIR::FunctionId::None, decl_block_id};
  1292. auto decl_id =
  1293. AddPlaceholderInstInNoBlock(context, Parse::NodeId::None, function_decl);
  1294. context.imports().push_back(decl_id);
  1295. SemIR::NameId function_name_id =
  1296. isa<clang::CXXConstructorDecl>(clang_decl)
  1297. ? context.classes()
  1298. .Get(context.insts()
  1299. .GetAs<SemIR::ClassDecl>(LookupClangDeclInstId(
  1300. context,
  1301. cast<clang::Decl>(clang_decl->getParent())))
  1302. .class_id)
  1303. .name_id
  1304. : AddIdentifierName(context, clang_decl->getName());
  1305. auto function_info = SemIR::Function{
  1306. {.name_id = function_name_id,
  1307. .parent_scope_id = GetParentNameScopeId(context, clang_decl),
  1308. .generic_id = SemIR::GenericId::None,
  1309. .first_param_node_id = Parse::NodeId::None,
  1310. .last_param_node_id = Parse::NodeId::None,
  1311. .pattern_block_id = pattern_block_id,
  1312. .implicit_param_patterns_id =
  1313. function_params_insts->implicit_param_patterns_id,
  1314. .param_patterns_id = function_params_insts->param_patterns_id,
  1315. .is_extern = false,
  1316. .extern_library_id = SemIR::LibraryNameId::None,
  1317. .non_owning_decl_id = SemIR::InstId::None,
  1318. .first_owning_decl_id = decl_id,
  1319. .definition_id = SemIR::InstId::None},
  1320. {.call_params_id = function_params_insts->call_params_id,
  1321. .return_slot_pattern_id = function_params_insts->return_slot_pattern_id,
  1322. .virtual_modifier = SemIR::FunctionFields::VirtualModifier::None,
  1323. .self_param_id = FindSelfPattern(
  1324. context, function_params_insts->implicit_param_patterns_id),
  1325. .clang_decl_id = context.sem_ir().clang_decls().Add(
  1326. {.decl = clang_decl, .inst_id = decl_id})}};
  1327. function_decl.function_id = context.functions().Add(function_info);
  1328. function_decl.type_id = GetFunctionType(context, function_decl.function_id,
  1329. SemIR::SpecificId::None);
  1330. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  1331. return function_decl.function_id;
  1332. }
  1333. // Imports a function declaration from Clang to Carbon. If successful, returns
  1334. // the new Carbon function declaration `InstId`. If the declaration was already
  1335. // imported, returns the mapped instruction.
  1336. static auto ImportFunctionDecl(Context& context, SemIR::LocId loc_id,
  1337. clang::FunctionDecl* clang_decl)
  1338. -> SemIR::InstId {
  1339. // Check if the declaration is already mapped.
  1340. if (SemIR::InstId existing_inst_id =
  1341. LookupClangDeclInstId(context, clang_decl);
  1342. existing_inst_id.has_value()) {
  1343. return existing_inst_id;
  1344. }
  1345. if (clang_decl->isVariadic()) {
  1346. context.TODO(loc_id, "Unsupported: Variadic function");
  1347. MarkFailedDecl(context, clang_decl);
  1348. return SemIR::ErrorInst::InstId;
  1349. }
  1350. if (clang_decl->getTemplatedKind() ==
  1351. clang::FunctionDecl::TK_FunctionTemplate) {
  1352. context.TODO(loc_id, "Unsupported: Template function");
  1353. MarkFailedDecl(context, clang_decl);
  1354. return SemIR::ErrorInst::InstId;
  1355. }
  1356. if (auto* method_decl = dyn_cast<clang::CXXMethodDecl>(clang_decl)) {
  1357. if (method_decl->isVirtual()) {
  1358. context.TODO(loc_id, "Unsupported: Virtual function");
  1359. MarkFailedDecl(context, clang_decl);
  1360. return SemIR::ErrorInst::InstId;
  1361. }
  1362. }
  1363. CARBON_CHECK(clang_decl->getFunctionType()->isFunctionProtoType(),
  1364. "Not Prototype function (non-C++ code)");
  1365. auto function_id = ImportFunction(context, loc_id, clang_decl);
  1366. if (!function_id) {
  1367. MarkFailedDecl(context, clang_decl);
  1368. return SemIR::ErrorInst::InstId;
  1369. }
  1370. SemIR::Function& function_info = context.functions().Get(*function_id);
  1371. if (IsCppThunkRequired(context, function_info)) {
  1372. clang::FunctionDecl* thunk_clang_decl =
  1373. BuildCppThunk(context, function_info);
  1374. if (thunk_clang_decl) {
  1375. SemIR::FunctionId thunk_function_id =
  1376. *ImportFunction(context, loc_id, thunk_clang_decl);
  1377. SemIR::InstId thunk_function_decl_id =
  1378. context.functions().Get(thunk_function_id).first_owning_decl_id;
  1379. function_info.SetHasCppThunk(thunk_function_decl_id);
  1380. }
  1381. }
  1382. return function_info.first_owning_decl_id;
  1383. }
  1384. namespace {
  1385. // An item to be imported in an import worklist.
  1386. // TODO: If worklists ever become particularly large, consider changing this
  1387. // to use a `PointerIntPair`.
  1388. struct ImportItem {
  1389. // A declaration that we want to import.
  1390. clang::Decl* decl;
  1391. // Whether we have added `decl`'s dependencies to the worklist.
  1392. bool added_dependencies;
  1393. };
  1394. // A worklist of declarations to import.
  1395. using ImportWorklist = llvm::SmallVector<ImportItem>;
  1396. } // namespace
  1397. // Adds the given declaration to our list of declarations to import.
  1398. static auto AddDependentDecl(const Context& context, clang::Decl* decl,
  1399. ImportWorklist& worklist) -> void {
  1400. if (!IsClangDeclImported(context, decl)) {
  1401. worklist.push_back({.decl = decl, .added_dependencies = false});
  1402. }
  1403. }
  1404. // Finds all decls that need to be imported before importing the given type and
  1405. // adds them to the given set.
  1406. static auto AddDependentUnimportedTypeDecls(const Context& context,
  1407. clang::QualType type,
  1408. ImportWorklist& worklist) -> void {
  1409. while (true) {
  1410. if (type->isPointerType() || type->isReferenceType()) {
  1411. type = type->getPointeeType();
  1412. } else if (const clang::ArrayType* array_type =
  1413. type->getAsArrayTypeUnsafe()) {
  1414. type = array_type->getElementType();
  1415. } else {
  1416. break;
  1417. }
  1418. }
  1419. if (const auto* record_type = type->getAs<clang::RecordType>()) {
  1420. AddDependentDecl(context, record_type->getDecl(), worklist);
  1421. }
  1422. }
  1423. // Finds all decls that need to be imported before importing the given function
  1424. // and adds them to the given set.
  1425. static auto AddDependentUnimportedFunctionDecls(
  1426. const Context& context, const clang::FunctionDecl& clang_decl,
  1427. ImportWorklist& worklist) -> void {
  1428. for (const auto* param : clang_decl.parameters()) {
  1429. AddDependentUnimportedTypeDecls(context, param->getType(), worklist);
  1430. }
  1431. AddDependentUnimportedTypeDecls(context, clang_decl.getReturnType(),
  1432. worklist);
  1433. }
  1434. // Finds all decls that need to be imported before importing the given
  1435. // declaration and adds them to the given set.
  1436. static auto AddDependentUnimportedDecls(const Context& context,
  1437. clang::Decl* clang_decl,
  1438. ImportWorklist& worklist) -> void {
  1439. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  1440. AddDependentUnimportedFunctionDecls(context, *clang_function_decl,
  1441. worklist);
  1442. } else if (auto* type_decl = dyn_cast<clang::TypeDecl>(clang_decl)) {
  1443. if (!isa<clang::RecordDecl>(clang_decl)) {
  1444. AddDependentUnimportedTypeDecls(
  1445. context, type_decl->getASTContext().getTypeDeclType(type_decl),
  1446. worklist);
  1447. }
  1448. }
  1449. if (!isa<clang::TranslationUnitDecl>(clang_decl)) {
  1450. AddDependentDecl(context, GetParentDecl(clang_decl), worklist);
  1451. }
  1452. }
  1453. // Imports a declaration from Clang to Carbon. Returns the instruction for the
  1454. // new Carbon declaration, which will be an ErrorInst on failure. Assumes all
  1455. // dependencies have already been imported.
  1456. static auto ImportDeclAfterDependencies(Context& context, SemIR::LocId loc_id,
  1457. clang::Decl* clang_decl)
  1458. -> SemIR::InstId {
  1459. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  1460. return ImportFunctionDecl(context, loc_id, clang_function_decl);
  1461. }
  1462. if (auto* clang_namespace_decl = dyn_cast<clang::NamespaceDecl>(clang_decl)) {
  1463. return ImportNamespaceDecl(context, clang_namespace_decl);
  1464. }
  1465. if (auto* type_decl = dyn_cast<clang::TypeDecl>(clang_decl)) {
  1466. auto type = clang_decl->getASTContext().getTypeDeclType(type_decl);
  1467. auto type_inst_id = MapType(context, loc_id, type).inst_id;
  1468. if (!type_inst_id.has_value()) {
  1469. context.TODO(AddImportIRInst(context.sem_ir(), type_decl->getLocation()),
  1470. llvm::formatv("Unsupported: Type declaration: {0}",
  1471. type.getAsString()));
  1472. return SemIR::ErrorInst::InstId;
  1473. }
  1474. context.sem_ir().clang_decls().Add(
  1475. {.decl = clang_decl, .inst_id = type_inst_id});
  1476. return type_inst_id;
  1477. }
  1478. if (isa<clang::FieldDecl, clang::IndirectFieldDecl>(clang_decl)) {
  1479. // Usable fields get imported as a side effect of importing the class.
  1480. if (SemIR::InstId existing_inst_id =
  1481. LookupClangDeclInstId(context, clang_decl);
  1482. existing_inst_id.has_value()) {
  1483. return existing_inst_id;
  1484. }
  1485. context.TODO(AddImportIRInst(context.sem_ir(), clang_decl->getLocation()),
  1486. "Unsupported: field declaration has unhandled type or kind");
  1487. return SemIR::ErrorInst::InstId;
  1488. }
  1489. context.TODO(AddImportIRInst(context.sem_ir(), clang_decl->getLocation()),
  1490. llvm::formatv("Unsupported: Declaration type {0}",
  1491. clang_decl->getDeclKindName()));
  1492. return SemIR::ErrorInst::InstId;
  1493. }
  1494. // Attempts to import a set of declarations. Returns `false` if an error was
  1495. // produced, `true` otherwise.
  1496. static auto ImportDeclSet(Context& context, SemIR::LocId loc_id,
  1497. ImportWorklist& worklist) -> bool {
  1498. // Walk the dependency graph in depth-first order, and import declarations
  1499. // once we've imported all of their dependencies.
  1500. while (!worklist.empty()) {
  1501. auto& item = worklist.back();
  1502. if (!item.added_dependencies) {
  1503. // Skip items we've already imported. We checked this when initially
  1504. // adding the item to the worklist, but it might have been added to the
  1505. // worklist twice before the first time we visited it. For example, this
  1506. // happens for `fn F(a: Cpp.T, b: Cpp.T)`.
  1507. if (IsClangDeclImported(context, item.decl)) {
  1508. worklist.pop_back();
  1509. continue;
  1510. }
  1511. // First time visiting this declaration (preorder): add its dependencies
  1512. // to the work list.
  1513. item.added_dependencies = true;
  1514. AddDependentUnimportedDecls(context, item.decl, worklist);
  1515. } else {
  1516. // Second time visiting this declaration (postorder): its dependencies are
  1517. // already imported, so we can import it now.
  1518. auto* decl = worklist.pop_back_val().decl;
  1519. auto inst_id = ImportDeclAfterDependencies(context, loc_id, decl);
  1520. CARBON_CHECK(inst_id.has_value());
  1521. if (inst_id == SemIR::ErrorInst::InstId) {
  1522. return false;
  1523. }
  1524. CARBON_CHECK(IsClangDeclImported(context, decl));
  1525. }
  1526. }
  1527. return true;
  1528. }
  1529. // Imports a declaration from Clang to Carbon. If successful, returns the
  1530. // instruction for the new Carbon declaration. All unimported dependencies are
  1531. // imported first.
  1532. static auto ImportDeclAndDependencies(Context& context, SemIR::LocId loc_id,
  1533. clang::Decl* clang_decl)
  1534. -> SemIR::InstId {
  1535. // Collect dependencies by walking the dependency graph in depth-first order.
  1536. ImportWorklist worklist;
  1537. AddDependentDecl(context, clang_decl, worklist);
  1538. if (!ImportDeclSet(context, loc_id, worklist)) {
  1539. return SemIR::ErrorInst::InstId;
  1540. }
  1541. return LookupClangDeclInstId(context, clang_decl);
  1542. }
  1543. // Imports a type from Clang to Carbon. If successful, returns the imported
  1544. // TypeId. All unimported dependencies are imported first.
  1545. static auto ImportTypeAndDependencies(Context& context, SemIR::LocId loc_id,
  1546. clang::QualType type) -> TypeExpr {
  1547. // Collect dependencies by walking the dependency graph in depth-first order.
  1548. ImportWorklist worklist;
  1549. AddDependentUnimportedTypeDecls(context, type, worklist);
  1550. if (!ImportDeclSet(context, loc_id, worklist)) {
  1551. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1552. .type_id = SemIR::ErrorInst::TypeId};
  1553. }
  1554. return MapType(context, loc_id, type);
  1555. }
  1556. // Maps `clang::AccessSpecifier` to `SemIR::AccessKind`.
  1557. static auto MapAccess(clang::AccessSpecifier access_specifier)
  1558. -> SemIR::AccessKind {
  1559. switch (access_specifier) {
  1560. case clang::AS_public:
  1561. case clang::AS_none:
  1562. return SemIR::AccessKind::Public;
  1563. case clang::AS_protected:
  1564. return SemIR::AccessKind::Protected;
  1565. case clang::AS_private:
  1566. return SemIR::AccessKind::Private;
  1567. }
  1568. }
  1569. // Imports a `clang::NamedDecl` into Carbon and adds that name into the
  1570. // `NameScope`.
  1571. static auto ImportNameDeclIntoScope(Context& context, SemIR::LocId loc_id,
  1572. SemIR::NameScopeId scope_id,
  1573. SemIR::NameId name_id,
  1574. clang::NamedDecl* clang_decl,
  1575. clang::AccessSpecifier access)
  1576. -> SemIR::ScopeLookupResult {
  1577. SemIR::InstId inst_id =
  1578. ImportDeclAndDependencies(context, loc_id, clang_decl);
  1579. if (!inst_id.has_value()) {
  1580. return SemIR::ScopeLookupResult::MakeNotFound();
  1581. }
  1582. SemIR::AccessKind access_kind = MapAccess(access);
  1583. AddNameToScope(context, scope_id, name_id, access_kind, inst_id);
  1584. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(inst_id,
  1585. access_kind);
  1586. }
  1587. auto ImportNameFromCpp(Context& context, SemIR::LocId loc_id,
  1588. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  1589. -> SemIR::ScopeLookupResult {
  1590. Diagnostics::AnnotationScope annotate_diagnostics(
  1591. &context.emitter(), [&](auto& builder) {
  1592. CARBON_DIAGNOSTIC(InCppNameLookup, Note,
  1593. "in `Cpp` name lookup for `{0}`", SemIR::NameId);
  1594. builder.Note(loc_id, InCppNameLookup, name_id);
  1595. });
  1596. auto decl_and_access = ClangLookup(context, loc_id, scope_id, name_id);
  1597. if (!decl_and_access) {
  1598. return SemIR::ScopeLookupResult::MakeNotFound();
  1599. }
  1600. auto [decl, access] = *decl_and_access;
  1601. if (!decl) {
  1602. context.name_scopes().AddRequiredName(scope_id, name_id,
  1603. SemIR::ErrorInst::InstId);
  1604. return SemIR::ScopeLookupResult::MakeError();
  1605. }
  1606. return ImportNameDeclIntoScope(context, loc_id, scope_id, name_id, decl,
  1607. access);
  1608. }
  1609. } // namespace Carbon::Check