semantics_context.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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/vlog.h"
  7. #include "toolchain/diagnostics/diagnostic_kind.h"
  8. #include "toolchain/lexer/token_kind.h"
  9. #include "toolchain/lexer/tokenized_buffer.h"
  10. #include "toolchain/parser/parse_node_kind.h"
  11. #include "toolchain/semantics/semantics_ir.h"
  12. #include "toolchain/semantics/semantics_node.h"
  13. #include "toolchain/semantics/semantics_node_block_stack.h"
  14. namespace Carbon {
  15. SemanticsContext::SemanticsContext(const TokenizedBuffer& tokens,
  16. DiagnosticEmitter<ParseTree::Node>& emitter,
  17. const ParseTree& parse_tree,
  18. SemanticsIR& semantics,
  19. llvm::raw_ostream* vlog_stream)
  20. : tokens_(&tokens),
  21. emitter_(&emitter),
  22. parse_tree_(&parse_tree),
  23. semantics_(&semantics),
  24. vlog_stream_(vlog_stream),
  25. node_stack_(parse_tree, vlog_stream),
  26. node_block_stack_("node_block_stack_", semantics.node_blocks(),
  27. vlog_stream),
  28. params_or_args_stack_("params_or_args_stack_", semantics.node_blocks(),
  29. vlog_stream),
  30. args_type_info_stack_("args_type_info_stack_", semantics.node_blocks(),
  31. vlog_stream) {}
  32. auto SemanticsContext::TODO(ParseTree::Node parse_node, std::string label)
  33. -> bool {
  34. CARBON_DIAGNOSTIC(SemanticsTodo, Error, "Semantics TODO: {0}", std::string);
  35. emitter_->Emit(parse_node, SemanticsTodo, std::move(label));
  36. return false;
  37. }
  38. auto SemanticsContext::VerifyOnFinish() -> void {
  39. // Information in all the various context objects should be cleaned up as
  40. // various pieces of context go out of scope. At this point, nothing should
  41. // remain.
  42. // node_stack_ will still contain top-level entities.
  43. CARBON_CHECK(name_lookup_.empty()) << name_lookup_.size();
  44. CARBON_CHECK(scope_stack_.empty()) << scope_stack_.size();
  45. CARBON_CHECK(node_block_stack_.empty()) << node_block_stack_.size();
  46. CARBON_CHECK(params_or_args_stack_.empty()) << params_or_args_stack_.size();
  47. }
  48. auto SemanticsContext::AddNode(SemanticsNode node) -> SemanticsNodeId {
  49. auto block = node_block_stack_.PeekForAdd();
  50. CARBON_VLOG() << "AddNode " << block << ": " << node << "\n";
  51. return semantics_->AddNode(block, node);
  52. }
  53. auto SemanticsContext::AddNodeAndPush(ParseTree::Node parse_node,
  54. SemanticsNode node) -> void {
  55. auto node_id = AddNode(node);
  56. node_stack_.Push(parse_node, node_id);
  57. }
  58. auto SemanticsContext::AddNameToLookup(ParseTree::Node name_node,
  59. SemanticsStringId name_id,
  60. SemanticsNodeId target_id) -> void {
  61. auto [it, inserted] = current_scope().names.insert(name_id);
  62. if (inserted) {
  63. name_lookup_[name_id].push_back(target_id);
  64. } else {
  65. CARBON_DIAGNOSTIC(NameRedefined, Error, "Redefining {0} in the same scope.",
  66. llvm::StringRef);
  67. CARBON_DIAGNOSTIC(PreviousDefinition, Note, "Previous definition is here.");
  68. auto prev_def_id = name_lookup_[name_id].back();
  69. auto prev_def = semantics_->GetNode(prev_def_id);
  70. emitter_->Build(name_node, NameRedefined, semantics_->GetString(name_id))
  71. .Note(prev_def.parse_node(), PreviousDefinition)
  72. .Emit();
  73. }
  74. }
  75. auto SemanticsContext::BindName(ParseTree::Node name_node,
  76. SemanticsNodeId type_id,
  77. SemanticsNodeId target_id)
  78. -> SemanticsStringId {
  79. CARBON_CHECK(parse_tree_->node_kind(name_node) == ParseNodeKind::DeclaredName)
  80. << parse_tree_->node_kind(name_node);
  81. auto name_str = parse_tree_->GetNodeText(name_node);
  82. auto name_id = semantics_->AddString(name_str);
  83. AddNode(
  84. SemanticsNode::BindName::Make(name_node, type_id, name_id, target_id));
  85. AddNameToLookup(name_node, name_id, target_id);
  86. return name_id;
  87. }
  88. auto SemanticsContext::TempRemoveLatestNameFromLookup() -> SemanticsNodeId {
  89. // Save the storage ID.
  90. auto it = name_lookup_.find(
  91. node_stack_.PeekForNameId(ParseNodeKind::PatternBinding));
  92. CARBON_CHECK(it != name_lookup_.end());
  93. CARBON_CHECK(!it->second.empty());
  94. auto storage_id = it->second.back();
  95. // Pop the name from lookup.
  96. if (it->second.size() == 1) {
  97. // Erase names that no longer resolve.
  98. name_lookup_.erase(it);
  99. } else {
  100. it->second.pop_back();
  101. }
  102. return storage_id;
  103. }
  104. auto SemanticsContext::LookupName(ParseTree::Node parse_node,
  105. llvm::StringRef name) -> SemanticsNodeId {
  106. CARBON_DIAGNOSTIC(NameNotFound, Error, "Name {0} not found", llvm::StringRef);
  107. auto name_id = semantics_->GetStringID(name);
  108. if (!name_id) {
  109. emitter_->Emit(parse_node, NameNotFound, name);
  110. return SemanticsNodeId::BuiltinInvalidType;
  111. }
  112. auto it = name_lookup_.find(*name_id);
  113. if (it == name_lookup_.end()) {
  114. emitter_->Emit(parse_node, NameNotFound, name);
  115. return SemanticsNodeId::BuiltinInvalidType;
  116. }
  117. CARBON_CHECK(!it->second.empty()) << "Should have been erased: " << name;
  118. // TODO: Check for ambiguous lookups.
  119. return it->second.back();
  120. }
  121. auto SemanticsContext::PushScope() -> void { scope_stack_.push_back({}); }
  122. auto SemanticsContext::PopScope() -> void {
  123. auto scope = scope_stack_.pop_back_val();
  124. for (const auto& str_id : scope.names) {
  125. auto it = name_lookup_.find(str_id);
  126. if (it->second.size() == 1) {
  127. // Erase names that no longer resolve.
  128. name_lookup_.erase(it);
  129. } else {
  130. it->second.pop_back();
  131. }
  132. }
  133. }
  134. auto SemanticsContext::ImplicitAsForArgs(
  135. SemanticsNodeBlockId /*arg_ir_id*/, SemanticsNodeBlockId arg_refs_id,
  136. ParseTree::Node param_parse_node, SemanticsNodeBlockId param_refs_id,
  137. DiagnosticEmitter<ParseTree::Node>::DiagnosticBuilder* diagnostic) -> bool {
  138. // If both arguments and parameters are empty, return quickly. Otherwise,
  139. // we'll fetch both so that errors are consistent.
  140. if (arg_refs_id == SemanticsNodeBlockId::Empty &&
  141. param_refs_id == SemanticsNodeBlockId::Empty) {
  142. return true;
  143. }
  144. auto arg_refs = semantics_->GetNodeBlock(arg_refs_id);
  145. auto param_refs = semantics_->GetNodeBlock(param_refs_id);
  146. // If sizes mismatch, fail early.
  147. if (arg_refs.size() != param_refs.size()) {
  148. CARBON_CHECK(diagnostic != nullptr) << "Should have validated first";
  149. CARBON_DIAGNOSTIC(CallArgCountMismatch, Note,
  150. "Callable cannot be used: Received {0} argument(s), but "
  151. "require {1} argument(s).",
  152. int, int);
  153. diagnostic->Note(param_parse_node, CallArgCountMismatch, arg_refs.size(),
  154. param_refs.size());
  155. return false;
  156. }
  157. // Check type conversions per-element.
  158. // TODO: arg_ir_id is passed so that implicit conversions can be inserted.
  159. // It's currently not supported, but will be needed.
  160. for (size_t i = 0; i < arg_refs.size(); ++i) {
  161. auto value_id = arg_refs[i];
  162. auto as_type_id = semantics_->GetNode(param_refs[i]).type_id();
  163. if (ImplicitAsImpl(value_id, as_type_id,
  164. diagnostic == nullptr ? &value_id : nullptr) ==
  165. ImplicitAsKind::Incompatible) {
  166. CARBON_CHECK(diagnostic != nullptr) << "Should have validated first";
  167. CARBON_DIAGNOSTIC(CallArgTypeMismatch, Note,
  168. "Callable cannot be used: Cannot implicityly convert "
  169. "argument {0} from `{1}` to `{2}`.",
  170. size_t, std::string, std::string);
  171. diagnostic->Note(
  172. param_parse_node, CallArgTypeMismatch, i,
  173. semantics_->StringifyNode(semantics_->GetNode(value_id).type_id()),
  174. semantics_->StringifyNode(as_type_id));
  175. return false;
  176. }
  177. }
  178. return true;
  179. }
  180. auto SemanticsContext::ImplicitAsRequired(ParseTree::Node parse_node,
  181. SemanticsNodeId value_id,
  182. SemanticsNodeId as_type_id)
  183. -> SemanticsNodeId {
  184. SemanticsNodeId output_value_id = value_id;
  185. if (ImplicitAsImpl(value_id, as_type_id, &output_value_id) ==
  186. ImplicitAsKind::Incompatible) {
  187. // Only error when the system is trying to use the result.
  188. CARBON_DIAGNOSTIC(ImplicitAsConversionFailure, Error,
  189. "Cannot implicitly convert from `{0}` to `{1}`.",
  190. std::string, std::string);
  191. emitter_
  192. ->Build(
  193. parse_node, ImplicitAsConversionFailure,
  194. semantics_->StringifyNode(semantics_->GetNode(value_id).type_id()),
  195. semantics_->StringifyNode(as_type_id))
  196. .Emit();
  197. }
  198. return output_value_id;
  199. }
  200. auto SemanticsContext::ImplicitAsImpl(SemanticsNodeId value_id,
  201. SemanticsNodeId as_type_id,
  202. SemanticsNodeId* output_value_id)
  203. -> ImplicitAsKind {
  204. // Start by making sure both sides are valid. If any part is invalid, the
  205. // result is invalid and we shouldn't error.
  206. if (value_id == SemanticsNodeId::BuiltinInvalidType) {
  207. // If the value is invalid, we can't do much, but do "succeed".
  208. return ImplicitAsKind::Identical;
  209. }
  210. auto value_type_id = semantics_->GetNode(value_id).type_id();
  211. if (value_type_id == SemanticsNodeId::BuiltinInvalidType) {
  212. return ImplicitAsKind::Identical;
  213. }
  214. if (as_type_id == SemanticsNodeId::BuiltinInvalidType) {
  215. // Although the target type is invalid, this still changes the value.
  216. if (output_value_id != nullptr) {
  217. *output_value_id = SemanticsNodeId::BuiltinInvalidType;
  218. }
  219. return ImplicitAsKind::Compatible;
  220. }
  221. if (value_type_id == as_type_id) {
  222. // Type doesn't need to change.
  223. return ImplicitAsKind::Identical;
  224. }
  225. // When converting to a Type, there are some automatic conversions that can be
  226. // done.
  227. if (as_type_id == SemanticsNodeId::BuiltinTypeType) {
  228. if (value_id == SemanticsNodeId::BuiltinEmptyTuple) {
  229. if (output_value_id != nullptr) {
  230. *output_value_id = SemanticsNodeId::BuiltinEmptyTupleType;
  231. }
  232. return ImplicitAsKind::Compatible;
  233. }
  234. if (value_id == SemanticsNodeId::BuiltinEmptyStruct) {
  235. if (output_value_id != nullptr) {
  236. *output_value_id = SemanticsNodeId::BuiltinEmptyStructType;
  237. }
  238. return ImplicitAsKind::Compatible;
  239. }
  240. }
  241. auto value_type = semantics_->GetNode(value_type_id);
  242. auto as_type = semantics_->GetNode(as_type_id);
  243. if (CanImplicitAsStruct(value_type, as_type)) {
  244. // Under the current implementation, struct types are only allowed to
  245. // ImplicitAs when they're equivalent. What's really missing is type
  246. // consolidation such that this would fall under the above `value_type_id ==
  247. // as_type_id` case. In the future, this will need to handle actual
  248. // conversions.
  249. return ImplicitAsKind::Identical;
  250. }
  251. if (output_value_id != nullptr) {
  252. *output_value_id = SemanticsNodeId::BuiltinInvalidType;
  253. }
  254. return ImplicitAsKind::Incompatible;
  255. }
  256. auto SemanticsContext::CanImplicitAsStruct(SemanticsNode value_type,
  257. SemanticsNode as_type) -> bool {
  258. if (value_type.kind() != SemanticsNodeKind::StructType ||
  259. as_type.kind() != SemanticsNodeKind::StructType) {
  260. return false;
  261. }
  262. auto value_type_refs =
  263. semantics_->GetNodeBlock(value_type.GetAsStructType().second);
  264. auto as_type_refs =
  265. semantics_->GetNodeBlock(as_type.GetAsStructType().second);
  266. if (value_type_refs.size() != as_type_refs.size()) {
  267. return false;
  268. }
  269. for (int i = 0; i < static_cast<int>(value_type_refs.size()); ++i) {
  270. auto value_type_field = semantics_->GetNode(value_type_refs[i]);
  271. auto as_type_field = semantics_->GetNode(as_type_refs[i]);
  272. if (value_type_field.type_id() != as_type_field.type_id() ||
  273. value_type_field.GetAsStructTypeField() !=
  274. as_type_field.GetAsStructTypeField()) {
  275. return false;
  276. }
  277. }
  278. return true;
  279. }
  280. auto SemanticsContext::ParamOrArgStart() -> void {
  281. params_or_args_stack_.Push();
  282. node_block_stack_.Push();
  283. }
  284. auto SemanticsContext::ParamOrArgComma(bool for_args) -> void {
  285. ParamOrArgSave(for_args);
  286. }
  287. auto SemanticsContext::ParamOrArgEnd(bool for_args, ParseNodeKind start_kind)
  288. -> std::pair<SemanticsNodeBlockId, SemanticsNodeBlockId> {
  289. if (parse_tree_->node_kind(node_stack_.PeekParseNode()) != start_kind) {
  290. ParamOrArgSave(for_args);
  291. }
  292. return {node_block_stack_.Pop(), params_or_args_stack_.Pop()};
  293. }
  294. auto SemanticsContext::ParamOrArgSave(bool for_args) -> void {
  295. SemanticsNodeId param_or_arg_id = SemanticsNodeId::Invalid;
  296. if (for_args) {
  297. // For an argument, we add a stub reference to the expression on the top of
  298. // the stack. There may not be anything on the IR prior to this.
  299. auto [entry_parse_node, entry_node_id] =
  300. node_stack_.PopForParseNodeAndNodeId();
  301. param_or_arg_id = AddNode(SemanticsNode::StubReference::Make(
  302. entry_parse_node, semantics_->GetNode(entry_node_id).type_id(),
  303. entry_node_id));
  304. } else {
  305. // For a parameter, there should always be something in the IR.
  306. node_stack_.PopAndIgnore();
  307. auto ir_id = node_block_stack_.Peek();
  308. CARBON_CHECK(ir_id.is_valid());
  309. auto& ir = semantics_->GetNodeBlock(ir_id);
  310. CARBON_CHECK(!ir.empty()) << "Should have had a param";
  311. param_or_arg_id = ir.back();
  312. }
  313. // Save the param or arg ID.
  314. auto& params_or_args =
  315. semantics_->GetNodeBlock(params_or_args_stack_.PeekForAdd());
  316. params_or_args.push_back(param_or_arg_id);
  317. }
  318. auto SemanticsContext::PrintForStackDump(llvm::raw_ostream& output) const
  319. -> void {
  320. node_stack_.PrintForStackDump(output);
  321. node_block_stack_.PrintForStackDump(output);
  322. params_or_args_stack_.PrintForStackDump(output);
  323. args_type_info_stack_.PrintForStackDump(output);
  324. }
  325. } // namespace Carbon