semantics_ir.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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 "llvm/ADT/DenseSet.h"
  7. #include "llvm/ADT/SmallVector.h"
  8. #include "llvm/Support/SaveAndRestore.h"
  9. #include "toolchain/common/pretty_stack_trace_function.h"
  10. #include "toolchain/parser/parse_tree_node_location_translator.h"
  11. #include "toolchain/semantics/semantics_builtin_kind.h"
  12. #include "toolchain/semantics/semantics_context.h"
  13. #include "toolchain/semantics/semantics_node.h"
  14. #include "toolchain/semantics/semantics_node_kind.h"
  15. namespace Carbon {
  16. auto SemanticsIR::MakeBuiltinIR() -> SemanticsIR {
  17. SemanticsIR semantics_ir(/*builtin_ir=*/nullptr);
  18. semantics_ir.nodes_.reserve(SemanticsBuiltinKind::ValidCount);
  19. // Error uses a self-referential type so that it's not accidentally treated as
  20. // a normal type. Every other builtin is a type, including the
  21. // self-referential TypeType.
  22. #define CARBON_SEMANTICS_BUILTIN_KIND(Name, ...) \
  23. semantics_ir.nodes_.push_back(SemanticsNode::Builtin::Make( \
  24. SemanticsBuiltinKind::Name, \
  25. SemanticsBuiltinKind::Name == SemanticsBuiltinKind::Error \
  26. ? SemanticsTypeId::Error \
  27. : SemanticsTypeId::TypeType));
  28. #include "toolchain/semantics/semantics_builtin_kind.def"
  29. CARBON_CHECK(semantics_ir.node_blocks_.size() == 1)
  30. << "BuildBuiltins should only have the empty block, actual: "
  31. << semantics_ir.node_blocks_.size();
  32. CARBON_CHECK(semantics_ir.nodes_.size() == SemanticsBuiltinKind::ValidCount)
  33. << "BuildBuiltins should produce " << SemanticsBuiltinKind::ValidCount
  34. << " nodes, actual: " << semantics_ir.nodes_.size();
  35. return semantics_ir;
  36. }
  37. auto SemanticsIR::MakeFromParseTree(const SemanticsIR& builtin_ir,
  38. const TokenizedBuffer& tokens,
  39. const ParseTree& parse_tree,
  40. DiagnosticConsumer& consumer,
  41. llvm::raw_ostream* vlog_stream)
  42. -> SemanticsIR {
  43. SemanticsIR semantics_ir(&builtin_ir);
  44. // Copy builtins over.
  45. semantics_ir.nodes_.resize_for_overwrite(SemanticsBuiltinKind::ValidCount);
  46. static constexpr auto BuiltinIR = SemanticsCrossReferenceIRId(0);
  47. for (int i = 0; i < SemanticsBuiltinKind::ValidCount; ++i) {
  48. // We can reuse the type node ID because the offsets of cross-references
  49. // will be the same in this IR.
  50. auto type = builtin_ir.nodes_[i].type_id();
  51. semantics_ir.nodes_[i] = SemanticsNode::CrossReference::Make(
  52. type, BuiltinIR, SemanticsNodeId(i));
  53. }
  54. ParseTreeNodeLocationTranslator translator(&tokens, &parse_tree);
  55. ErrorTrackingDiagnosticConsumer err_tracker(consumer);
  56. DiagnosticEmitter<ParseTree::Node> emitter(translator, err_tracker);
  57. SemanticsContext context(tokens, emitter, parse_tree, semantics_ir,
  58. vlog_stream);
  59. PrettyStackTraceFunction context_dumper(
  60. [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); });
  61. // Add a block for the ParseTree.
  62. context.node_block_stack().Push();
  63. context.PushScope();
  64. // Loops over all nodes in the tree. On some errors, this may return early,
  65. // for example if an unrecoverable state is encountered.
  66. for (auto parse_node : parse_tree.postorder()) {
  67. switch (auto parse_kind = parse_tree.node_kind(parse_node)) {
  68. #define CARBON_PARSE_NODE_KIND(Name) \
  69. case ParseNodeKind::Name: { \
  70. if (!SemanticsHandle##Name(context, parse_node)) { \
  71. semantics_ir.has_errors_ = true; \
  72. return semantics_ir; \
  73. } \
  74. break; \
  75. }
  76. #include "toolchain/parser/parse_node_kind.def"
  77. }
  78. }
  79. // Pop information for the file-level scope.
  80. semantics_ir.top_node_block_id_ = context.node_block_stack().Pop();
  81. context.PopScope();
  82. context.VerifyOnFinish();
  83. semantics_ir.has_errors_ = err_tracker.seen_error();
  84. #ifndef NDEBUG
  85. if (auto verify = semantics_ir.Verify(); !verify.ok()) {
  86. CARBON_FATAL() << semantics_ir
  87. << "Built invalid semantics IR: " << verify.error() << "\n";
  88. }
  89. #endif
  90. return semantics_ir;
  91. }
  92. auto SemanticsIR::Verify() const -> ErrorOr<Success> {
  93. // Invariants don't necessarily hold for invalid IR.
  94. if (has_errors_) {
  95. return Success();
  96. }
  97. // Check that every code block has a terminator sequence that appears at the
  98. // end of the block.
  99. for (const SemanticsFunction& function : functions_) {
  100. for (SemanticsNodeBlockId block_id : function.body_block_ids) {
  101. SemanticsTerminatorKind prior_kind =
  102. SemanticsTerminatorKind::NotTerminator;
  103. for (SemanticsNodeId node_id : GetNodeBlock(block_id)) {
  104. SemanticsTerminatorKind node_kind =
  105. GetNode(node_id).kind().terminator_kind();
  106. if (prior_kind == SemanticsTerminatorKind::Terminator) {
  107. return Error(llvm::formatv("Node {0} in block {1} follows terminator",
  108. node_id, block_id));
  109. }
  110. if (prior_kind > node_kind) {
  111. return Error(
  112. llvm::formatv("Non-terminator node {0} in block {1} follows "
  113. "terminator sequence",
  114. node_id, block_id));
  115. }
  116. prior_kind = node_kind;
  117. }
  118. if (prior_kind != SemanticsTerminatorKind::Terminator) {
  119. return Error(llvm::formatv("No terminator in block {0}", block_id));
  120. }
  121. }
  122. }
  123. // TODO: Check that a node only references other nodes that are either global
  124. // or that dominate it.
  125. return Success();
  126. }
  127. static constexpr int Indent = 2;
  128. template <typename T>
  129. static auto PrintList(llvm::raw_ostream& out, llvm::StringLiteral name,
  130. const llvm::SmallVector<T>& list) {
  131. out << name << ": [\n";
  132. for (const auto& element : list) {
  133. out.indent(Indent);
  134. out << element << ",\n";
  135. }
  136. out << "]\n";
  137. }
  138. template <typename T>
  139. static auto PrintBlock(llvm::raw_ostream& out, llvm::StringLiteral block_name,
  140. const llvm::SmallVector<T>& blocks) {
  141. out << block_name << ": [\n";
  142. for (const auto& block : blocks) {
  143. out.indent(Indent);
  144. out << "[\n";
  145. for (const auto& node : block) {
  146. out.indent(2 * Indent);
  147. out << node << ",\n";
  148. }
  149. out.indent(Indent);
  150. out << "],\n";
  151. }
  152. out << "]\n";
  153. }
  154. auto SemanticsIR::Print(llvm::raw_ostream& out, bool include_builtins) const
  155. -> void {
  156. out << "cross_reference_irs_size: " << cross_reference_irs_.size() << "\n";
  157. PrintList(out, "functions", functions_);
  158. PrintList(out, "integer_literals", integer_literals_);
  159. PrintList(out, "real_literals", real_literals_);
  160. PrintList(out, "strings", strings_);
  161. PrintList(out, "types", types_);
  162. PrintBlock(out, "type_blocks", type_blocks_);
  163. out << "nodes: [\n";
  164. for (int i = include_builtins ? 0 : SemanticsBuiltinKind::ValidCount;
  165. i < static_cast<int>(nodes_.size()); ++i) {
  166. const auto& element = nodes_[i];
  167. out.indent(Indent);
  168. out << element << ",\n";
  169. }
  170. out << "]\n";
  171. PrintBlock(out, "node_blocks", node_blocks_);
  172. }
  173. // Map a node kind representing a type into an integer describing the
  174. // precedence of that type's syntax. Higher numbers correspond to higher
  175. // precedence.
  176. static auto GetTypePrecedence(SemanticsNodeKind kind) -> int {
  177. switch (kind) {
  178. case SemanticsNodeKind::Builtin:
  179. case SemanticsNodeKind::StructType:
  180. case SemanticsNodeKind::TupleType:
  181. return 0;
  182. case SemanticsNodeKind::ConstType:
  183. return -1;
  184. case SemanticsNodeKind::PointerType:
  185. return -2;
  186. case SemanticsNodeKind::CrossReference:
  187. // TODO: Once we support stringification of cross-references, we'll need
  188. // to determine the precedence of the target of the cross-reference. For
  189. // now, all cross-references refer to builtin types from the prelude.
  190. return 0;
  191. case SemanticsNodeKind::AddressOf:
  192. case SemanticsNodeKind::Assign:
  193. case SemanticsNodeKind::BinaryOperatorAdd:
  194. case SemanticsNodeKind::BindName:
  195. case SemanticsNodeKind::BlockArg:
  196. case SemanticsNodeKind::BoolLiteral:
  197. case SemanticsNodeKind::Branch:
  198. case SemanticsNodeKind::BranchIf:
  199. case SemanticsNodeKind::BranchWithArg:
  200. case SemanticsNodeKind::Call:
  201. case SemanticsNodeKind::Dereference:
  202. case SemanticsNodeKind::FunctionDeclaration:
  203. case SemanticsNodeKind::Index:
  204. case SemanticsNodeKind::IntegerLiteral:
  205. case SemanticsNodeKind::Invalid:
  206. case SemanticsNodeKind::Namespace:
  207. case SemanticsNodeKind::RealLiteral:
  208. case SemanticsNodeKind::Return:
  209. case SemanticsNodeKind::ReturnExpression:
  210. case SemanticsNodeKind::StringLiteral:
  211. case SemanticsNodeKind::StructMemberAccess:
  212. case SemanticsNodeKind::StructTypeField:
  213. case SemanticsNodeKind::StructValue:
  214. case SemanticsNodeKind::StubReference:
  215. case SemanticsNodeKind::TupleValue:
  216. case SemanticsNodeKind::UnaryOperatorNot:
  217. case SemanticsNodeKind::VarStorage:
  218. CARBON_FATAL() << "GetTypePrecedence for non-type node kind " << kind;
  219. }
  220. }
  221. auto SemanticsIR::StringifyType(SemanticsTypeId type_id,
  222. bool in_type_context) const -> std::string {
  223. std::string str;
  224. llvm::raw_string_ostream out(str);
  225. struct Step {
  226. // The node to print.
  227. SemanticsNodeId node_id;
  228. // The index into node_id to print. Not used by all types.
  229. int index = 0;
  230. auto Next() const -> Step {
  231. return {.node_id = node_id, .index = index + 1};
  232. }
  233. };
  234. auto outer_node_id = GetTypeAllowBuiltinTypes(type_id);
  235. llvm::SmallVector<Step> steps = {{.node_id = outer_node_id}};
  236. while (!steps.empty()) {
  237. auto step = steps.pop_back_val();
  238. // Invalid node IDs will use the default invalid printing.
  239. if (!step.node_id.is_valid()) {
  240. out << step.node_id;
  241. continue;
  242. }
  243. // Builtins have designated labels.
  244. if (step.node_id.index < SemanticsBuiltinKind::ValidCount) {
  245. out << SemanticsBuiltinKind::FromInt(step.node_id.index).label();
  246. continue;
  247. }
  248. auto node = GetNode(step.node_id);
  249. switch (node.kind()) {
  250. case SemanticsNodeKind::ConstType: {
  251. if (step.index == 0) {
  252. out << "const ";
  253. // Add parentheses if required.
  254. auto inner_type_node_id =
  255. GetTypeAllowBuiltinTypes(node.GetAsConstType());
  256. if (GetTypePrecedence(GetNode(inner_type_node_id).kind()) <
  257. GetTypePrecedence(node.kind())) {
  258. out << "(";
  259. steps.push_back(step.Next());
  260. }
  261. steps.push_back({.node_id = inner_type_node_id});
  262. } else if (step.index == 1) {
  263. out << ")";
  264. }
  265. break;
  266. }
  267. case SemanticsNodeKind::PointerType: {
  268. if (step.index == 0) {
  269. steps.push_back(step.Next());
  270. steps.push_back(
  271. {.node_id = GetTypeAllowBuiltinTypes(node.GetAsPointerType())});
  272. } else if (step.index == 1) {
  273. out << "*";
  274. }
  275. break;
  276. }
  277. case SemanticsNodeKind::StructType: {
  278. auto refs = GetNodeBlock(node.GetAsStructType());
  279. if (refs.empty()) {
  280. out << "{}";
  281. break;
  282. } else if (step.index == 0) {
  283. out << "{";
  284. } else if (step.index < static_cast<int>(refs.size())) {
  285. out << ", ";
  286. } else {
  287. out << "}";
  288. break;
  289. }
  290. steps.push_back(step.Next());
  291. steps.push_back({.node_id = refs[step.index]});
  292. break;
  293. }
  294. case SemanticsNodeKind::StructTypeField: {
  295. auto [name_id, type_id] = node.GetAsStructTypeField();
  296. out << "." << GetString(name_id) << ": ";
  297. steps.push_back({.node_id = GetTypeAllowBuiltinTypes(type_id)});
  298. break;
  299. }
  300. case SemanticsNodeKind::TupleType: {
  301. auto refs = GetTypeBlock(node.GetAsTupleType());
  302. if (refs.empty()) {
  303. out << "()";
  304. break;
  305. } else if (step.index == 0) {
  306. out << "(";
  307. } else if (step.index < static_cast<int>(refs.size())) {
  308. out << ", ";
  309. } else {
  310. // A tuple of one element has a comma to disambiguate from an
  311. // expression.
  312. if (step.index == 1) {
  313. out << ",";
  314. }
  315. out << ")";
  316. break;
  317. }
  318. steps.push_back(step.Next());
  319. steps.push_back(
  320. {.node_id = GetTypeAllowBuiltinTypes(refs[step.index])});
  321. break;
  322. }
  323. case SemanticsNodeKind::AddressOf:
  324. case SemanticsNodeKind::Assign:
  325. case SemanticsNodeKind::BinaryOperatorAdd:
  326. case SemanticsNodeKind::BindName:
  327. case SemanticsNodeKind::BlockArg:
  328. case SemanticsNodeKind::BoolLiteral:
  329. case SemanticsNodeKind::Branch:
  330. case SemanticsNodeKind::BranchIf:
  331. case SemanticsNodeKind::BranchWithArg:
  332. case SemanticsNodeKind::Builtin:
  333. case SemanticsNodeKind::Call:
  334. case SemanticsNodeKind::Dereference:
  335. case SemanticsNodeKind::CrossReference:
  336. case SemanticsNodeKind::FunctionDeclaration:
  337. case SemanticsNodeKind::Index:
  338. case SemanticsNodeKind::IntegerLiteral:
  339. case SemanticsNodeKind::Namespace:
  340. case SemanticsNodeKind::RealLiteral:
  341. case SemanticsNodeKind::Return:
  342. case SemanticsNodeKind::ReturnExpression:
  343. case SemanticsNodeKind::StringLiteral:
  344. case SemanticsNodeKind::StructMemberAccess:
  345. case SemanticsNodeKind::StructValue:
  346. case SemanticsNodeKind::StubReference:
  347. case SemanticsNodeKind::TupleValue:
  348. case SemanticsNodeKind::UnaryOperatorNot:
  349. case SemanticsNodeKind::VarStorage:
  350. // We don't need to handle stringification for nodes that don't show up
  351. // in errors, but make it clear what's going on so that it's clearer
  352. // when stringification is needed.
  353. out << "<cannot stringify " << step.node_id << ">";
  354. break;
  355. case SemanticsNodeKind::Invalid:
  356. llvm_unreachable("SemanticsNodeKind::Invalid is never used.");
  357. }
  358. }
  359. // For `{}` or any tuple type, we've printed a non-type expression, so add a
  360. // conversion to type `type` if it's not implied by the context.
  361. if (!in_type_context) {
  362. auto outer_node = GetNode(outer_node_id);
  363. if (outer_node.kind() == SemanticsNodeKind::TupleType ||
  364. (outer_node.kind() == SemanticsNodeKind::StructType &&
  365. GetNodeBlock(outer_node.GetAsStructType()).empty())) {
  366. out << " as type";
  367. }
  368. }
  369. return str;
  370. }
  371. auto GetSemanticsExpressionCategory(const SemanticsIR& semantics_ir,
  372. SemanticsNodeId node_id)
  373. -> SemanticsExpressionCategory {
  374. const SemanticsIR* ir = &semantics_ir;
  375. while (true) {
  376. auto node = ir->GetNode(node_id);
  377. switch (node.kind()) {
  378. case SemanticsNodeKind::Invalid:
  379. case SemanticsNodeKind::Assign:
  380. case SemanticsNodeKind::Branch:
  381. case SemanticsNodeKind::BranchIf:
  382. case SemanticsNodeKind::BranchWithArg:
  383. case SemanticsNodeKind::FunctionDeclaration:
  384. case SemanticsNodeKind::Namespace:
  385. case SemanticsNodeKind::Return:
  386. case SemanticsNodeKind::ReturnExpression:
  387. case SemanticsNodeKind::StructTypeField:
  388. return SemanticsExpressionCategory::NotExpression;
  389. case SemanticsNodeKind::CrossReference: {
  390. auto [xref_id, xref_node_id] = node.GetAsCrossReference();
  391. ir = &semantics_ir.GetCrossReferenceIR(xref_id);
  392. node_id = xref_node_id;
  393. continue;
  394. }
  395. case SemanticsNodeKind::Call:
  396. // TODO: This should eventually be Initializing.
  397. return SemanticsExpressionCategory::Value;
  398. case SemanticsNodeKind::BindName: {
  399. auto [name_id, value_id] = node.GetAsBindName();
  400. node_id = value_id;
  401. continue;
  402. }
  403. case SemanticsNodeKind::AddressOf:
  404. case SemanticsNodeKind::BinaryOperatorAdd:
  405. case SemanticsNodeKind::BlockArg:
  406. case SemanticsNodeKind::BoolLiteral:
  407. case SemanticsNodeKind::Builtin:
  408. case SemanticsNodeKind::ConstType:
  409. case SemanticsNodeKind::IntegerLiteral:
  410. case SemanticsNodeKind::PointerType:
  411. case SemanticsNodeKind::RealLiteral:
  412. case SemanticsNodeKind::StringLiteral:
  413. case SemanticsNodeKind::StructType:
  414. case SemanticsNodeKind::TupleType:
  415. case SemanticsNodeKind::UnaryOperatorNot:
  416. return SemanticsExpressionCategory::Value;
  417. case SemanticsNodeKind::StructMemberAccess: {
  418. auto [base_id, member_index] = node.GetAsStructMemberAccess();
  419. node_id = base_id;
  420. continue;
  421. }
  422. case SemanticsNodeKind::Index: {
  423. auto [base_id, index_id] = node.GetAsIndex();
  424. node_id = base_id;
  425. continue;
  426. }
  427. case SemanticsNodeKind::StubReference: {
  428. node_id = node.GetAsStubReference();
  429. continue;
  430. }
  431. case SemanticsNodeKind::StructValue:
  432. case SemanticsNodeKind::TupleValue:
  433. // TODO: Eventually these will depend on the context in which the value
  434. // is used, and could be either Value or Initializing. We may want
  435. // different node kinds for a struct/tuple initializer versus a
  436. // struct/tuple value construction.
  437. return SemanticsExpressionCategory::Value;
  438. case SemanticsNodeKind::Dereference:
  439. case SemanticsNodeKind::VarStorage:
  440. return SemanticsExpressionCategory::DurableReference;
  441. }
  442. }
  443. }
  444. } // namespace Carbon