semantics_context.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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_ir,
  19. llvm::raw_ostream* vlog_stream)
  20. : tokens_(&tokens),
  21. emitter_(&emitter),
  22. parse_tree_(&parse_tree),
  23. semantics_ir_(&semantics_ir),
  24. vlog_stream_(vlog_stream),
  25. node_stack_(parse_tree, vlog_stream),
  26. node_block_stack_("node_block_stack_", semantics_ir.node_blocks(),
  27. vlog_stream),
  28. params_or_args_stack_("params_or_args_stack_", semantics_ir.node_blocks(),
  29. vlog_stream),
  30. args_type_info_stack_("args_type_info_stack_", semantics_ir.node_blocks(),
  31. vlog_stream) {
  32. // Inserts the "Invalid" 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::BuiltinInvalidType, SemanticsTypeId::InvalidType});
  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::AddNameToLookup(ParseTree::Node name_node,
  69. SemanticsStringId name_id,
  70. SemanticsNodeId target_id) -> void {
  71. if (current_scope().names.insert(name_id).second) {
  72. name_lookup_[name_id].push_back(target_id);
  73. } else {
  74. CARBON_DIAGNOSTIC(NameRedefined, Error, "Redefining {0} in the same scope.",
  75. llvm::StringRef);
  76. CARBON_DIAGNOSTIC(PreviousDefinition, Note, "Previous definition is here.");
  77. auto prev_def_id = name_lookup_[name_id].back();
  78. auto prev_def = semantics_ir_->GetNode(prev_def_id);
  79. emitter_->Build(name_node, NameRedefined, semantics_ir_->GetString(name_id))
  80. .Note(prev_def.parse_node(), PreviousDefinition)
  81. .Emit();
  82. }
  83. }
  84. auto SemanticsContext::LookupName(ParseTree::Node parse_node,
  85. llvm::StringRef name) -> SemanticsNodeId {
  86. CARBON_DIAGNOSTIC(NameNotFound, Error, "Name {0} not found", llvm::StringRef);
  87. auto name_id = semantics_ir_->GetStringID(name);
  88. if (!name_id) {
  89. emitter_->Emit(parse_node, NameNotFound, name);
  90. return SemanticsNodeId::BuiltinInvalidType;
  91. }
  92. auto it = name_lookup_.find(*name_id);
  93. if (it == name_lookup_.end()) {
  94. emitter_->Emit(parse_node, NameNotFound, name);
  95. return SemanticsNodeId::BuiltinInvalidType;
  96. }
  97. CARBON_CHECK(!it->second.empty()) << "Should have been erased: " << name;
  98. // TODO: Check for ambiguous lookups.
  99. return it->second.back();
  100. }
  101. auto SemanticsContext::PushScope() -> void { scope_stack_.push_back({}); }
  102. auto SemanticsContext::PopScope() -> void {
  103. auto scope = scope_stack_.pop_back_val();
  104. for (const auto& str_id : scope.names) {
  105. auto it = name_lookup_.find(str_id);
  106. if (it->second.size() == 1) {
  107. // Erase names that no longer resolve.
  108. name_lookup_.erase(it);
  109. } else {
  110. it->second.pop_back();
  111. }
  112. }
  113. }
  114. auto SemanticsContext::ImplicitAsForArgs(
  115. SemanticsNodeBlockId arg_refs_id, ParseTree::Node param_parse_node,
  116. SemanticsNodeBlockId param_refs_id,
  117. DiagnosticEmitter<ParseTree::Node>::DiagnosticBuilder* diagnostic) -> bool {
  118. // If both arguments and parameters are empty, return quickly. Otherwise,
  119. // we'll fetch both so that errors are consistent.
  120. if (arg_refs_id == SemanticsNodeBlockId::Empty &&
  121. param_refs_id == SemanticsNodeBlockId::Empty) {
  122. return true;
  123. }
  124. auto arg_refs = semantics_ir_->GetNodeBlock(arg_refs_id);
  125. auto param_refs = semantics_ir_->GetNodeBlock(param_refs_id);
  126. // If sizes mismatch, fail early.
  127. if (arg_refs.size() != param_refs.size()) {
  128. CARBON_CHECK(diagnostic != nullptr) << "Should have validated first";
  129. CARBON_DIAGNOSTIC(CallArgCountMismatch, Note,
  130. "Function cannot be used: Received {0} argument(s), but "
  131. "require {1} argument(s).",
  132. int, int);
  133. diagnostic->Note(param_parse_node, CallArgCountMismatch, arg_refs.size(),
  134. param_refs.size());
  135. return false;
  136. }
  137. // Check type conversions per-element.
  138. // TODO: arg_ir_id is passed so that implicit conversions can be inserted.
  139. // It's currently not supported, but will be needed.
  140. for (size_t i = 0; i < arg_refs.size(); ++i) {
  141. auto value_id = arg_refs[i];
  142. auto as_type_id = semantics_ir_->GetNode(param_refs[i]).type_id();
  143. if (ImplicitAsImpl(value_id, as_type_id,
  144. diagnostic == nullptr ? &value_id : nullptr) ==
  145. ImplicitAsKind::Incompatible) {
  146. CARBON_CHECK(diagnostic != nullptr) << "Should have validated first";
  147. CARBON_DIAGNOSTIC(CallArgTypeMismatch, Note,
  148. "Function cannot be used: Cannot implicityly convert "
  149. "argument {0} from `{1}` to `{2}`.",
  150. size_t, std::string, std::string);
  151. diagnostic->Note(param_parse_node, CallArgTypeMismatch, i,
  152. semantics_ir_->StringifyType(
  153. semantics_ir_->GetNode(value_id).type_id()),
  154. semantics_ir_->StringifyType(as_type_id));
  155. return false;
  156. }
  157. }
  158. return true;
  159. }
  160. auto SemanticsContext::ImplicitAsRequired(ParseTree::Node parse_node,
  161. SemanticsNodeId value_id,
  162. SemanticsTypeId as_type_id)
  163. -> SemanticsNodeId {
  164. SemanticsNodeId output_value_id = value_id;
  165. if (ImplicitAsImpl(value_id, as_type_id, &output_value_id) ==
  166. ImplicitAsKind::Incompatible) {
  167. // Only error when the system is trying to use the result.
  168. CARBON_DIAGNOSTIC(ImplicitAsConversionFailure, Error,
  169. "Cannot implicitly convert from `{0}` to `{1}`.",
  170. std::string, std::string);
  171. emitter_
  172. ->Build(parse_node, ImplicitAsConversionFailure,
  173. semantics_ir_->StringifyType(
  174. semantics_ir_->GetNode(value_id).type_id()),
  175. semantics_ir_->StringifyType(as_type_id))
  176. .Emit();
  177. }
  178. return output_value_id;
  179. }
  180. auto SemanticsContext::ImplicitAsBool(ParseTree::Node parse_node,
  181. SemanticsNodeId value_id)
  182. -> SemanticsNodeId {
  183. return ImplicitAsRequired(parse_node, value_id,
  184. CanonicalizeType(SemanticsNodeId::BuiltinBoolType));
  185. }
  186. auto SemanticsContext::ImplicitAsImpl(SemanticsNodeId value_id,
  187. SemanticsTypeId as_type_id,
  188. SemanticsNodeId* output_value_id)
  189. -> ImplicitAsKind {
  190. // Start by making sure both sides are valid. If any part is invalid, the
  191. // result is invalid and we shouldn't error.
  192. if (value_id == SemanticsNodeId::BuiltinInvalidType) {
  193. // If the value is invalid, we can't do much, but do "succeed".
  194. return ImplicitAsKind::Identical;
  195. }
  196. auto value = semantics_ir_->GetNode(value_id);
  197. auto value_type_id = value.type_id();
  198. if (value_type_id == SemanticsTypeId::InvalidType) {
  199. return ImplicitAsKind::Identical;
  200. }
  201. if (as_type_id == SemanticsTypeId::InvalidType) {
  202. // Although the target type is invalid, this still changes the value.
  203. if (output_value_id != nullptr) {
  204. *output_value_id = SemanticsNodeId::BuiltinInvalidType;
  205. }
  206. return ImplicitAsKind::Compatible;
  207. }
  208. if (value_type_id == as_type_id) {
  209. // Type doesn't need to change.
  210. return ImplicitAsKind::Identical;
  211. }
  212. if (as_type_id == SemanticsTypeId::TypeType) {
  213. // TODO: When converting `()` to a type, the result is `() as Type`.
  214. // Right now there is no tuple value support.
  215. // When converting `{}` to a type, the result is `{} as Type`.
  216. if (value.kind() == SemanticsNodeKind::StructValue &&
  217. value.GetAsStructValue() == SemanticsNodeBlockId::Empty) {
  218. if (output_value_id != nullptr) {
  219. *output_value_id = semantics_ir_->GetType(value_type_id);
  220. }
  221. return ImplicitAsKind::Compatible;
  222. }
  223. }
  224. // TODO: Handle ImplicitAs for compatible structs and tuples.
  225. if (output_value_id != nullptr) {
  226. *output_value_id = SemanticsNodeId::BuiltinInvalidType;
  227. }
  228. return ImplicitAsKind::Incompatible;
  229. }
  230. auto SemanticsContext::ParamOrArgStart() -> void {
  231. params_or_args_stack_.Push();
  232. }
  233. auto SemanticsContext::ParamOrArgComma(bool for_args) -> void {
  234. ParamOrArgSave(for_args);
  235. }
  236. auto SemanticsContext::ParamOrArgEnd(bool for_args, ParseNodeKind start_kind)
  237. -> SemanticsNodeBlockId {
  238. if (parse_tree_->node_kind(node_stack_.PeekParseNode()) != start_kind) {
  239. ParamOrArgSave(for_args);
  240. }
  241. return params_or_args_stack_.Pop();
  242. }
  243. auto SemanticsContext::ParamOrArgSave(bool for_args) -> void {
  244. SemanticsNodeId param_or_arg_id = SemanticsNodeId::Invalid;
  245. if (for_args) {
  246. // For an argument, we add a stub reference to the expression on the top of
  247. // the stack. There may not be anything on the IR prior to this.
  248. auto [entry_parse_node, entry_node_id] =
  249. node_stack_.PopWithParseNode<SemanticsNodeId>();
  250. param_or_arg_id = AddNode(SemanticsNode::StubReference::Make(
  251. entry_parse_node, semantics_ir_->GetNode(entry_node_id).type_id(),
  252. entry_node_id));
  253. } else {
  254. // For a parameter, there should always be something in the IR.
  255. node_stack_.PopAndIgnore();
  256. auto ir_id = node_block_stack_.Peek();
  257. CARBON_CHECK(ir_id.is_valid());
  258. auto& ir = semantics_ir_->GetNodeBlock(ir_id);
  259. CARBON_CHECK(!ir.empty()) << "Should have had a param";
  260. param_or_arg_id = ir.back();
  261. }
  262. // Save the param or arg ID.
  263. auto& params_or_args =
  264. semantics_ir_->GetNodeBlock(params_or_args_stack_.PeekForAdd());
  265. params_or_args.push_back(param_or_arg_id);
  266. }
  267. auto SemanticsContext::CanonicalizeType(SemanticsNodeId node_id)
  268. -> SemanticsTypeId {
  269. auto it = canonical_types_.find(node_id);
  270. if (it != canonical_types_.end()) {
  271. return it->second;
  272. }
  273. auto type_id = semantics_ir_->AddType(node_id);
  274. CARBON_CHECK(canonical_types_.insert({node_id, type_id}).second);
  275. return type_id;
  276. }
  277. auto SemanticsContext::CanonicalizeStructType(ParseTree::Node parse_node,
  278. SemanticsNodeBlockId refs_id)
  279. -> SemanticsTypeId {
  280. // Construct the field structure for lookup.
  281. auto refs = semantics_ir_->GetNodeBlock(refs_id);
  282. llvm::FoldingSetNodeID canonical_id;
  283. for (const auto& ref_id : refs) {
  284. auto ref = semantics_ir_->GetNode(ref_id);
  285. canonical_id.AddInteger(ref.GetAsStructTypeField().index);
  286. canonical_id.AddInteger(ref.type_id().index);
  287. }
  288. // If a struct with matching fields was already created, reuse it.
  289. void* insert_pos;
  290. auto* node =
  291. canonical_struct_types_.FindNodeOrInsertPos(canonical_id, insert_pos);
  292. if (node != nullptr) {
  293. return node->type_id();
  294. }
  295. // The struct doesn't already exist, so create and store it as canonical.
  296. auto node_id = AddNode(SemanticsNode::StructType::Make(
  297. parse_node, SemanticsTypeId::TypeType, refs_id));
  298. auto type_id = semantics_ir_->AddType(node_id);
  299. CARBON_CHECK(canonical_types_.insert({node_id, type_id}).second);
  300. canonical_struct_types_nodes_.push_back(
  301. std::make_unique<StructTypeNode>(canonical_id, type_id));
  302. canonical_struct_types_.InsertNode(canonical_struct_types_nodes_.back().get(),
  303. insert_pos);
  304. return type_id;
  305. }
  306. auto SemanticsContext::PrintForStackDump(llvm::raw_ostream& output) const
  307. -> void {
  308. node_stack_.PrintForStackDump(output);
  309. node_block_stack_.PrintForStackDump(output);
  310. params_or_args_stack_.PrintForStackDump(output);
  311. args_type_info_stack_.PrintForStackDump(output);
  312. }
  313. } // namespace Carbon