semantics_ir.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. template <typename T>
  136. static auto PrintBlock(llvm::raw_ostream& out, llvm::StringLiteral block_name,
  137. const llvm::SmallVector<T>& blocks) {
  138. out << block_name << ": [\n";
  139. for (const auto& block : blocks) {
  140. out.indent(Indent);
  141. out << "[\n";
  142. for (const auto& node : block) {
  143. out.indent(2 * Indent);
  144. out << node << ",\n";
  145. }
  146. out.indent(Indent);
  147. out << "],\n";
  148. }
  149. out << "]\n";
  150. }
  151. auto SemanticsIR::Print(llvm::raw_ostream& out, bool include_builtins) const
  152. -> void {
  153. out << "cross_reference_irs_size: " << cross_reference_irs_.size() << "\n";
  154. PrintList(out, "functions", functions_);
  155. PrintList(out, "integer_literals", integer_literals_);
  156. PrintList(out, "real_literals", real_literals_);
  157. PrintList(out, "strings", strings_);
  158. PrintList(out, "types", types_);
  159. PrintBlock(out, "type_blocks", type_blocks_);
  160. out << "nodes: [\n";
  161. for (int i = include_builtins ? 0 : SemanticsBuiltinKind::ValidCount;
  162. i < static_cast<int>(nodes_.size()); ++i) {
  163. const auto& element = nodes_[i];
  164. out.indent(Indent);
  165. out << element << ",\n";
  166. }
  167. out << "]\n";
  168. PrintBlock(out, "node_blocks", node_blocks_);
  169. }
  170. auto SemanticsIR::StringifyType(SemanticsTypeId type_id) -> std::string {
  171. std::string str;
  172. llvm::raw_string_ostream out(str);
  173. struct Step {
  174. // The node to print.
  175. SemanticsNodeId node_id;
  176. // The index into node_id to print. Not used by all types.
  177. int index = 0;
  178. };
  179. llvm::SmallVector<Step> steps = {
  180. {.node_id = GetTypeAllowBuiltinTypes(type_id)}};
  181. while (!steps.empty()) {
  182. auto step = steps.pop_back_val();
  183. // Invalid node IDs will use the default invalid printing.
  184. if (!step.node_id.is_valid()) {
  185. out << step.node_id;
  186. continue;
  187. }
  188. // Builtins have designated labels.
  189. if (step.node_id.index < SemanticsBuiltinKind::ValidCount) {
  190. out << SemanticsBuiltinKind::FromInt(step.node_id.index).label();
  191. continue;
  192. }
  193. auto node = GetNode(step.node_id);
  194. switch (node.kind()) {
  195. case SemanticsNodeKind::StructType: {
  196. auto refs = GetNodeBlock(node.GetAsStructType());
  197. if (refs.empty()) {
  198. out << "{} as Type";
  199. break;
  200. } else if (step.index == 0) {
  201. out << "{";
  202. } else if (step.index < static_cast<int>(refs.size())) {
  203. out << ", ";
  204. } else {
  205. out << "}";
  206. break;
  207. }
  208. steps.push_back({.node_id = step.node_id, .index = step.index + 1});
  209. steps.push_back({.node_id = refs[step.index]});
  210. break;
  211. }
  212. case SemanticsNodeKind::StructTypeField: {
  213. auto [name_id, type_id] = node.GetAsStructTypeField();
  214. out << "." << GetString(name_id) << ": ";
  215. steps.push_back({.node_id = GetTypeAllowBuiltinTypes(type_id)});
  216. break;
  217. }
  218. case SemanticsNodeKind::TupleType: {
  219. auto refs = GetTypeBlock(node.GetAsTupleType());
  220. if (refs.empty()) {
  221. out << "() as type";
  222. break;
  223. } else if (step.index == 0) {
  224. out << "(";
  225. } else if (step.index < static_cast<int>(refs.size())) {
  226. out << ", ";
  227. } else {
  228. // A tuple of one element has a comma to disambiguate from an
  229. // expression.
  230. if (step.index == 1) {
  231. out << ",";
  232. }
  233. out << ") as type";
  234. break;
  235. }
  236. steps.push_back({.node_id = step.node_id, .index = step.index + 1});
  237. steps.push_back(
  238. {.node_id = GetTypeAllowBuiltinTypes(refs[step.index])});
  239. break;
  240. }
  241. case SemanticsNodeKind::Assign:
  242. case SemanticsNodeKind::BinaryOperatorAdd:
  243. case SemanticsNodeKind::BindName:
  244. case SemanticsNodeKind::BlockArg:
  245. case SemanticsNodeKind::BoolLiteral:
  246. case SemanticsNodeKind::Branch:
  247. case SemanticsNodeKind::BranchIf:
  248. case SemanticsNodeKind::BranchWithArg:
  249. case SemanticsNodeKind::Builtin:
  250. case SemanticsNodeKind::Call:
  251. case SemanticsNodeKind::CrossReference:
  252. case SemanticsNodeKind::FunctionDeclaration:
  253. case SemanticsNodeKind::IntegerLiteral:
  254. case SemanticsNodeKind::Namespace:
  255. case SemanticsNodeKind::RealLiteral:
  256. case SemanticsNodeKind::Return:
  257. case SemanticsNodeKind::ReturnExpression:
  258. case SemanticsNodeKind::StringLiteral:
  259. case SemanticsNodeKind::StructMemberAccess:
  260. case SemanticsNodeKind::StructValue:
  261. case SemanticsNodeKind::StubReference:
  262. case SemanticsNodeKind::TupleValue:
  263. case SemanticsNodeKind::UnaryOperatorNot:
  264. case SemanticsNodeKind::VarStorage:
  265. // We don't need to handle stringification for nodes that don't show up
  266. // in errors, but make it clear what's going on so that it's clearer
  267. // when stringification is needed.
  268. out << "<cannot stringify " << step.node_id << ">";
  269. break;
  270. case SemanticsNodeKind::Invalid:
  271. llvm_unreachable("SemanticsNodeKind::Invalid is never used.");
  272. }
  273. }
  274. return str;
  275. }
  276. } // namespace Carbon