import_cpp.cpp 85 KB

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