semantics_context.cpp 32 KB

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