semantics_ir.cpp 7.5 KB

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