semantics_ir.cpp 18 KB

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