semantics_context.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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/semantics/semantics_context.h"
  5. #include <utility>
  6. #include "common/check.h"
  7. #include "common/vlog.h"
  8. #include "toolchain/diagnostics/diagnostic_kind.h"
  9. #include "toolchain/lexer/tokenized_buffer.h"
  10. #include "toolchain/parser/parse_node_kind.h"
  11. #include "toolchain/semantics/semantics_declaration_name_stack.h"
  12. #include "toolchain/semantics/semantics_ir.h"
  13. #include "toolchain/semantics/semantics_node.h"
  14. #include "toolchain/semantics/semantics_node_block_stack.h"
  15. #include "toolchain/semantics/semantics_node_kind.h"
  16. namespace Carbon {
  17. SemanticsContext::SemanticsContext(const TokenizedBuffer& tokens,
  18. DiagnosticEmitter<ParseTree::Node>& emitter,
  19. const ParseTree& parse_tree,
  20. SemanticsIR& 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(
  35. {SemanticsNodeId::BuiltinError, SemanticsTypeId::Error});
  36. canonical_types_.insert(
  37. {SemanticsNodeId::BuiltinTypeType, SemanticsTypeId::TypeType});
  38. }
  39. auto SemanticsContext::TODO(ParseTree::Node parse_node, std::string label)
  40. -> bool {
  41. CARBON_DIAGNOSTIC(SemanticsTodo, Error, "Semantics TODO: {0}", std::string);
  42. emitter_->Emit(parse_node, SemanticsTodo, std::move(label));
  43. return false;
  44. }
  45. auto SemanticsContext::VerifyOnFinish() -> void {
  46. // Information in all the various context objects should be cleaned up as
  47. // various pieces of context go out of scope. At this point, nothing should
  48. // remain.
  49. // node_stack_ will still contain top-level entities.
  50. CARBON_CHECK(name_lookup_.empty()) << name_lookup_.size();
  51. CARBON_CHECK(scope_stack_.empty()) << scope_stack_.size();
  52. CARBON_CHECK(node_block_stack_.empty()) << node_block_stack_.size();
  53. CARBON_CHECK(params_or_args_stack_.empty()) << params_or_args_stack_.size();
  54. }
  55. auto SemanticsContext::AddNode(SemanticsNode node) -> SemanticsNodeId {
  56. return AddNodeToBlock(node_block_stack_.PeekForAdd(), node);
  57. }
  58. auto SemanticsContext::AddNodeToBlock(SemanticsNodeBlockId block,
  59. SemanticsNode node) -> SemanticsNodeId {
  60. CARBON_VLOG() << "AddNode " << block << ": " << node << "\n";
  61. return semantics_ir_->AddNode(block, node);
  62. }
  63. auto SemanticsContext::AddNodeAndPush(ParseTree::Node parse_node,
  64. SemanticsNode node) -> void {
  65. auto node_id = AddNode(node);
  66. node_stack_.Push(parse_node, node_id);
  67. }
  68. auto SemanticsContext::DiagnoseDuplicateName(ParseTree::Node parse_node,
  69. SemanticsNodeId prev_def_id)
  70. -> void {
  71. CARBON_DIAGNOSTIC(NameDeclarationDuplicate, Error,
  72. "Duplicate name being declared in the same scope.");
  73. CARBON_DIAGNOSTIC(NameDeclarationPrevious, Note,
  74. "Name is previously declared here.");
  75. auto prev_def = semantics_ir_->GetNode(prev_def_id);
  76. emitter_->Build(parse_node, NameDeclarationDuplicate)
  77. .Note(prev_def.parse_node(), NameDeclarationPrevious)
  78. .Emit();
  79. }
  80. auto SemanticsContext::DiagnoseNameNotFound(ParseTree::Node parse_node,
  81. SemanticsStringId name_id) -> void {
  82. CARBON_DIAGNOSTIC(NameNotFound, Error, "Name {0} not found", llvm::StringRef);
  83. emitter_->Emit(parse_node, NameNotFound, semantics_ir_->GetString(name_id));
  84. }
  85. auto SemanticsContext::AddNameToLookup(ParseTree::Node name_node,
  86. SemanticsStringId name_id,
  87. SemanticsNodeId target_id) -> void {
  88. if (current_scope().names.insert(name_id).second) {
  89. name_lookup_[name_id].push_back(target_id);
  90. } else {
  91. DiagnoseDuplicateName(name_node, name_lookup_[name_id].back());
  92. }
  93. }
  94. auto SemanticsContext::LookupName(ParseTree::Node parse_node,
  95. SemanticsStringId name_id,
  96. SemanticsNameScopeId scope_id,
  97. bool print_diagnostics) -> SemanticsNodeId {
  98. if (scope_id == SemanticsNameScopeId::Invalid) {
  99. auto it = name_lookup_.find(name_id);
  100. if (it == name_lookup_.end()) {
  101. if (print_diagnostics) {
  102. DiagnoseNameNotFound(parse_node, name_id);
  103. }
  104. return SemanticsNodeId::BuiltinError;
  105. }
  106. CARBON_CHECK(!it->second.empty())
  107. << "Should have been erased: " << semantics_ir_->GetString(name_id);
  108. // TODO: Check for ambiguous lookups.
  109. return it->second.back();
  110. } else {
  111. const auto& scope = semantics_ir_->GetNameScope(scope_id);
  112. auto it = scope.find(name_id);
  113. if (it == scope.end()) {
  114. if (print_diagnostics) {
  115. DiagnoseNameNotFound(parse_node, name_id);
  116. }
  117. return SemanticsNodeId::BuiltinError;
  118. }
  119. return it->second;
  120. }
  121. }
  122. auto SemanticsContext::PushScope() -> void { scope_stack_.push_back({}); }
  123. auto SemanticsContext::PopScope() -> void {
  124. auto scope = scope_stack_.pop_back_val();
  125. for (const auto& str_id : scope.names) {
  126. auto it = name_lookup_.find(str_id);
  127. if (it->second.size() == 1) {
  128. // Erase names that no longer resolve.
  129. name_lookup_.erase(it);
  130. } else {
  131. it->second.pop_back();
  132. }
  133. }
  134. }
  135. template <typename BranchNode, typename... Args>
  136. static auto AddDominatedBlockAndBranchImpl(SemanticsContext& context,
  137. ParseTree::Node parse_node,
  138. Args... args)
  139. -> SemanticsNodeBlockId {
  140. if (!context.node_block_stack().is_current_block_reachable()) {
  141. return SemanticsNodeBlockId::Unreachable;
  142. }
  143. auto block_id = context.semantics_ir().AddNodeBlock();
  144. context.AddNode(BranchNode::Make(parse_node, block_id, args...));
  145. return block_id;
  146. }
  147. auto SemanticsContext::AddDominatedBlockAndBranch(ParseTree::Node parse_node)
  148. -> SemanticsNodeBlockId {
  149. return AddDominatedBlockAndBranchImpl<SemanticsNode::Branch>(*this,
  150. parse_node);
  151. }
  152. auto SemanticsContext::AddDominatedBlockAndBranchWithArg(
  153. ParseTree::Node parse_node, SemanticsNodeId arg_id)
  154. -> SemanticsNodeBlockId {
  155. return AddDominatedBlockAndBranchImpl<SemanticsNode::BranchWithArg>(
  156. *this, parse_node, arg_id);
  157. }
  158. auto SemanticsContext::AddDominatedBlockAndBranchIf(ParseTree::Node parse_node,
  159. SemanticsNodeId cond_id)
  160. -> SemanticsNodeBlockId {
  161. return AddDominatedBlockAndBranchImpl<SemanticsNode::BranchIf>(
  162. *this, parse_node, cond_id);
  163. }
  164. auto SemanticsContext::AddConvergenceBlockAndPush(
  165. ParseTree::Node parse_node,
  166. std::initializer_list<SemanticsNodeBlockId> blocks) -> void {
  167. CARBON_CHECK(blocks.size() >= 2) << "no convergence";
  168. SemanticsNodeBlockId new_block_id = SemanticsNodeBlockId::Unreachable;
  169. for (SemanticsNodeBlockId block_id : blocks) {
  170. if (block_id != SemanticsNodeBlockId::Unreachable) {
  171. if (new_block_id == SemanticsNodeBlockId::Unreachable) {
  172. new_block_id = semantics_ir().AddNodeBlock();
  173. }
  174. AddNodeToBlock(block_id,
  175. SemanticsNode::Branch::Make(parse_node, new_block_id));
  176. }
  177. }
  178. node_block_stack().Push(new_block_id);
  179. }
  180. auto SemanticsContext::AddConvergenceBlockWithArgAndPush(
  181. ParseTree::Node parse_node,
  182. std::initializer_list<std::pair<SemanticsNodeBlockId, SemanticsNodeId>>
  183. blocks_and_args) -> SemanticsNodeId {
  184. CARBON_CHECK(blocks_and_args.size() >= 2) << "no convergence";
  185. SemanticsNodeBlockId new_block_id = SemanticsNodeBlockId::Unreachable;
  186. for (auto [block_id, arg_id] : blocks_and_args) {
  187. if (block_id != SemanticsNodeBlockId::Unreachable) {
  188. if (new_block_id == SemanticsNodeBlockId::Unreachable) {
  189. new_block_id = semantics_ir().AddNodeBlock();
  190. }
  191. AddNodeToBlock(block_id, SemanticsNode::BranchWithArg::Make(
  192. parse_node, new_block_id, arg_id));
  193. }
  194. }
  195. node_block_stack().Push(new_block_id);
  196. // Acquire the result value.
  197. SemanticsTypeId result_type_id =
  198. semantics_ir().GetNode(blocks_and_args.begin()->second).type_id();
  199. return AddNode(
  200. SemanticsNode::BlockArg::Make(parse_node, result_type_id, new_block_id));
  201. }
  202. // Add the current code block to the enclosing function.
  203. auto SemanticsContext::AddCurrentCodeBlockToFunction() -> void {
  204. CARBON_CHECK(!node_block_stack().empty()) << "no current code block";
  205. CARBON_CHECK(!return_scope_stack().empty()) << "no current function";
  206. if (!node_block_stack().is_current_block_reachable()) {
  207. // Don't include unreachable blocks in the function.
  208. return;
  209. }
  210. auto function_id = semantics_ir()
  211. .GetNode(return_scope_stack().back())
  212. .GetAsFunctionDeclaration();
  213. semantics_ir()
  214. .GetFunction(function_id)
  215. .body_block_ids.push_back(node_block_stack().PeekForAdd());
  216. }
  217. auto SemanticsContext::is_current_position_reachable() -> bool {
  218. switch (auto block_id = node_block_stack().Peek(); block_id.index) {
  219. case SemanticsNodeBlockId::Unreachable.index: {
  220. return false;
  221. }
  222. case SemanticsNodeBlockId::Invalid.index: {
  223. return true;
  224. }
  225. default: {
  226. // Our current position is at the end of a real block. That position is
  227. // reachable unless the previous instruction is a terminator instruction.
  228. const auto& block_contents = semantics_ir().GetNodeBlock(block_id);
  229. if (block_contents.empty()) {
  230. return true;
  231. }
  232. const auto& last_node = semantics_ir().GetNode(block_contents.back());
  233. return last_node.kind().terminator_kind() !=
  234. SemanticsTerminatorKind::Terminator;
  235. }
  236. }
  237. }
  238. auto SemanticsContext::ImplicitAsForArgs(
  239. SemanticsNodeBlockId arg_refs_id, ParseTree::Node param_parse_node,
  240. SemanticsNodeBlockId param_refs_id,
  241. DiagnosticEmitter<ParseTree::Node>::DiagnosticBuilder* diagnostic) -> bool {
  242. // If both arguments and parameters are empty, return quickly. Otherwise,
  243. // we'll fetch both so that errors are consistent.
  244. if (arg_refs_id == SemanticsNodeBlockId::Empty &&
  245. param_refs_id == SemanticsNodeBlockId::Empty) {
  246. return true;
  247. }
  248. auto arg_refs = semantics_ir_->GetNodeBlock(arg_refs_id);
  249. auto param_refs = semantics_ir_->GetNodeBlock(param_refs_id);
  250. // If sizes mismatch, fail early.
  251. if (arg_refs.size() != param_refs.size()) {
  252. CARBON_CHECK(diagnostic != nullptr) << "Should have validated first";
  253. CARBON_DIAGNOSTIC(CallArgCountMismatch, Note,
  254. "Function cannot be used: Received {0} argument(s), but "
  255. "require {1} argument(s).",
  256. int, int);
  257. diagnostic->Note(param_parse_node, CallArgCountMismatch, arg_refs.size(),
  258. param_refs.size());
  259. return false;
  260. }
  261. // Check type conversions per-element.
  262. // TODO: arg_ir_id is passed so that implicit conversions can be inserted.
  263. // It's currently not supported, but will be needed.
  264. for (size_t i = 0; i < arg_refs.size(); ++i) {
  265. auto value_id = arg_refs[i];
  266. auto as_type_id = semantics_ir_->GetNode(param_refs[i]).type_id();
  267. if (ImplicitAsImpl(value_id, as_type_id,
  268. diagnostic == nullptr ? &value_id : nullptr) ==
  269. ImplicitAsKind::Incompatible) {
  270. CARBON_CHECK(diagnostic != nullptr) << "Should have validated first";
  271. CARBON_DIAGNOSTIC(CallArgTypeMismatch, Note,
  272. "Function cannot be used: Cannot implicityly convert "
  273. "argument {0} from `{1}` to `{2}`.",
  274. size_t, std::string, std::string);
  275. diagnostic->Note(param_parse_node, CallArgTypeMismatch, i,
  276. semantics_ir_->StringifyType(
  277. semantics_ir_->GetNode(value_id).type_id()),
  278. semantics_ir_->StringifyType(as_type_id));
  279. return false;
  280. }
  281. }
  282. return true;
  283. }
  284. auto SemanticsContext::ImplicitAsRequired(ParseTree::Node parse_node,
  285. SemanticsNodeId value_id,
  286. SemanticsTypeId as_type_id)
  287. -> SemanticsNodeId {
  288. SemanticsNodeId output_value_id = value_id;
  289. if (ImplicitAsImpl(value_id, as_type_id, &output_value_id) ==
  290. ImplicitAsKind::Incompatible) {
  291. // Only error when the system is trying to use the result.
  292. CARBON_DIAGNOSTIC(ImplicitAsConversionFailure, Error,
  293. "Cannot implicitly convert from `{0}` to `{1}`.",
  294. std::string, std::string);
  295. emitter_
  296. ->Build(parse_node, ImplicitAsConversionFailure,
  297. semantics_ir_->StringifyType(
  298. semantics_ir_->GetNode(value_id).type_id()),
  299. semantics_ir_->StringifyType(as_type_id))
  300. .Emit();
  301. }
  302. return output_value_id;
  303. }
  304. auto SemanticsContext::ImplicitAsBool(ParseTree::Node parse_node,
  305. SemanticsNodeId value_id)
  306. -> SemanticsNodeId {
  307. return ImplicitAsRequired(parse_node, value_id,
  308. CanonicalizeType(SemanticsNodeId::BuiltinBoolType));
  309. }
  310. auto SemanticsContext::ImplicitAsImpl(SemanticsNodeId value_id,
  311. SemanticsTypeId as_type_id,
  312. SemanticsNodeId* output_value_id)
  313. -> ImplicitAsKind {
  314. // Start by making sure both sides are valid. If any part is invalid, the
  315. // result is invalid and we shouldn't error.
  316. if (value_id == SemanticsNodeId::BuiltinError) {
  317. // If the value is invalid, we can't do much, but do "succeed".
  318. return ImplicitAsKind::Identical;
  319. }
  320. auto value = semantics_ir_->GetNode(value_id);
  321. auto value_type_id = value.type_id();
  322. if (value_type_id == SemanticsTypeId::Error) {
  323. return ImplicitAsKind::Identical;
  324. }
  325. if (as_type_id == SemanticsTypeId::Error) {
  326. // Although the target type is invalid, this still changes the value.
  327. if (output_value_id != nullptr) {
  328. *output_value_id = SemanticsNodeId::BuiltinError;
  329. }
  330. return ImplicitAsKind::Compatible;
  331. }
  332. if (value_type_id == as_type_id) {
  333. // Type doesn't need to change.
  334. return ImplicitAsKind::Identical;
  335. }
  336. if (as_type_id == SemanticsTypeId::TypeType) {
  337. if (value.kind() == SemanticsNodeKind::TupleValue) {
  338. auto tuple_block_id = value.GetAsTupleValue();
  339. llvm::SmallVector<SemanticsTypeId> type_ids;
  340. // If it is empty tuple type, we don't fetch anything.
  341. if (tuple_block_id != SemanticsNodeBlockId::Empty) {
  342. const auto& tuple_block = semantics_ir_->GetNodeBlock(tuple_block_id);
  343. for (auto tuple_node_id : tuple_block) {
  344. // TODO: Eventually ExpressionAsType will insert implicit cast
  345. // instructions. When that happens, this will need to verify the full
  346. // tuple conversion will work before calling it.
  347. type_ids.push_back(
  348. ExpressionAsType(value.parse_node(), tuple_node_id));
  349. }
  350. }
  351. auto tuple_type_id =
  352. CanonicalizeTupleType(value.parse_node(), std::move(type_ids));
  353. if (output_value_id != nullptr) {
  354. *output_value_id =
  355. semantics_ir_->GetTypeAllowBuiltinTypes(tuple_type_id);
  356. }
  357. return ImplicitAsKind::Compatible;
  358. }
  359. // When converting `{}` to a type, the result is `{} as Type`.
  360. if (value.kind() == SemanticsNodeKind::StructValue &&
  361. value.GetAsStructValue() == SemanticsNodeBlockId::Empty) {
  362. if (output_value_id != nullptr) {
  363. *output_value_id = semantics_ir_->GetType(value_type_id);
  364. }
  365. return ImplicitAsKind::Compatible;
  366. }
  367. }
  368. // TODO: Handle ImplicitAs for compatible structs and tuples.
  369. if (output_value_id != nullptr) {
  370. *output_value_id = SemanticsNodeId::BuiltinError;
  371. }
  372. return ImplicitAsKind::Incompatible;
  373. }
  374. auto SemanticsContext::ParamOrArgStart() -> void {
  375. params_or_args_stack_.Push();
  376. }
  377. auto SemanticsContext::ParamOrArgComma(bool for_args) -> void {
  378. ParamOrArgSave(for_args);
  379. }
  380. auto SemanticsContext::ParamOrArgEnd(bool for_args, ParseNodeKind start_kind)
  381. -> SemanticsNodeBlockId {
  382. if (parse_tree_->node_kind(node_stack_.PeekParseNode()) != start_kind) {
  383. ParamOrArgSave(for_args);
  384. }
  385. return params_or_args_stack_.Pop();
  386. }
  387. auto SemanticsContext::ParamOrArgSave(bool for_args) -> void {
  388. SemanticsNodeId param_or_arg_id = SemanticsNodeId::Invalid;
  389. if (for_args) {
  390. // For an argument, we add a stub reference to the expression on the top of
  391. // the stack. There may not be anything on the IR prior to this.
  392. auto [entry_parse_node, entry_node_id] =
  393. node_stack_.PopExpressionWithParseNode();
  394. param_or_arg_id = AddNode(SemanticsNode::StubReference::Make(
  395. entry_parse_node, semantics_ir_->GetNode(entry_node_id).type_id(),
  396. entry_node_id));
  397. } else {
  398. // For a parameter, there should always be something in the IR.
  399. node_stack_.PopAndIgnore();
  400. auto ir_id = node_block_stack_.Peek();
  401. CARBON_CHECK(ir_id.is_valid());
  402. auto& ir = semantics_ir_->GetNodeBlock(ir_id);
  403. CARBON_CHECK(!ir.empty()) << "Should have had a param";
  404. param_or_arg_id = ir.back();
  405. }
  406. // Save the param or arg ID.
  407. auto& params_or_args =
  408. semantics_ir_->GetNodeBlock(params_or_args_stack_.PeekForAdd());
  409. params_or_args.push_back(param_or_arg_id);
  410. }
  411. auto SemanticsContext::CanonicalizeType(SemanticsNodeId node_id)
  412. -> SemanticsTypeId {
  413. auto node = semantics_ir_->GetNode(node_id);
  414. if (node.kind() == SemanticsNodeKind::StubReference) {
  415. node_id = node.GetAsStubReference();
  416. CARBON_CHECK(semantics_ir_->GetNode(node_id).kind() !=
  417. SemanticsNodeKind::StubReference)
  418. << "Stub reference should not point to another stub reference";
  419. }
  420. auto it = canonical_types_.find(node_id);
  421. if (it != canonical_types_.end()) {
  422. return it->second;
  423. }
  424. auto type_id = semantics_ir_->AddType(node_id);
  425. CARBON_CHECK(canonical_types_.insert({node_id, type_id}).second);
  426. return type_id;
  427. }
  428. auto SemanticsContext::CanonicalizeStructType(ParseTree::Node parse_node,
  429. SemanticsNodeBlockId refs_id)
  430. -> SemanticsTypeId {
  431. // Construct the field structure for lookup.
  432. auto refs = semantics_ir_->GetNodeBlock(refs_id);
  433. llvm::FoldingSetNodeID canonical_id;
  434. for (const auto& ref_id : refs) {
  435. auto ref = semantics_ir_->GetNode(ref_id);
  436. canonical_id.AddInteger(ref.GetAsStructTypeField().index);
  437. canonical_id.AddInteger(ref.type_id().index);
  438. }
  439. // If a struct with matching fields was already created, reuse it.
  440. void* insert_pos;
  441. auto* node =
  442. canonical_struct_types_.FindNodeOrInsertPos(canonical_id, insert_pos);
  443. if (node != nullptr) {
  444. return node->type_id();
  445. }
  446. // The struct doesn't already exist, so create and store it as canonical.
  447. auto node_id = AddNode(SemanticsNode::StructType::Make(
  448. parse_node, SemanticsTypeId::TypeType, refs_id));
  449. auto type_id = semantics_ir_->AddType(node_id);
  450. CARBON_CHECK(canonical_types_.insert({node_id, type_id}).second);
  451. canonical_types_nodes_.push_back(
  452. std::make_unique<TypeNode>(canonical_id, type_id));
  453. canonical_struct_types_.InsertNode(canonical_types_nodes_.back().get(),
  454. insert_pos);
  455. return type_id;
  456. }
  457. auto SemanticsContext::CanonicalizeTupleType(
  458. ParseTree::Node parse_node, llvm::SmallVector<SemanticsTypeId>&& type_ids)
  459. -> SemanticsTypeId {
  460. llvm::FoldingSetNodeID canonical_id;
  461. for (const auto& type_id : type_ids) {
  462. canonical_id.AddInteger(type_id.index);
  463. }
  464. // If a tuple with matching fields was already created, reuse it.
  465. void* insert_pos;
  466. auto* node =
  467. canonical_tuple_types_.FindNodeOrInsertPos(canonical_id, insert_pos);
  468. if (node != nullptr) {
  469. return node->type_id();
  470. }
  471. // The tuple type doesn't already exist, so create and store it as canonical.
  472. auto type_block_id = semantics_ir_->AddTypeBlock();
  473. auto& type_block = semantics_ir_->GetTypeBlock(type_block_id);
  474. type_block = std::move(type_ids);
  475. auto node_id = AddNode(SemanticsNode::TupleType::Make(
  476. parse_node, SemanticsTypeId::TypeType, type_block_id));
  477. auto type_id = semantics_ir_->AddType(node_id);
  478. CARBON_CHECK(canonical_types_.insert({node_id, type_id}).second);
  479. canonical_types_nodes_.push_back(
  480. std::make_unique<TypeNode>(canonical_id, type_id));
  481. canonical_tuple_types_.InsertNode(canonical_types_nodes_.back().get(),
  482. insert_pos);
  483. return type_id;
  484. }
  485. auto SemanticsContext::PrintForStackDump(llvm::raw_ostream& output) const
  486. -> void {
  487. node_stack_.PrintForStackDump(output);
  488. node_block_stack_.PrintForStackDump(output);
  489. params_or_args_stack_.PrintForStackDump(output);
  490. args_type_info_stack_.PrintForStackDump(output);
  491. }
  492. } // namespace Carbon