semantics_ir.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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_ir.h"
  5. #include "common/check.h"
  6. #include "toolchain/common/pretty_stack_trace_function.h"
  7. #include "toolchain/parser/parse_tree_node_location_translator.h"
  8. #include "toolchain/semantics/semantics_builtin_kind.h"
  9. #include "toolchain/semantics/semantics_context.h"
  10. #include "toolchain/semantics/semantics_node.h"
  11. namespace Carbon {
  12. auto SemanticsIR::MakeBuiltinIR() -> SemanticsIR {
  13. SemanticsIR semantics(/*builtin_ir=*/nullptr);
  14. semantics.nodes_.reserve(SemanticsBuiltinKind::ValidCount);
  15. // InvalidType uses a self-referential type so that it's not accidentally
  16. // treated as a normal type. Every other builtin is a type, including the
  17. // self-referential TypeType.
  18. #define CARBON_SEMANTICS_BUILTIN_KIND(Name, ...) \
  19. semantics.nodes_.push_back(SemanticsNode::Builtin::Make( \
  20. SemanticsBuiltinKind::Name, \
  21. SemanticsBuiltinKind::Name == SemanticsBuiltinKind::InvalidType \
  22. ? SemanticsTypeId::InvalidType \
  23. : SemanticsTypeId::TypeType));
  24. #include "toolchain/semantics/semantics_builtin_kind.def"
  25. CARBON_CHECK(semantics.node_blocks_.size() == 1)
  26. << "BuildBuiltins should only have the empty block, actual: "
  27. << semantics.node_blocks_.size();
  28. CARBON_CHECK(semantics.nodes_.size() == SemanticsBuiltinKind::ValidCount)
  29. << "BuildBuiltins should produce " << SemanticsBuiltinKind::ValidCount
  30. << " nodes, actual: " << semantics.nodes_.size();
  31. return semantics;
  32. }
  33. auto SemanticsIR::MakeFromParseTree(const SemanticsIR& builtin_ir,
  34. const TokenizedBuffer& tokens,
  35. const ParseTree& parse_tree,
  36. DiagnosticConsumer& consumer,
  37. llvm::raw_ostream* vlog_stream)
  38. -> SemanticsIR {
  39. SemanticsIR semantics(&builtin_ir);
  40. // Copy builtins over.
  41. semantics.nodes_.resize_for_overwrite(SemanticsBuiltinKind::ValidCount);
  42. static constexpr auto BuiltinIR = SemanticsCrossReferenceIRId(0);
  43. for (int i = 0; i < SemanticsBuiltinKind::ValidCount; ++i) {
  44. // We can reuse the type node ID because the offsets of cross-references
  45. // will be the same in this IR.
  46. auto type = builtin_ir.nodes_[i].type_id();
  47. semantics.nodes_[i] = SemanticsNode::CrossReference::Make(
  48. type, BuiltinIR, SemanticsNodeId(i));
  49. }
  50. ParseTreeNodeLocationTranslator translator(&tokens, &parse_tree);
  51. ErrorTrackingDiagnosticConsumer err_tracker(consumer);
  52. DiagnosticEmitter<ParseTree::Node> emitter(translator, err_tracker);
  53. SemanticsContext context(tokens, emitter, parse_tree, semantics, vlog_stream);
  54. PrettyStackTraceFunction context_dumper(
  55. [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); });
  56. // Add a block for the ParseTree.
  57. context.node_block_stack().Push();
  58. context.PushScope();
  59. // Loops over all nodes in the tree. On some errors, this may return early,
  60. // for example if an unrecoverable state is encountered.
  61. for (auto parse_node : parse_tree.postorder()) {
  62. switch (auto parse_kind = parse_tree.node_kind(parse_node)) {
  63. #define CARBON_PARSE_NODE_KIND(Name) \
  64. case ParseNodeKind::Name: { \
  65. if (!SemanticsHandle##Name(context, parse_node)) { \
  66. semantics.has_errors_ = true; \
  67. return semantics; \
  68. } \
  69. break; \
  70. }
  71. #include "toolchain/parser/parse_node_kind.def"
  72. }
  73. }
  74. // Pop information for the file-level scope.
  75. semantics.top_node_block_id_ = context.node_block_stack().Pop();
  76. context.PopScope();
  77. context.VerifyOnFinish();
  78. semantics.has_errors_ = err_tracker.seen_error();
  79. return semantics;
  80. }
  81. static constexpr int Indent = 2;
  82. template <typename T>
  83. static auto PrintList(llvm::raw_ostream& out, llvm::StringLiteral name,
  84. const llvm::SmallVector<T>& list) {
  85. out << name << ": [\n";
  86. for (const auto& element : list) {
  87. out.indent(Indent);
  88. out << element << ",\n";
  89. }
  90. out << "]\n";
  91. }
  92. auto SemanticsIR::Print(llvm::raw_ostream& out, bool include_builtins) const
  93. -> void {
  94. out << "cross_reference_irs_size: " << cross_reference_irs_.size() << "\n";
  95. PrintList(out, "callables", callables_);
  96. PrintList(out, "integer_literals", integer_literals_);
  97. PrintList(out, "real_literals", real_literals_);
  98. PrintList(out, "strings", strings_);
  99. PrintList(out, "types", types_);
  100. out << "nodes: [\n";
  101. for (int i = include_builtins ? 0 : SemanticsBuiltinKind::ValidCount;
  102. i < static_cast<int>(nodes_.size()); ++i) {
  103. const auto& element = nodes_[i];
  104. out.indent(Indent);
  105. out << element << ",\n";
  106. }
  107. out << "]\n";
  108. out << "node_blocks: [\n";
  109. for (const auto& node_block : node_blocks_) {
  110. out.indent(Indent);
  111. out << "[\n";
  112. for (const auto& node : node_block) {
  113. out.indent(2 * Indent);
  114. out << node << ",\n";
  115. }
  116. out.indent(Indent);
  117. out << "],\n";
  118. }
  119. out << "]\n";
  120. }
  121. auto SemanticsIR::StringifyType(SemanticsTypeId type_id) -> std::string {
  122. std::string str;
  123. llvm::raw_string_ostream out(str);
  124. struct Step {
  125. // The node to print.
  126. SemanticsNodeId node_id;
  127. // The index into node_id to print. Not used by all types.
  128. int index = 0;
  129. };
  130. llvm::SmallVector<Step> steps = {
  131. {.node_id = GetTypeAllowBuiltinTypes(type_id)}};
  132. while (!steps.empty()) {
  133. auto step = steps.pop_back_val();
  134. // Invalid node IDs will use the default invalid printing.
  135. if (!step.node_id.is_valid()) {
  136. out << step.node_id;
  137. continue;
  138. }
  139. // Builtins have designated labels.
  140. if (step.node_id.index < SemanticsBuiltinKind::ValidCount) {
  141. out << SemanticsBuiltinKind::FromInt(step.node_id.index).label();
  142. continue;
  143. }
  144. auto node = GetNode(step.node_id);
  145. switch (node.kind()) {
  146. case SemanticsNodeKind::StructType: {
  147. auto refs = GetNodeBlock(node.GetAsStructType());
  148. if (refs.empty()) {
  149. out << "{} as Type";
  150. break;
  151. } else if (step.index == 0) {
  152. out << "{";
  153. } else if (step.index < static_cast<int>(refs.size())) {
  154. out << ", ";
  155. } else {
  156. out << "}";
  157. break;
  158. }
  159. steps.push_back({.node_id = step.node_id, .index = step.index + 1});
  160. steps.push_back({.node_id = refs[step.index]});
  161. break;
  162. }
  163. case SemanticsNodeKind::StructTypeField: {
  164. out << "." << GetString(node.GetAsStructTypeField()) << ": ";
  165. steps.push_back({.node_id = GetTypeAllowBuiltinTypes(node.type_id())});
  166. break;
  167. }
  168. case SemanticsNodeKind::Assign:
  169. case SemanticsNodeKind::BinaryOperatorAdd:
  170. case SemanticsNodeKind::BindName:
  171. case SemanticsNodeKind::Builtin:
  172. case SemanticsNodeKind::Call:
  173. case SemanticsNodeKind::CodeBlock:
  174. case SemanticsNodeKind::CrossReference:
  175. case SemanticsNodeKind::FunctionDeclaration:
  176. case SemanticsNodeKind::FunctionDefinition:
  177. case SemanticsNodeKind::IntegerLiteral:
  178. case SemanticsNodeKind::RealLiteral:
  179. case SemanticsNodeKind::Return:
  180. case SemanticsNodeKind::ReturnExpression:
  181. case SemanticsNodeKind::StringLiteral:
  182. case SemanticsNodeKind::StructMemberAccess:
  183. case SemanticsNodeKind::StructValue:
  184. case SemanticsNodeKind::StubReference:
  185. case SemanticsNodeKind::VarStorage:
  186. // We don't need to handle stringification for nodes that don't show up
  187. // in errors, but make it clear what's going on so that it's clearer
  188. // when stringification is needed.
  189. out << "<cannot stringify " << step.node_id << ">";
  190. break;
  191. case SemanticsNodeKind::Invalid:
  192. llvm_unreachable("SemanticsNodeKind::Invalid is never used.");
  193. }
  194. }
  195. return str;
  196. }
  197. } // namespace Carbon