semantics_context.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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",
  83. llvm::StringRef);
  84. emitter_->Emit(parse_node, NameNotFound, semantics_ir_->GetString(name_id));
  85. }
  86. auto SemanticsContext::AddNameToLookup(ParseTree::Node name_node,
  87. SemanticsStringId name_id,
  88. SemanticsNodeId target_id) -> void {
  89. if (current_scope().names.insert(name_id).second) {
  90. name_lookup_[name_id].push_back(target_id);
  91. } else {
  92. DiagnoseDuplicateName(name_node, name_lookup_[name_id].back());
  93. }
  94. }
  95. auto SemanticsContext::LookupName(ParseTree::Node parse_node,
  96. SemanticsStringId name_id,
  97. SemanticsNameScopeId scope_id,
  98. bool print_diagnostics) -> SemanticsNodeId {
  99. if (scope_id == SemanticsNameScopeId::Invalid) {
  100. auto it = name_lookup_.find(name_id);
  101. if (it == name_lookup_.end()) {
  102. if (print_diagnostics) {
  103. DiagnoseNameNotFound(parse_node, name_id);
  104. }
  105. return SemanticsNodeId::BuiltinError;
  106. }
  107. CARBON_CHECK(!it->second.empty())
  108. << "Should have been erased: " << semantics_ir_->GetString(name_id);
  109. // TODO: Check for ambiguous lookups.
  110. return it->second.back();
  111. } else {
  112. const auto& scope = semantics_ir_->GetNameScope(scope_id);
  113. auto it = scope.find(name_id);
  114. if (it == scope.end()) {
  115. if (print_diagnostics) {
  116. DiagnoseNameNotFound(parse_node, name_id);
  117. }
  118. return SemanticsNodeId::BuiltinError;
  119. }
  120. return it->second;
  121. }
  122. }
  123. auto SemanticsContext::PushScope() -> void { scope_stack_.push_back({}); }
  124. auto SemanticsContext::PopScope() -> void {
  125. auto scope = scope_stack_.pop_back_val();
  126. for (const auto& str_id : scope.names) {
  127. auto it = name_lookup_.find(str_id);
  128. if (it->second.size() == 1) {
  129. // Erase names that no longer resolve.
  130. name_lookup_.erase(it);
  131. } else {
  132. it->second.pop_back();
  133. }
  134. }
  135. }
  136. template <typename BranchNode, typename... Args>
  137. static auto AddDominatedBlockAndBranchImpl(SemanticsContext& context,
  138. ParseTree::Node parse_node,
  139. Args... args)
  140. -> SemanticsNodeBlockId {
  141. if (!context.node_block_stack().is_current_block_reachable()) {
  142. return SemanticsNodeBlockId::Unreachable;
  143. }
  144. auto block_id = context.semantics_ir().AddNodeBlock();
  145. context.AddNode(BranchNode::Make(parse_node, block_id, args...));
  146. return block_id;
  147. }
  148. auto SemanticsContext::AddDominatedBlockAndBranch(ParseTree::Node parse_node)
  149. -> SemanticsNodeBlockId {
  150. return AddDominatedBlockAndBranchImpl<SemanticsNode::Branch>(*this,
  151. parse_node);
  152. }
  153. auto SemanticsContext::AddDominatedBlockAndBranchWithArg(
  154. ParseTree::Node parse_node, SemanticsNodeId arg_id)
  155. -> SemanticsNodeBlockId {
  156. return AddDominatedBlockAndBranchImpl<SemanticsNode::BranchWithArg>(
  157. *this, parse_node, arg_id);
  158. }
  159. auto SemanticsContext::AddDominatedBlockAndBranchIf(ParseTree::Node parse_node,
  160. SemanticsNodeId cond_id)
  161. -> SemanticsNodeBlockId {
  162. return AddDominatedBlockAndBranchImpl<SemanticsNode::BranchIf>(
  163. *this, parse_node, cond_id);
  164. }
  165. auto SemanticsContext::AddConvergenceBlockAndPush(
  166. ParseTree::Node parse_node,
  167. std::initializer_list<SemanticsNodeBlockId> blocks) -> void {
  168. CARBON_CHECK(blocks.size() >= 2) << "no convergence";
  169. SemanticsNodeBlockId new_block_id = SemanticsNodeBlockId::Unreachable;
  170. for (SemanticsNodeBlockId block_id : blocks) {
  171. if (block_id != SemanticsNodeBlockId::Unreachable) {
  172. if (new_block_id == SemanticsNodeBlockId::Unreachable) {
  173. new_block_id = semantics_ir().AddNodeBlock();
  174. }
  175. AddNodeToBlock(block_id,
  176. SemanticsNode::Branch::Make(parse_node, new_block_id));
  177. }
  178. }
  179. node_block_stack().Push(new_block_id);
  180. }
  181. auto SemanticsContext::AddConvergenceBlockWithArgAndPush(
  182. ParseTree::Node parse_node,
  183. std::initializer_list<std::pair<SemanticsNodeBlockId, SemanticsNodeId>>
  184. blocks_and_args) -> SemanticsNodeId {
  185. CARBON_CHECK(blocks_and_args.size() >= 2) << "no convergence";
  186. SemanticsNodeBlockId new_block_id = SemanticsNodeBlockId::Unreachable;
  187. for (auto [block_id, arg_id] : blocks_and_args) {
  188. if (block_id != SemanticsNodeBlockId::Unreachable) {
  189. if (new_block_id == SemanticsNodeBlockId::Unreachable) {
  190. new_block_id = semantics_ir().AddNodeBlock();
  191. }
  192. AddNodeToBlock(block_id, SemanticsNode::BranchWithArg::Make(
  193. parse_node, new_block_id, arg_id));
  194. }
  195. }
  196. node_block_stack().Push(new_block_id);
  197. // Acquire the result value.
  198. SemanticsTypeId result_type_id =
  199. semantics_ir().GetNode(blocks_and_args.begin()->second).type_id();
  200. return AddNode(
  201. SemanticsNode::BlockArg::Make(parse_node, result_type_id, new_block_id));
  202. }
  203. // Add the current code block to the enclosing function.
  204. auto SemanticsContext::AddCurrentCodeBlockToFunction() -> void {
  205. CARBON_CHECK(!node_block_stack().empty()) << "no current code block";
  206. CARBON_CHECK(!return_scope_stack().empty()) << "no current function";
  207. if (!node_block_stack().is_current_block_reachable()) {
  208. // Don't include unreachable blocks in the function.
  209. return;
  210. }
  211. auto function_id = semantics_ir()
  212. .GetNode(return_scope_stack().back())
  213. .GetAsFunctionDeclaration();
  214. semantics_ir()
  215. .GetFunction(function_id)
  216. .body_block_ids.push_back(node_block_stack().PeekForAdd());
  217. }
  218. auto SemanticsContext::is_current_position_reachable() -> bool {
  219. switch (auto block_id = node_block_stack().Peek(); block_id.index) {
  220. case SemanticsNodeBlockId::Unreachable.index: {
  221. return false;
  222. }
  223. case SemanticsNodeBlockId::Invalid.index: {
  224. return true;
  225. }
  226. default: {
  227. // Our current position is at the end of a real block. That position is
  228. // reachable unless the previous instruction is a terminator instruction.
  229. const auto& block_contents = semantics_ir().GetNodeBlock(block_id);
  230. if (block_contents.empty()) {
  231. return true;
  232. }
  233. const auto& last_node = semantics_ir().GetNode(block_contents.back());
  234. return last_node.kind().terminator_kind() !=
  235. SemanticsTerminatorKind::Terminator;
  236. }
  237. }
  238. }
  239. auto SemanticsContext::ImplicitAsForArgs(
  240. SemanticsNodeBlockId arg_refs_id, ParseTree::Node param_parse_node,
  241. SemanticsNodeBlockId param_refs_id,
  242. DiagnosticEmitter<ParseTree::Node>::DiagnosticBuilder* diagnostic) -> bool {
  243. // If both arguments and parameters are empty, return quickly. Otherwise,
  244. // we'll fetch both so that errors are consistent.
  245. if (arg_refs_id == SemanticsNodeBlockId::Empty &&
  246. param_refs_id == SemanticsNodeBlockId::Empty) {
  247. return true;
  248. }
  249. auto arg_refs = semantics_ir_->GetNodeBlock(arg_refs_id);
  250. auto param_refs = semantics_ir_->GetNodeBlock(param_refs_id);
  251. // If sizes mismatch, fail early.
  252. if (arg_refs.size() != param_refs.size()) {
  253. CARBON_CHECK(diagnostic != nullptr) << "Should have validated first";
  254. CARBON_DIAGNOSTIC(CallArgCountMismatch, Note,
  255. "Function cannot be used: Received {0} argument(s), but "
  256. "require {1} argument(s).",
  257. int, int);
  258. diagnostic->Note(param_parse_node, CallArgCountMismatch, arg_refs.size(),
  259. param_refs.size());
  260. return false;
  261. }
  262. // Check type conversions per-element.
  263. // TODO: arg_ir_id is passed so that implicit conversions can be inserted.
  264. // It's currently not supported, but will be needed.
  265. for (size_t i = 0; i < arg_refs.size(); ++i) {
  266. auto value_id = arg_refs[i];
  267. auto as_type_id = semantics_ir_->GetNode(param_refs[i]).type_id();
  268. if (ImplicitAsImpl(value_id, as_type_id,
  269. diagnostic == nullptr ? &value_id : nullptr) ==
  270. ImplicitAsKind::Incompatible) {
  271. CARBON_CHECK(diagnostic != nullptr) << "Should have validated first";
  272. CARBON_DIAGNOSTIC(CallArgTypeMismatch, Note,
  273. "Function cannot be used: Cannot implicitly convert "
  274. "argument {0} from `{1}` to `{2}`.",
  275. size_t, std::string, std::string);
  276. diagnostic->Note(param_parse_node, CallArgTypeMismatch, i,
  277. semantics_ir_->StringifyType(
  278. semantics_ir_->GetNode(value_id).type_id()),
  279. semantics_ir_->StringifyType(as_type_id));
  280. return false;
  281. }
  282. }
  283. return true;
  284. }
  285. auto SemanticsContext::ImplicitAsRequired(ParseTree::Node parse_node,
  286. SemanticsNodeId value_id,
  287. SemanticsTypeId as_type_id)
  288. -> SemanticsNodeId {
  289. SemanticsNodeId output_value_id = value_id;
  290. if (ImplicitAsImpl(value_id, as_type_id, &output_value_id) ==
  291. ImplicitAsKind::Incompatible) {
  292. // Only error when the system is trying to use the result.
  293. CARBON_DIAGNOSTIC(ImplicitAsConversionFailure, Error,
  294. "Cannot implicitly convert from `{0}` to `{1}`.",
  295. std::string, std::string);
  296. emitter_
  297. ->Build(parse_node, ImplicitAsConversionFailure,
  298. semantics_ir_->StringifyType(
  299. semantics_ir_->GetNode(value_id).type_id()),
  300. semantics_ir_->StringifyType(as_type_id))
  301. .Emit();
  302. }
  303. return output_value_id;
  304. }
  305. auto SemanticsContext::ImplicitAsBool(ParseTree::Node parse_node,
  306. SemanticsNodeId value_id)
  307. -> SemanticsNodeId {
  308. return ImplicitAsRequired(parse_node, value_id,
  309. CanonicalizeType(SemanticsNodeId::BuiltinBoolType));
  310. }
  311. auto SemanticsContext::ImplicitAsImpl(SemanticsNodeId value_id,
  312. SemanticsTypeId as_type_id,
  313. SemanticsNodeId* output_value_id)
  314. -> ImplicitAsKind {
  315. // Start by making sure both sides are valid. If any part is invalid, the
  316. // result is invalid and we shouldn't error.
  317. if (value_id == SemanticsNodeId::BuiltinError) {
  318. // If the value is invalid, we can't do much, but do "succeed".
  319. return ImplicitAsKind::Identical;
  320. }
  321. auto value = semantics_ir_->GetNode(value_id);
  322. auto value_type_id = value.type_id();
  323. if (value_type_id == SemanticsTypeId::Error) {
  324. return ImplicitAsKind::Identical;
  325. }
  326. if (as_type_id == SemanticsTypeId::Error) {
  327. // Although the target type is invalid, this still changes the value.
  328. if (output_value_id != nullptr) {
  329. *output_value_id = SemanticsNodeId::BuiltinError;
  330. }
  331. return ImplicitAsKind::Compatible;
  332. }
  333. if (value_type_id == as_type_id) {
  334. // Type doesn't need to change.
  335. return ImplicitAsKind::Identical;
  336. }
  337. if (as_type_id == SemanticsTypeId::TypeType) {
  338. if (value.kind() == SemanticsNodeKind::TupleValue) {
  339. auto tuple_block_id = value.GetAsTupleValue();
  340. llvm::SmallVector<SemanticsTypeId> type_ids;
  341. // If it is empty tuple type, we don't fetch anything.
  342. if (tuple_block_id != SemanticsNodeBlockId::Empty) {
  343. const auto& tuple_block = semantics_ir_->GetNodeBlock(tuple_block_id);
  344. for (auto tuple_node_id : tuple_block) {
  345. // TODO: Eventually ExpressionAsType will insert implicit cast
  346. // instructions. When that happens, this will need to verify the full
  347. // tuple conversion will work before calling it.
  348. type_ids.push_back(
  349. ExpressionAsType(value.parse_node(), tuple_node_id));
  350. }
  351. }
  352. auto tuple_type_id =
  353. CanonicalizeTupleType(value.parse_node(), std::move(type_ids));
  354. if (output_value_id != nullptr) {
  355. *output_value_id =
  356. semantics_ir_->GetTypeAllowBuiltinTypes(tuple_type_id);
  357. }
  358. return ImplicitAsKind::Compatible;
  359. }
  360. // When converting `{}` to a type, the result is `{} as Type`.
  361. if (value.kind() == SemanticsNodeKind::StructValue &&
  362. value.GetAsStructValue() == SemanticsNodeBlockId::Empty) {
  363. if (output_value_id != nullptr) {
  364. *output_value_id = semantics_ir_->GetType(value_type_id);
  365. }
  366. return ImplicitAsKind::Compatible;
  367. }
  368. }
  369. // TODO: Handle ImplicitAs for compatible structs and tuples.
  370. if (output_value_id != nullptr) {
  371. *output_value_id = SemanticsNodeId::BuiltinError;
  372. }
  373. return ImplicitAsKind::Incompatible;
  374. }
  375. auto SemanticsContext::ParamOrArgStart() -> void {
  376. params_or_args_stack_.Push();
  377. }
  378. auto SemanticsContext::ParamOrArgComma(bool for_args) -> void {
  379. ParamOrArgSave(for_args);
  380. }
  381. auto SemanticsContext::ParamOrArgEnd(bool for_args, ParseNodeKind start_kind)
  382. -> SemanticsNodeBlockId {
  383. if (parse_tree_->node_kind(node_stack_.PeekParseNode()) != start_kind) {
  384. ParamOrArgSave(for_args);
  385. }
  386. return params_or_args_stack_.Pop();
  387. }
  388. auto SemanticsContext::ParamOrArgSave(bool for_args) -> void {
  389. auto [entry_parse_node, entry_node_id] =
  390. node_stack_.PopExpressionWithParseNode();
  391. if (for_args) {
  392. // For an argument, we add a stub reference to the expression on the top of
  393. // the stack. There may not be anything on the IR prior to this.
  394. entry_node_id = AddNode(SemanticsNode::StubReference::Make(
  395. entry_parse_node, semantics_ir_->GetNode(entry_node_id).type_id(),
  396. entry_node_id));
  397. }
  398. // Save the param or arg ID.
  399. auto& params_or_args =
  400. semantics_ir_->GetNodeBlock(params_or_args_stack_.PeekForAdd());
  401. params_or_args.push_back(entry_node_id);
  402. }
  403. auto SemanticsContext::CanonicalizeTypeImpl(
  404. SemanticsNodeKind kind,
  405. llvm::function_ref<void(llvm::FoldingSetNodeID& canonical_id)> profile_type,
  406. llvm::function_ref<SemanticsNodeId()> make_node) -> SemanticsTypeId {
  407. llvm::FoldingSetNodeID canonical_id;
  408. kind.Profile(canonical_id);
  409. profile_type(canonical_id);
  410. void* insert_pos;
  411. auto* node =
  412. canonical_type_nodes_.FindNodeOrInsertPos(canonical_id, insert_pos);
  413. if (node != nullptr) {
  414. return node->type_id();
  415. }
  416. auto node_id = make_node();
  417. auto type_id = semantics_ir_->AddType(node_id);
  418. CARBON_CHECK(canonical_types_.insert({node_id, type_id}).second);
  419. type_node_storage_.push_back(
  420. std::make_unique<TypeNode>(canonical_id, type_id));
  421. // In a debug build, check that our insertion position is still valid. It
  422. // could have been invalidated by a misbehaving `make_node`.
  423. CARBON_DCHECK([&] {
  424. void* check_insert_pos;
  425. auto* check_node = canonical_type_nodes_.FindNodeOrInsertPos(
  426. canonical_id, check_insert_pos);
  427. return !check_node && insert_pos == check_insert_pos;
  428. }()) << "Type was created recursively during canonicalization";
  429. canonical_type_nodes_.InsertNode(type_node_storage_.back().get(), insert_pos);
  430. return type_id;
  431. }
  432. auto SemanticsContext::CanonicalizeType(SemanticsNodeId node_id)
  433. -> SemanticsTypeId {
  434. auto node = semantics_ir_->GetNode(node_id);
  435. if (node.kind() == SemanticsNodeKind::StubReference) {
  436. node_id = node.GetAsStubReference();
  437. CARBON_CHECK(semantics_ir_->GetNode(node_id).kind() !=
  438. SemanticsNodeKind::StubReference)
  439. << "Stub reference should not point to another stub reference";
  440. }
  441. auto it = canonical_types_.find(node_id);
  442. if (it != canonical_types_.end()) {
  443. return it->second;
  444. }
  445. switch (node.kind()) {
  446. case SemanticsNodeKind::Builtin:
  447. case SemanticsNodeKind::CrossReference: {
  448. // TODO: Cross-references should be canonicalized by looking at their
  449. // target rather than treating them as new unique types.
  450. auto type_id = semantics_ir_->AddType(node_id);
  451. CARBON_CHECK(canonical_types_.insert({node_id, type_id}).second);
  452. return type_id;
  453. }
  454. case SemanticsNodeKind::ConstType: {
  455. return CanonicalizeTypeImpl(
  456. node.kind(), node_id, [&](llvm::FoldingSetNodeID& canonical_id) {
  457. canonical_id.AddInteger(
  458. GetUnqualifiedType(node.GetAsConstType()).index);
  459. });
  460. }
  461. case SemanticsNodeKind::PointerType: {
  462. return CanonicalizeTypeImpl(
  463. node.kind(), node_id, [&](llvm::FoldingSetNodeID& canonical_id) {
  464. canonical_id.AddInteger(node.GetAsPointerType().index);
  465. });
  466. }
  467. case SemanticsNodeKind::StructType:
  468. case SemanticsNodeKind::TupleType: {
  469. CARBON_FATAL() << "Type should have been canonizalized when created: "
  470. << node;
  471. }
  472. default: {
  473. CARBON_FATAL() << "Unexpected non-canonical type node " << node;
  474. }
  475. }
  476. }
  477. auto SemanticsContext::CanonicalizeStructType(ParseTree::Node parse_node,
  478. SemanticsNodeBlockId refs_id)
  479. -> SemanticsTypeId {
  480. auto profile_struct = [&](llvm::FoldingSetNodeID& canonical_id) {
  481. auto refs = semantics_ir_->GetNodeBlock(refs_id);
  482. for (const auto& ref_id : refs) {
  483. auto ref = semantics_ir_->GetNode(ref_id);
  484. auto [name_id, type_id] = ref.GetAsStructTypeField();
  485. canonical_id.AddInteger(name_id.index);
  486. canonical_id.AddInteger(type_id.index);
  487. }
  488. };
  489. auto make_struct_node = [&] {
  490. return AddNode(SemanticsNode::StructType::Make(
  491. parse_node, SemanticsTypeId::TypeType, refs_id));
  492. };
  493. return CanonicalizeTypeImpl(SemanticsNodeKind::StructType, profile_struct,
  494. make_struct_node);
  495. }
  496. auto SemanticsContext::CanonicalizeTupleType(
  497. ParseTree::Node parse_node, llvm::SmallVector<SemanticsTypeId>&& type_ids)
  498. -> SemanticsTypeId {
  499. auto profile_tuple = [&](llvm::FoldingSetNodeID& canonical_id) {
  500. for (const auto& type_id : type_ids) {
  501. canonical_id.AddInteger(type_id.index);
  502. }
  503. };
  504. auto make_tuple_node = [&] {
  505. auto type_block_id = semantics_ir_->AddTypeBlock();
  506. auto& type_block = semantics_ir_->GetTypeBlock(type_block_id);
  507. type_block = std::move(type_ids);
  508. return AddNode(SemanticsNode::TupleType::Make(
  509. parse_node, SemanticsTypeId::TypeType, type_block_id));
  510. };
  511. return CanonicalizeTypeImpl(SemanticsNodeKind::TupleType, profile_tuple,
  512. make_tuple_node);
  513. }
  514. auto SemanticsContext::GetUnqualifiedType(SemanticsTypeId type_id)
  515. -> SemanticsTypeId {
  516. SemanticsNode type_node =
  517. semantics_ir_->GetNode(semantics_ir_->GetType(type_id));
  518. if (type_node.kind() == SemanticsNodeKind::ConstType)
  519. return type_node.GetAsConstType();
  520. return type_id;
  521. }
  522. auto SemanticsContext::PrintForStackDump(llvm::raw_ostream& output) const
  523. -> void {
  524. node_stack_.PrintForStackDump(output);
  525. node_block_stack_.PrintForStackDump(output);
  526. params_or_args_stack_.PrintForStackDump(output);
  527. args_type_info_stack_.PrintForStackDump(output);
  528. }
  529. } // namespace Carbon