import_cpp.cpp 88 KB

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