context.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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/context.h"
  5. #include <utility>
  6. #include "common/check.h"
  7. #include "common/vlog.h"
  8. #include "llvm/ADT/STLExtras.h"
  9. #include "toolchain/check/declaration_name_stack.h"
  10. #include "toolchain/check/node_block_stack.h"
  11. #include "toolchain/diagnostics/diagnostic_kind.h"
  12. #include "toolchain/lex/tokenized_buffer.h"
  13. #include "toolchain/parse/node_kind.h"
  14. #include "toolchain/sem_ir/file.h"
  15. #include "toolchain/sem_ir/node.h"
  16. #include "toolchain/sem_ir/node_kind.h"
  17. namespace Carbon::Check {
  18. Context::Context(const Lex::TokenizedBuffer& tokens,
  19. DiagnosticEmitter<Parse::Node>& emitter,
  20. const Parse::Tree& parse_tree, SemIR::File& semantics_ir,
  21. llvm::raw_ostream* vlog_stream)
  22. : tokens_(&tokens),
  23. emitter_(&emitter),
  24. parse_tree_(&parse_tree),
  25. semantics_ir_(&semantics_ir),
  26. vlog_stream_(vlog_stream),
  27. node_stack_(parse_tree, vlog_stream),
  28. node_block_stack_("node_block_stack_", semantics_ir, vlog_stream),
  29. params_or_args_stack_("params_or_args_stack_", semantics_ir, vlog_stream),
  30. args_type_info_stack_("args_type_info_stack_", semantics_ir, vlog_stream),
  31. declaration_name_stack_(this) {
  32. // Inserts the "Error" and "Type" types as "used types" so that
  33. // canonicalization can skip them. We don't emit either for lowering.
  34. canonical_types_.insert({SemIR::NodeId::BuiltinError, SemIR::TypeId::Error});
  35. canonical_types_.insert(
  36. {SemIR::NodeId::BuiltinTypeType, SemIR::TypeId::TypeType});
  37. }
  38. auto Context::TODO(Parse::Node parse_node, std::string label) -> bool {
  39. CARBON_DIAGNOSTIC(SemanticsTodo, Error, "Semantics TODO: `{0}`.",
  40. std::string);
  41. emitter_->Emit(parse_node, SemanticsTodo, std::move(label));
  42. return false;
  43. }
  44. auto Context::VerifyOnFinish() -> void {
  45. // Information in all the various context objects should be cleaned up as
  46. // various pieces of context go out of scope. At this point, nothing should
  47. // remain.
  48. // node_stack_ will still contain top-level entities.
  49. CARBON_CHECK(name_lookup_.empty()) << name_lookup_.size();
  50. CARBON_CHECK(scope_stack_.empty()) << scope_stack_.size();
  51. CARBON_CHECK(node_block_stack_.empty()) << node_block_stack_.size();
  52. CARBON_CHECK(params_or_args_stack_.empty()) << params_or_args_stack_.size();
  53. }
  54. auto Context::AddNode(SemIR::Node node) -> SemIR::NodeId {
  55. return AddNodeToBlock(node_block_stack_.PeekForAdd(), node);
  56. }
  57. auto Context::AddNodeToBlock(SemIR::NodeBlockId block, SemIR::Node node)
  58. -> SemIR::NodeId {
  59. CARBON_VLOG() << "AddNode " << block << ": " << node << "\n";
  60. return semantics_ir_->AddNode(block, node);
  61. }
  62. auto Context::AddNodeAndPush(Parse::Node parse_node, SemIR::Node node) -> void {
  63. auto node_id = AddNode(node);
  64. node_stack_.Push(parse_node, node_id);
  65. }
  66. auto Context::DiagnoseDuplicateName(Parse::Node parse_node,
  67. SemIR::NodeId prev_def_id) -> void {
  68. CARBON_DIAGNOSTIC(NameDeclarationDuplicate, Error,
  69. "Duplicate name being declared in the same scope.");
  70. CARBON_DIAGNOSTIC(NameDeclarationPrevious, Note,
  71. "Name is previously declared here.");
  72. auto prev_def = semantics_ir_->GetNode(prev_def_id);
  73. emitter_->Build(parse_node, NameDeclarationDuplicate)
  74. .Note(prev_def.parse_node(), NameDeclarationPrevious)
  75. .Emit();
  76. }
  77. auto Context::DiagnoseNameNotFound(Parse::Node parse_node,
  78. SemIR::StringId name_id) -> void {
  79. CARBON_DIAGNOSTIC(NameNotFound, Error, "Name `{0}` not found.",
  80. llvm::StringRef);
  81. emitter_->Emit(parse_node, NameNotFound, semantics_ir_->GetString(name_id));
  82. }
  83. auto Context::AddNameToLookup(Parse::Node name_node, SemIR::StringId name_id,
  84. SemIR::NodeId target_id) -> void {
  85. if (current_scope().names.insert(name_id).second) {
  86. name_lookup_[name_id].push_back(target_id);
  87. } else {
  88. DiagnoseDuplicateName(name_node, name_lookup_[name_id].back());
  89. }
  90. }
  91. auto Context::LookupName(Parse::Node parse_node, SemIR::StringId name_id,
  92. SemIR::NameScopeId scope_id, bool print_diagnostics)
  93. -> SemIR::NodeId {
  94. if (scope_id == SemIR::NameScopeId::Invalid) {
  95. auto it = name_lookup_.find(name_id);
  96. if (it == name_lookup_.end()) {
  97. if (print_diagnostics) {
  98. DiagnoseNameNotFound(parse_node, name_id);
  99. }
  100. return SemIR::NodeId::BuiltinError;
  101. }
  102. CARBON_CHECK(!it->second.empty())
  103. << "Should have been erased: " << semantics_ir_->GetString(name_id);
  104. // TODO: Check for ambiguous lookups.
  105. return it->second.back();
  106. } else {
  107. const auto& scope = semantics_ir_->GetNameScope(scope_id);
  108. auto it = scope.find(name_id);
  109. if (it == scope.end()) {
  110. if (print_diagnostics) {
  111. DiagnoseNameNotFound(parse_node, name_id);
  112. }
  113. return SemIR::NodeId::BuiltinError;
  114. }
  115. return it->second;
  116. }
  117. }
  118. auto Context::PushScope() -> void { scope_stack_.push_back({}); }
  119. auto Context::PopScope() -> void {
  120. auto scope = scope_stack_.pop_back_val();
  121. for (const auto& str_id : scope.names) {
  122. auto it = name_lookup_.find(str_id);
  123. if (it->second.size() == 1) {
  124. // Erase names that no longer resolve.
  125. name_lookup_.erase(it);
  126. } else {
  127. it->second.pop_back();
  128. }
  129. }
  130. }
  131. template <typename BranchNode, typename... Args>
  132. static auto AddDominatedBlockAndBranchImpl(Context& context,
  133. Parse::Node parse_node, Args... args)
  134. -> SemIR::NodeBlockId {
  135. if (!context.node_block_stack().is_current_block_reachable()) {
  136. return SemIR::NodeBlockId::Unreachable;
  137. }
  138. auto block_id = context.semantics_ir().AddNodeBlock();
  139. context.AddNode(BranchNode::Make(parse_node, block_id, args...));
  140. return block_id;
  141. }
  142. auto Context::AddDominatedBlockAndBranch(Parse::Node parse_node)
  143. -> SemIR::NodeBlockId {
  144. return AddDominatedBlockAndBranchImpl<SemIR::Node::Branch>(*this, parse_node);
  145. }
  146. auto Context::AddDominatedBlockAndBranchWithArg(Parse::Node parse_node,
  147. SemIR::NodeId arg_id)
  148. -> SemIR::NodeBlockId {
  149. return AddDominatedBlockAndBranchImpl<SemIR::Node::BranchWithArg>(
  150. *this, parse_node, arg_id);
  151. }
  152. auto Context::AddDominatedBlockAndBranchIf(Parse::Node parse_node,
  153. SemIR::NodeId cond_id)
  154. -> SemIR::NodeBlockId {
  155. return AddDominatedBlockAndBranchImpl<SemIR::Node::BranchIf>(
  156. *this, parse_node, cond_id);
  157. }
  158. auto Context::AddConvergenceBlockAndPush(
  159. Parse::Node parse_node, std::initializer_list<SemIR::NodeBlockId> blocks)
  160. -> void {
  161. CARBON_CHECK(blocks.size() >= 2) << "no convergence";
  162. SemIR::NodeBlockId new_block_id = SemIR::NodeBlockId::Unreachable;
  163. for (SemIR::NodeBlockId block_id : blocks) {
  164. if (block_id != SemIR::NodeBlockId::Unreachable) {
  165. if (new_block_id == SemIR::NodeBlockId::Unreachable) {
  166. new_block_id = semantics_ir().AddNodeBlock();
  167. }
  168. AddNodeToBlock(block_id,
  169. SemIR::Node::Branch::Make(parse_node, new_block_id));
  170. }
  171. }
  172. node_block_stack().Push(new_block_id);
  173. }
  174. auto Context::AddConvergenceBlockWithArgAndPush(
  175. Parse::Node parse_node,
  176. std::initializer_list<std::pair<SemIR::NodeBlockId, SemIR::NodeId>>
  177. blocks_and_args) -> SemIR::NodeId {
  178. CARBON_CHECK(blocks_and_args.size() >= 2) << "no convergence";
  179. SemIR::NodeBlockId new_block_id = SemIR::NodeBlockId::Unreachable;
  180. for (auto [block_id, arg_id] : blocks_and_args) {
  181. if (block_id != SemIR::NodeBlockId::Unreachable) {
  182. if (new_block_id == SemIR::NodeBlockId::Unreachable) {
  183. new_block_id = semantics_ir().AddNodeBlock();
  184. }
  185. AddNodeToBlock(block_id, SemIR::Node::BranchWithArg::Make(
  186. parse_node, new_block_id, arg_id));
  187. }
  188. }
  189. node_block_stack().Push(new_block_id);
  190. // Acquire the result value.
  191. SemIR::TypeId result_type_id =
  192. semantics_ir().GetNode(blocks_and_args.begin()->second).type_id();
  193. return AddNode(
  194. SemIR::Node::BlockArg::Make(parse_node, result_type_id, new_block_id));
  195. }
  196. // Add the current code block to the enclosing function.
  197. auto Context::AddCurrentCodeBlockToFunction() -> void {
  198. CARBON_CHECK(!node_block_stack().empty()) << "no current code block";
  199. CARBON_CHECK(!return_scope_stack().empty()) << "no current function";
  200. if (!node_block_stack().is_current_block_reachable()) {
  201. // Don't include unreachable blocks in the function.
  202. return;
  203. }
  204. auto function_id = semantics_ir()
  205. .GetNode(return_scope_stack().back())
  206. .GetAsFunctionDeclaration();
  207. semantics_ir()
  208. .GetFunction(function_id)
  209. .body_block_ids.push_back(node_block_stack().PeekForAdd());
  210. }
  211. auto Context::is_current_position_reachable() -> bool {
  212. switch (auto block_id = node_block_stack().Peek(); block_id.index) {
  213. case SemIR::NodeBlockId::Unreachable.index: {
  214. return false;
  215. }
  216. case SemIR::NodeBlockId::Invalid.index: {
  217. return true;
  218. }
  219. default: {
  220. // Our current position is at the end of a real block. That position is
  221. // reachable unless the previous instruction is a terminator instruction.
  222. const auto& block_contents = semantics_ir().GetNodeBlock(block_id);
  223. if (block_contents.empty()) {
  224. return true;
  225. }
  226. const auto& last_node = semantics_ir().GetNode(block_contents.back());
  227. return last_node.kind().terminator_kind() !=
  228. SemIR::TerminatorKind::Terminator;
  229. }
  230. }
  231. }
  232. auto Context::Initialize(Parse::Node parse_node, SemIR::NodeId target_id,
  233. SemIR::NodeId value_id) -> SemIR::NodeId {
  234. // Implicitly convert the value to the type of the target.
  235. auto type_id = semantics_ir().GetNode(target_id).type_id();
  236. auto expr_id = ImplicitAs(parse_node, value_id, type_id);
  237. SemIR::Node expr = semantics_ir().GetNode(expr_id);
  238. // Perform initialization now that we have an expression of the right type.
  239. switch (SemIR::GetExpressionCategory(semantics_ir(), expr_id)) {
  240. case SemIR::ExpressionCategory::NotExpression:
  241. CARBON_FATAL() << "Converting non-expression node " << expr
  242. << " to initializing expression";
  243. case SemIR::ExpressionCategory::DurableReference:
  244. case SemIR::ExpressionCategory::EphemeralReference:
  245. // The design uses a custom "copy initialization" process here. We model
  246. // that as value binding followed by direct initialization.
  247. //
  248. // TODO: Determine whether this is observably different from the design,
  249. // and change either the toolchain or the design so they match.
  250. return AddNode(SemIR::Node::BindValue::Make(expr.parse_node(),
  251. expr.type_id(), expr_id));
  252. case SemIR::ExpressionCategory::Value:
  253. // TODO: For class types, use an interface to determine how to perform
  254. // this operation.
  255. return expr_id;
  256. case SemIR::ExpressionCategory::Initializing:
  257. MarkInitializerFor(expr_id, target_id);
  258. return expr_id;
  259. }
  260. }
  261. auto Context::ConvertToValueExpression(SemIR::NodeId expr_id) -> SemIR::NodeId {
  262. if (expr_id == SemIR::NodeId::BuiltinError) {
  263. return expr_id;
  264. }
  265. switch (SemIR::GetExpressionCategory(semantics_ir(), expr_id)) {
  266. case SemIR::ExpressionCategory::NotExpression:
  267. CARBON_FATAL() << "Converting non-expression node "
  268. << semantics_ir().GetNode(expr_id)
  269. << " to value expression";
  270. case SemIR::ExpressionCategory::Initializing:
  271. // Commit to using a temporary for this initializing expression.
  272. // TODO: Don't create a temporary if the initializing representation is
  273. // already a value representation.
  274. expr_id = FinalizeTemporary(expr_id, /*discarded=*/false);
  275. [[fallthrough]];
  276. case SemIR::ExpressionCategory::DurableReference:
  277. case SemIR::ExpressionCategory::EphemeralReference: {
  278. // TODO: Support types with custom value representations.
  279. SemIR::Node expr = semantics_ir().GetNode(expr_id);
  280. return AddNode(SemIR::Node::BindValue::Make(expr.parse_node(),
  281. expr.type_id(), expr_id));
  282. }
  283. case SemIR::ExpressionCategory::Value:
  284. return expr_id;
  285. }
  286. }
  287. auto Context::FinalizeTemporary(SemIR::NodeId init_id, bool discarded)
  288. -> SemIR::NodeId {
  289. // TODO: See if we can refactor this with MarkInitializerFor once recursion
  290. // through struct and tuple values is properly handled.
  291. auto orig_init_id = init_id;
  292. while (true) {
  293. SemIR::Node init = semantics_ir().GetNode(init_id);
  294. CARBON_CHECK(SemIR::GetExpressionCategory(semantics_ir(), init_id) ==
  295. SemIR::ExpressionCategory::Initializing)
  296. << "Can only materialize initializing expressions, found " << init;
  297. switch (init.kind()) {
  298. default:
  299. CARBON_FATAL() << "Initialization from unexpected node " << init;
  300. case SemIR::NodeKind::StructLiteral:
  301. case SemIR::NodeKind::TupleLiteral:
  302. CARBON_FATAL() << init << " is not modeled as initializing yet";
  303. case SemIR::NodeKind::StubReference: {
  304. init_id = init.GetAsStubReference();
  305. continue;
  306. }
  307. case SemIR::NodeKind::Call: {
  308. auto [refs_id, callee_id] = init.GetAsCall();
  309. if (semantics_ir().GetFunction(callee_id).return_slot_id.is_valid()) {
  310. // The return slot should have a materialized temporary in it.
  311. auto temporary_id = semantics_ir().GetNodeBlock(refs_id).back();
  312. CARBON_CHECK(semantics_ir().GetNode(temporary_id).kind() ==
  313. SemIR::NodeKind::TemporaryStorage)
  314. << "Return slot for function call does not contain a temporary; "
  315. << "initialized multiple times? Have "
  316. << semantics_ir().GetNode(temporary_id);
  317. return AddNode(SemIR::Node::Temporary::Make(
  318. init.parse_node(), init.type_id(), temporary_id, orig_init_id));
  319. }
  320. if (discarded) {
  321. // Don't invent a temporary that we're going to discard.
  322. return SemIR::NodeId::Invalid;
  323. }
  324. // The function has no return slot, but we want to produce a temporary
  325. // object. Materialize one now.
  326. // TODO: Consider using an invalid ID to mean that we immediately
  327. // materialize and initialize a temporary, rather than two separate
  328. // nodes.
  329. auto temporary_id = AddNode(SemIR::Node::TemporaryStorage::Make(
  330. init.parse_node(), init.type_id()));
  331. return AddNode(SemIR::Node::Temporary::Make(
  332. init.parse_node(), init.type_id(), temporary_id, init_id));
  333. }
  334. }
  335. }
  336. }
  337. auto Context::MarkInitializerFor(SemIR::NodeId init_id, SemIR::NodeId target_id)
  338. -> void {
  339. while (true) {
  340. SemIR::Node init = semantics_ir().GetNode(init_id);
  341. CARBON_CHECK(SemIR::GetExpressionCategory(semantics_ir(), init_id) ==
  342. SemIR::ExpressionCategory::Initializing)
  343. << "initialization from non-initializing node " << init;
  344. switch (init.kind()) {
  345. default:
  346. CARBON_FATAL() << "Initialization from unexpected node " << init;
  347. case SemIR::NodeKind::StructLiteral:
  348. case SemIR::NodeKind::TupleLiteral:
  349. CARBON_FATAL() << init << " is not modeled as initializing yet";
  350. case SemIR::NodeKind::StubReference:
  351. init_id = init.GetAsStubReference();
  352. continue;
  353. case SemIR::NodeKind::Call: {
  354. // If the callee has a return slot, point it at our target.
  355. auto [refs_id, callee_id] = init.GetAsCall();
  356. if (semantics_ir().GetFunction(callee_id).return_slot_id.is_valid()) {
  357. // Replace the return slot with our given target, and remove the
  358. // tentatively-created temporary.
  359. auto temporary_id = std::exchange(
  360. semantics_ir().GetNodeBlock(refs_id).back(), target_id);
  361. auto temporary = semantics_ir().GetNode(temporary_id);
  362. CARBON_CHECK(temporary.kind() == SemIR::NodeKind::TemporaryStorage)
  363. << "Return slot for function call does not contain a temporary; "
  364. << "initialized multiple times? Have " << temporary;
  365. semantics_ir().ReplaceNode(
  366. temporary_id, SemIR::Node::NoOp::Make(temporary.parse_node()));
  367. }
  368. return;
  369. }
  370. }
  371. }
  372. }
  373. auto Context::HandleDiscardedExpression(SemIR::NodeId expr_id) -> void {
  374. // If we discard an initializing expression, materialize it first.
  375. if (SemIR::GetExpressionCategory(semantics_ir(), expr_id) ==
  376. SemIR::ExpressionCategory::Initializing) {
  377. FinalizeTemporary(expr_id, /*discarded=*/true);
  378. }
  379. // TODO: This will eventually need to do some "do not discard" analysis.
  380. (void)expr_id;
  381. }
  382. auto Context::ImplicitAsForArgs(Parse::Node call_parse_node,
  383. SemIR::NodeBlockId arg_refs_id,
  384. Parse::Node param_parse_node,
  385. SemIR::NodeBlockId param_refs_id) -> bool {
  386. // If both arguments and parameters are empty, return quickly. Otherwise,
  387. // we'll fetch both so that errors are consistent.
  388. if (arg_refs_id == SemIR::NodeBlockId::Empty &&
  389. param_refs_id == SemIR::NodeBlockId::Empty) {
  390. return true;
  391. }
  392. auto& arg_refs = semantics_ir_->GetNodeBlock(arg_refs_id);
  393. const auto& param_refs = semantics_ir_->GetNodeBlock(param_refs_id);
  394. // If sizes mismatch, fail early.
  395. if (arg_refs.size() != param_refs.size()) {
  396. CARBON_DIAGNOSTIC(CallArgCountMismatch, Error,
  397. "{0} argument(s) passed to function expecting "
  398. "{1} argument(s).",
  399. int, int);
  400. CARBON_DIAGNOSTIC(InCallToFunction, Note,
  401. "Calling function declared here.");
  402. emitter_
  403. ->Build(call_parse_node, CallArgCountMismatch, arg_refs.size(),
  404. param_refs.size())
  405. .Note(param_parse_node, InCallToFunction)
  406. .Emit();
  407. return false;
  408. }
  409. if (param_refs.empty()) {
  410. return true;
  411. }
  412. int diag_param_index;
  413. DiagnosticAnnotationScope annotate_diagnostics(emitter_, [&](auto& builder) {
  414. CARBON_DIAGNOSTIC(InCallToFunctionParam, Note,
  415. "Initializing parameter {0} of function declared here.",
  416. int);
  417. builder.Note(param_parse_node, InCallToFunctionParam, diag_param_index + 1);
  418. });
  419. // Check type conversions per-element.
  420. for (auto [i, value_id, param_ref] : llvm::enumerate(arg_refs, param_refs)) {
  421. diag_param_index = i;
  422. auto as_type_id = semantics_ir_->GetNode(param_ref).type_id();
  423. // TODO: Convert to the proper expression category. For now, we assume
  424. // parameters are all `let` bindings.
  425. value_id = ConvertToValueOfType(call_parse_node, value_id, as_type_id);
  426. if (value_id == SemIR::NodeId::BuiltinError) {
  427. return false;
  428. }
  429. arg_refs[i] = value_id;
  430. }
  431. return true;
  432. }
  433. auto Context::ImplicitAs(Parse::Node parse_node, SemIR::NodeId value_id,
  434. SemIR::TypeId as_type_id) -> SemIR::NodeId {
  435. // Start by making sure both sides are valid. If any part is invalid, the
  436. // result is invalid and we shouldn't error.
  437. if (value_id == SemIR::NodeId::BuiltinError) {
  438. // If the value is invalid, we can't do much, but do "succeed".
  439. return value_id;
  440. }
  441. auto value = semantics_ir_->GetNode(value_id);
  442. auto value_type_id = value.type_id();
  443. if (value_type_id == SemIR::TypeId::Error ||
  444. as_type_id == SemIR::TypeId::Error) {
  445. return SemIR::NodeId::BuiltinError;
  446. }
  447. if (value_type_id == as_type_id) {
  448. return value_id;
  449. }
  450. auto as_type = semantics_ir_->GetTypeAllowBuiltinTypes(as_type_id);
  451. auto as_type_node = semantics_ir_->GetNode(as_type);
  452. if (as_type_node.kind() == SemIR::NodeKind::ArrayType) {
  453. auto [bound_node_id, element_type_id] = as_type_node.GetAsArrayType();
  454. // To resolve lambda issue.
  455. auto element_type = element_type_id;
  456. auto value_type_node = semantics_ir_->GetNode(
  457. semantics_ir_->GetTypeAllowBuiltinTypes(value_type_id));
  458. if (value_type_node.kind() == SemIR::NodeKind::TupleType) {
  459. auto tuple_type_block_id = value_type_node.GetAsTupleType();
  460. const auto& type_block = semantics_ir_->GetTypeBlock(tuple_type_block_id);
  461. if (type_block.size() ==
  462. semantics_ir_->GetArrayBoundValue(bound_node_id) &&
  463. std::all_of(type_block.begin(), type_block.end(),
  464. [&](auto type) { return type == element_type; })) {
  465. // TODO: We should convert an initializing expression of tuple type
  466. // to an initializing expression of array type.
  467. value_id = ConvertToValueExpression(value_id);
  468. return AddNode(SemIR::Node::ArrayValue::Make(value.parse_node(),
  469. as_type_id, value_id));
  470. }
  471. }
  472. }
  473. if (as_type_id == SemIR::TypeId::TypeType) {
  474. if (value.kind() == SemIR::NodeKind::TupleLiteral) {
  475. auto tuple_block_id = value.GetAsTupleLiteral();
  476. llvm::SmallVector<SemIR::TypeId> type_ids;
  477. // If it is empty tuple type, we don't fetch anything.
  478. if (tuple_block_id != SemIR::NodeBlockId::Empty) {
  479. const auto& tuple_block = semantics_ir_->GetNodeBlock(tuple_block_id);
  480. for (auto tuple_node_id : tuple_block) {
  481. // TODO: Eventually ExpressionAsType will insert implicit cast
  482. // instructions. When that happens, this will need to verify the full
  483. // tuple conversion will work before calling it.
  484. type_ids.push_back(
  485. ExpressionAsType(value.parse_node(), tuple_node_id));
  486. }
  487. }
  488. auto tuple_type_id =
  489. CanonicalizeTupleType(value.parse_node(), std::move(type_ids));
  490. return semantics_ir_->GetTypeAllowBuiltinTypes(tuple_type_id);
  491. }
  492. // When converting `{}` to a type, the result is `{} as Type`.
  493. if (value.kind() == SemIR::NodeKind::StructLiteral &&
  494. value.GetAsStructLiteral() == SemIR::NodeBlockId::Empty) {
  495. return semantics_ir_->GetType(value_type_id);
  496. }
  497. }
  498. // TODO: Handle ImplicitAs for compatible structs and tuples.
  499. CARBON_DIAGNOSTIC(ImplicitAsConversionFailure, Error,
  500. "Cannot implicitly convert from `{0}` to `{1}`.",
  501. std::string, std::string);
  502. emitter_
  503. ->Build(parse_node, ImplicitAsConversionFailure,
  504. semantics_ir_->StringifyType(
  505. semantics_ir_->GetNode(value_id).type_id()),
  506. semantics_ir_->StringifyType(as_type_id))
  507. .Emit();
  508. return SemIR::NodeId::BuiltinError;
  509. }
  510. auto Context::ParamOrArgStart() -> void { params_or_args_stack_.Push(); }
  511. auto Context::ParamOrArgComma(bool for_args) -> void {
  512. ParamOrArgSave(for_args);
  513. }
  514. auto Context::ParamOrArgEnd(bool for_args, Parse::NodeKind start_kind)
  515. -> SemIR::NodeBlockId {
  516. if (parse_tree_->node_kind(node_stack_.PeekParseNode()) != start_kind) {
  517. ParamOrArgSave(for_args);
  518. }
  519. return params_or_args_stack_.Pop();
  520. }
  521. auto Context::ParamOrArgSave(bool for_args) -> void {
  522. auto [entry_parse_node, entry_node_id] =
  523. node_stack_.PopExpressionWithParseNode();
  524. if (for_args) {
  525. // For an argument, we add a stub reference to the expression on the top of
  526. // the stack. There may not be anything on the IR prior to this.
  527. entry_node_id = AddNode(SemIR::Node::StubReference::Make(
  528. entry_parse_node, semantics_ir_->GetNode(entry_node_id).type_id(),
  529. entry_node_id));
  530. }
  531. // Save the param or arg ID.
  532. auto& params_or_args =
  533. semantics_ir_->GetNodeBlock(params_or_args_stack_.PeekForAdd());
  534. params_or_args.push_back(entry_node_id);
  535. }
  536. auto Context::CanonicalizeTypeImpl(
  537. SemIR::NodeKind kind,
  538. llvm::function_ref<void(llvm::FoldingSetNodeID& canonical_id)> profile_type,
  539. llvm::function_ref<SemIR::NodeId()> make_node) -> SemIR::TypeId {
  540. llvm::FoldingSetNodeID canonical_id;
  541. kind.Profile(canonical_id);
  542. profile_type(canonical_id);
  543. void* insert_pos;
  544. auto* node =
  545. canonical_type_nodes_.FindNodeOrInsertPos(canonical_id, insert_pos);
  546. if (node != nullptr) {
  547. return node->type_id();
  548. }
  549. auto node_id = make_node();
  550. auto type_id = semantics_ir_->AddType(node_id);
  551. CARBON_CHECK(canonical_types_.insert({node_id, type_id}).second);
  552. type_node_storage_.push_back(
  553. std::make_unique<TypeNode>(canonical_id, type_id));
  554. // In a debug build, check that our insertion position is still valid. It
  555. // could have been invalidated by a misbehaving `make_node`.
  556. CARBON_DCHECK([&] {
  557. void* check_insert_pos;
  558. auto* check_node = canonical_type_nodes_.FindNodeOrInsertPos(
  559. canonical_id, check_insert_pos);
  560. return !check_node && insert_pos == check_insert_pos;
  561. }()) << "Type was created recursively during canonicalization";
  562. canonical_type_nodes_.InsertNode(type_node_storage_.back().get(), insert_pos);
  563. return type_id;
  564. }
  565. // Compute a fingerprint for a tuple type, for use as a key in a folding set.
  566. static auto ProfileTupleType(const llvm::SmallVector<SemIR::TypeId>& type_ids,
  567. llvm::FoldingSetNodeID& canonical_id) -> void {
  568. for (const auto& type_id : type_ids) {
  569. canonical_id.AddInteger(type_id.index);
  570. }
  571. }
  572. // Compute a fingerprint for a type, for use as a key in a folding set.
  573. static auto ProfileType(Context& semantics_context, SemIR::Node node,
  574. llvm::FoldingSetNodeID& canonical_id) -> void {
  575. switch (node.kind()) {
  576. case SemIR::NodeKind::ArrayType: {
  577. auto [bound_id, element_type_id] = node.GetAsArrayType();
  578. canonical_id.AddInteger(
  579. semantics_context.semantics_ir().GetArrayBoundValue(bound_id));
  580. canonical_id.AddInteger(element_type_id.index);
  581. break;
  582. }
  583. case SemIR::NodeKind::Builtin:
  584. canonical_id.AddInteger(node.GetAsBuiltin().AsInt());
  585. break;
  586. case SemIR::NodeKind::CrossReference: {
  587. // TODO: Cross-references should be canonicalized by looking at their
  588. // target rather than treating them as new unique types.
  589. auto [xref_id, node_id] = node.GetAsCrossReference();
  590. canonical_id.AddInteger(xref_id.index);
  591. canonical_id.AddInteger(node_id.index);
  592. break;
  593. }
  594. case SemIR::NodeKind::ConstType:
  595. canonical_id.AddInteger(
  596. semantics_context.GetUnqualifiedType(node.GetAsConstType()).index);
  597. break;
  598. case SemIR::NodeKind::PointerType:
  599. canonical_id.AddInteger(node.GetAsPointerType().index);
  600. break;
  601. case SemIR::NodeKind::StructType: {
  602. auto refs =
  603. semantics_context.semantics_ir().GetNodeBlock(node.GetAsStructType());
  604. for (const auto& ref_id : refs) {
  605. auto ref = semantics_context.semantics_ir().GetNode(ref_id);
  606. auto [name_id, type_id] = ref.GetAsStructTypeField();
  607. canonical_id.AddInteger(name_id.index);
  608. canonical_id.AddInteger(type_id.index);
  609. }
  610. break;
  611. }
  612. case SemIR::NodeKind::StubReference: {
  613. // We rely on stub references not referring to each other to ensure we
  614. // only recurse once here.
  615. auto inner =
  616. semantics_context.semantics_ir().GetNode(node.GetAsStubReference());
  617. CARBON_CHECK(inner.kind() != SemIR::NodeKind::StubReference)
  618. << "A stub reference should never refer to another stub reference.";
  619. ProfileType(semantics_context, inner, canonical_id);
  620. break;
  621. }
  622. case SemIR::NodeKind::TupleType:
  623. ProfileTupleType(
  624. semantics_context.semantics_ir().GetTypeBlock(node.GetAsTupleType()),
  625. canonical_id);
  626. break;
  627. default:
  628. CARBON_FATAL() << "Unexpected type node " << node;
  629. }
  630. }
  631. auto Context::CanonicalizeTypeAndAddNodeIfNew(SemIR::Node node)
  632. -> SemIR::TypeId {
  633. auto profile_node = [&](llvm::FoldingSetNodeID& canonical_id) {
  634. ProfileType(*this, node, canonical_id);
  635. };
  636. auto make_node = [&] { return AddNode(node); };
  637. return CanonicalizeTypeImpl(node.kind(), profile_node, make_node);
  638. }
  639. auto Context::CanonicalizeType(SemIR::NodeId node_id) -> SemIR::TypeId {
  640. auto it = canonical_types_.find(node_id);
  641. if (it != canonical_types_.end()) {
  642. return it->second;
  643. }
  644. auto node = semantics_ir_->GetNode(node_id);
  645. auto profile_node = [&](llvm::FoldingSetNodeID& canonical_id) {
  646. ProfileType(*this, node, canonical_id);
  647. };
  648. auto make_node = [&] { return node_id; };
  649. return CanonicalizeTypeImpl(node.kind(), profile_node, make_node);
  650. }
  651. auto Context::CanonicalizeStructType(Parse::Node parse_node,
  652. SemIR::NodeBlockId refs_id)
  653. -> SemIR::TypeId {
  654. return CanonicalizeTypeAndAddNodeIfNew(SemIR::Node::StructType::Make(
  655. parse_node, SemIR::TypeId::TypeType, refs_id));
  656. }
  657. auto Context::CanonicalizeTupleType(Parse::Node parse_node,
  658. llvm::SmallVector<SemIR::TypeId>&& type_ids)
  659. -> SemIR::TypeId {
  660. // Defer allocating a SemIR::TypeBlockId until we know this is a new type.
  661. auto profile_tuple = [&](llvm::FoldingSetNodeID& canonical_id) {
  662. ProfileTupleType(type_ids, canonical_id);
  663. };
  664. auto make_tuple_node = [&] {
  665. auto type_block_id = semantics_ir_->AddTypeBlock();
  666. auto& type_block = semantics_ir_->GetTypeBlock(type_block_id);
  667. type_block = std::move(type_ids);
  668. return AddNode(SemIR::Node::TupleType::Make(
  669. parse_node, SemIR::TypeId::TypeType, type_block_id));
  670. };
  671. return CanonicalizeTypeImpl(SemIR::NodeKind::TupleType, profile_tuple,
  672. make_tuple_node);
  673. }
  674. auto Context::GetPointerType(Parse::Node parse_node,
  675. SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  676. return CanonicalizeTypeAndAddNodeIfNew(SemIR::Node::PointerType::Make(
  677. parse_node, SemIR::TypeId::TypeType, pointee_type_id));
  678. }
  679. auto Context::GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId {
  680. SemIR::Node type_node =
  681. semantics_ir_->GetNode(semantics_ir_->GetTypeAllowBuiltinTypes(type_id));
  682. if (type_node.kind() == SemIR::NodeKind::ConstType) {
  683. return type_node.GetAsConstType();
  684. }
  685. return type_id;
  686. }
  687. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  688. node_stack_.PrintForStackDump(output);
  689. node_block_stack_.PrintForStackDump(output);
  690. params_or_args_stack_.PrintForStackDump(output);
  691. args_type_info_stack_.PrintForStackDump(output);
  692. }
  693. } // namespace Carbon::Check