semantics_ir.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. #include "toolchain/semantics/semantics_node_kind.h"
  12. namespace Carbon {
  13. auto SemanticsIR::MakeBuiltinIR() -> SemanticsIR {
  14. SemanticsIR semantics_ir(/*builtin_ir=*/nullptr);
  15. semantics_ir.nodes_.reserve(SemanticsBuiltinKind::ValidCount);
  16. // Error uses a self-referential type so that it's not accidentally treated as
  17. // a normal type. Every other builtin is a type, including the
  18. // self-referential TypeType.
  19. #define CARBON_SEMANTICS_BUILTIN_KIND(Name, ...) \
  20. semantics_ir.nodes_.push_back(SemanticsNode::Builtin::Make( \
  21. SemanticsBuiltinKind::Name, \
  22. SemanticsBuiltinKind::Name == SemanticsBuiltinKind::Error \
  23. ? SemanticsTypeId::Error \
  24. : SemanticsTypeId::TypeType));
  25. #include "toolchain/semantics/semantics_builtin_kind.def"
  26. CARBON_CHECK(semantics_ir.node_blocks_.size() == 1)
  27. << "BuildBuiltins should only have the empty block, actual: "
  28. << semantics_ir.node_blocks_.size();
  29. CARBON_CHECK(semantics_ir.nodes_.size() == SemanticsBuiltinKind::ValidCount)
  30. << "BuildBuiltins should produce " << SemanticsBuiltinKind::ValidCount
  31. << " nodes, actual: " << semantics_ir.nodes_.size();
  32. return semantics_ir;
  33. }
  34. auto SemanticsIR::MakeFromParseTree(const SemanticsIR& builtin_ir,
  35. const TokenizedBuffer& tokens,
  36. const ParseTree& parse_tree,
  37. DiagnosticConsumer& consumer,
  38. llvm::raw_ostream* vlog_stream)
  39. -> SemanticsIR {
  40. SemanticsIR semantics_ir(&builtin_ir);
  41. // Copy builtins over.
  42. semantics_ir.nodes_.resize_for_overwrite(SemanticsBuiltinKind::ValidCount);
  43. static constexpr auto BuiltinIR = SemanticsCrossReferenceIRId(0);
  44. for (int i = 0; i < SemanticsBuiltinKind::ValidCount; ++i) {
  45. // We can reuse the type node ID because the offsets of cross-references
  46. // will be the same in this IR.
  47. auto type = builtin_ir.nodes_[i].type_id();
  48. semantics_ir.nodes_[i] = SemanticsNode::CrossReference::Make(
  49. type, BuiltinIR, SemanticsNodeId(i));
  50. }
  51. ParseTreeNodeLocationTranslator translator(&tokens, &parse_tree);
  52. ErrorTrackingDiagnosticConsumer err_tracker(consumer);
  53. DiagnosticEmitter<ParseTree::Node> emitter(translator, err_tracker);
  54. SemanticsContext context(tokens, emitter, parse_tree, semantics_ir,
  55. vlog_stream);
  56. PrettyStackTraceFunction context_dumper(
  57. [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); });
  58. // Add a block for the ParseTree.
  59. context.node_block_stack().Push();
  60. context.PushScope();
  61. // Loops over all nodes in the tree. On some errors, this may return early,
  62. // for example if an unrecoverable state is encountered.
  63. for (auto parse_node : parse_tree.postorder()) {
  64. switch (auto parse_kind = parse_tree.node_kind(parse_node)) {
  65. #define CARBON_PARSE_NODE_KIND(Name) \
  66. case ParseNodeKind::Name: { \
  67. if (!SemanticsHandle##Name(context, parse_node)) { \
  68. semantics_ir.has_errors_ = true; \
  69. return semantics_ir; \
  70. } \
  71. break; \
  72. }
  73. #include "toolchain/parser/parse_node_kind.def"
  74. }
  75. }
  76. // Pop information for the file-level scope.
  77. semantics_ir.top_node_block_id_ = context.node_block_stack().Pop();
  78. context.PopScope();
  79. context.VerifyOnFinish();
  80. semantics_ir.has_errors_ = err_tracker.seen_error();
  81. #ifndef NDEBUG
  82. if (auto verify = semantics_ir.Verify(); !verify.ok()) {
  83. CARBON_FATAL() << semantics_ir
  84. << "Built invalid semantics IR: " << verify.error() << "\n";
  85. }
  86. #endif
  87. return semantics_ir;
  88. }
  89. auto SemanticsIR::Verify() const -> ErrorOr<Success> {
  90. // Invariants don't necessarily hold for invalid IR.
  91. if (has_errors_) {
  92. return Success();
  93. }
  94. // Check that every code block has a terminator sequence that appears at the
  95. // end of the block.
  96. for (const SemanticsFunction& function : functions_) {
  97. for (SemanticsNodeBlockId block_id : function.body_block_ids) {
  98. SemanticsTerminatorKind prior_kind =
  99. SemanticsTerminatorKind::NotTerminator;
  100. for (SemanticsNodeId node_id : GetNodeBlock(block_id)) {
  101. SemanticsTerminatorKind node_kind =
  102. GetNode(node_id).kind().terminator_kind();
  103. if (prior_kind == SemanticsTerminatorKind::Terminator) {
  104. return Error(llvm::formatv("Node {0} in block {1} follows terminator",
  105. node_id, block_id));
  106. }
  107. if (prior_kind > node_kind) {
  108. return Error(
  109. llvm::formatv("Non-terminator node {0} in block {1} follows "
  110. "terminator sequence",
  111. node_id, block_id));
  112. }
  113. prior_kind = node_kind;
  114. }
  115. if (prior_kind != SemanticsTerminatorKind::Terminator) {
  116. return Error(llvm::formatv("No terminator in block {0}", block_id));
  117. }
  118. }
  119. }
  120. // TODO: Check that a node only references other nodes that are either global
  121. // or that dominate it.
  122. return Success();
  123. }
  124. static constexpr int Indent = 2;
  125. template <typename T>
  126. static auto PrintList(llvm::raw_ostream& out, llvm::StringLiteral name,
  127. const llvm::SmallVector<T>& list) {
  128. out << name << ": [\n";
  129. for (const auto& element : list) {
  130. out.indent(Indent);
  131. out << element << ",\n";
  132. }
  133. out << "]\n";
  134. }
  135. auto SemanticsIR::Print(llvm::raw_ostream& out, bool include_builtins) const
  136. -> void {
  137. out << "cross_reference_irs_size: " << cross_reference_irs_.size() << "\n";
  138. PrintList(out, "functions", functions_);
  139. PrintList(out, "integer_literals", integer_literals_);
  140. PrintList(out, "real_literals", real_literals_);
  141. PrintList(out, "strings", strings_);
  142. PrintList(out, "types", types_);
  143. out << "nodes: [\n";
  144. for (int i = include_builtins ? 0 : SemanticsBuiltinKind::ValidCount;
  145. i < static_cast<int>(nodes_.size()); ++i) {
  146. const auto& element = nodes_[i];
  147. out.indent(Indent);
  148. out << element << ",\n";
  149. }
  150. out << "]\n";
  151. out << "node_blocks: [\n";
  152. for (const auto& node_block : node_blocks_) {
  153. out.indent(Indent);
  154. out << "[\n";
  155. for (const auto& node : node_block) {
  156. out.indent(2 * Indent);
  157. out << node << ",\n";
  158. }
  159. out.indent(Indent);
  160. out << "],\n";
  161. }
  162. out << "]\n";
  163. }
  164. auto SemanticsIR::StringifyType(SemanticsTypeId type_id) -> std::string {
  165. std::string str;
  166. llvm::raw_string_ostream out(str);
  167. struct Step {
  168. // The node to print.
  169. SemanticsNodeId node_id;
  170. // The index into node_id to print. Not used by all types.
  171. int index = 0;
  172. };
  173. llvm::SmallVector<Step> steps = {
  174. {.node_id = GetTypeAllowBuiltinTypes(type_id)}};
  175. while (!steps.empty()) {
  176. auto step = steps.pop_back_val();
  177. // Invalid node IDs will use the default invalid printing.
  178. if (!step.node_id.is_valid()) {
  179. out << step.node_id;
  180. continue;
  181. }
  182. // Builtins have designated labels.
  183. if (step.node_id.index < SemanticsBuiltinKind::ValidCount) {
  184. out << SemanticsBuiltinKind::FromInt(step.node_id.index).label();
  185. continue;
  186. }
  187. auto node = GetNode(step.node_id);
  188. switch (node.kind()) {
  189. case SemanticsNodeKind::StructType: {
  190. auto refs = GetNodeBlock(node.GetAsStructType());
  191. if (refs.empty()) {
  192. out << "{} as Type";
  193. break;
  194. } else if (step.index == 0) {
  195. out << "{";
  196. } else if (step.index < static_cast<int>(refs.size())) {
  197. out << ", ";
  198. } else {
  199. out << "}";
  200. break;
  201. }
  202. steps.push_back({.node_id = step.node_id, .index = step.index + 1});
  203. steps.push_back({.node_id = refs[step.index]});
  204. break;
  205. }
  206. case SemanticsNodeKind::StructTypeField: {
  207. out << "." << GetString(node.GetAsStructTypeField()) << ": ";
  208. steps.push_back({.node_id = GetTypeAllowBuiltinTypes(node.type_id())});
  209. break;
  210. }
  211. case SemanticsNodeKind::TupleType: {
  212. auto refs = GetTypeBlock(node.GetAsTupleType());
  213. if (refs.empty()) {
  214. out << "() as type";
  215. break;
  216. } else if (step.index == 0) {
  217. out << "(";
  218. } else if (step.index < static_cast<int>(refs.size())) {
  219. out << ", ";
  220. } else {
  221. // A tuple of one element has a comma to disambiguate from an
  222. // expression.
  223. if (step.index == 1) {
  224. out << ",";
  225. }
  226. out << ") as type";
  227. break;
  228. }
  229. steps.push_back({.node_id = step.node_id, .index = step.index + 1});
  230. steps.push_back(
  231. {.node_id = GetTypeAllowBuiltinTypes(refs[step.index])});
  232. break;
  233. }
  234. case SemanticsNodeKind::Assign:
  235. case SemanticsNodeKind::BinaryOperatorAdd:
  236. case SemanticsNodeKind::BindName:
  237. case SemanticsNodeKind::BlockArg:
  238. case SemanticsNodeKind::BoolLiteral:
  239. case SemanticsNodeKind::Branch:
  240. case SemanticsNodeKind::BranchIf:
  241. case SemanticsNodeKind::BranchWithArg:
  242. case SemanticsNodeKind::Builtin:
  243. case SemanticsNodeKind::Call:
  244. case SemanticsNodeKind::CrossReference:
  245. case SemanticsNodeKind::FunctionDeclaration:
  246. case SemanticsNodeKind::IntegerLiteral:
  247. case SemanticsNodeKind::Namespace:
  248. case SemanticsNodeKind::RealLiteral:
  249. case SemanticsNodeKind::Return:
  250. case SemanticsNodeKind::ReturnExpression:
  251. case SemanticsNodeKind::StringLiteral:
  252. case SemanticsNodeKind::StructMemberAccess:
  253. case SemanticsNodeKind::StructValue:
  254. case SemanticsNodeKind::StubReference:
  255. case SemanticsNodeKind::TupleValue:
  256. case SemanticsNodeKind::UnaryOperatorNot:
  257. case SemanticsNodeKind::VarStorage:
  258. // We don't need to handle stringification for nodes that don't show up
  259. // in errors, but make it clear what's going on so that it's clearer
  260. // when stringification is needed.
  261. out << "<cannot stringify " << step.node_id << ">";
  262. break;
  263. case SemanticsNodeKind::Invalid:
  264. llvm_unreachable("SemanticsNodeKind::Invalid is never used.");
  265. }
  266. }
  267. return str;
  268. }
  269. } // namespace Carbon