semantics_node.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. #ifndef CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_H_
  5. #define CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_H_
  6. #include <cstdint>
  7. #include "common/check.h"
  8. #include "common/ostream.h"
  9. #include "toolchain/parser/parse_tree.h"
  10. #include "toolchain/semantics/semantics_builtin_kind.h"
  11. #include "toolchain/semantics/semantics_node_kind.h"
  12. namespace Carbon {
  13. // The ID of a node.
  14. struct SemanticsNodeId : public IndexBase {
  15. // An explicitly invalid node ID.
  16. static const SemanticsNodeId Invalid;
  17. // Builtin node IDs.
  18. #define CARBON_SEMANTICS_BUILTIN_KIND_NAME(Name) \
  19. static const SemanticsNodeId Builtin##Name;
  20. #include "toolchain/semantics/semantics_builtin_kind.def"
  21. using IndexBase::IndexBase;
  22. auto Print(llvm::raw_ostream& out) const -> void {
  23. out << "node";
  24. if (!is_valid()) {
  25. IndexBase::Print(out);
  26. } else if (index < SemanticsBuiltinKind::ValidCount) {
  27. out << SemanticsBuiltinKind::FromInt(index);
  28. } else {
  29. // Use the `+` as a small reminder that this is a delta, rather than an
  30. // absolute index.
  31. out << "+" << index - SemanticsBuiltinKind::ValidCount;
  32. }
  33. }
  34. };
  35. constexpr SemanticsNodeId SemanticsNodeId::Invalid =
  36. SemanticsNodeId(SemanticsNodeId::InvalidIndex);
  37. // Uses the cross-reference node ID for a builtin. This relies on SemanticsIR
  38. // guarantees for builtin cross-reference placement.
  39. #define CARBON_SEMANTICS_BUILTIN_KIND_NAME(Name) \
  40. constexpr SemanticsNodeId SemanticsNodeId::Builtin##Name = \
  41. SemanticsNodeId(SemanticsBuiltinKind::Name.AsInt());
  42. #include "toolchain/semantics/semantics_builtin_kind.def"
  43. // The ID of a function.
  44. struct SemanticsFunctionId : public IndexBase {
  45. using IndexBase::IndexBase;
  46. auto Print(llvm::raw_ostream& out) const -> void {
  47. out << "function";
  48. IndexBase::Print(out);
  49. }
  50. };
  51. // The ID of a cross-referenced IR.
  52. struct SemanticsCrossReferenceIRId : public IndexBase {
  53. using IndexBase::IndexBase;
  54. auto Print(llvm::raw_ostream& out) const -> void {
  55. out << "ir";
  56. IndexBase::Print(out);
  57. }
  58. };
  59. // A boolean value.
  60. struct SemanticsBoolValue : public IndexBase {
  61. static const SemanticsBoolValue False;
  62. static const SemanticsBoolValue True;
  63. using IndexBase::IndexBase;
  64. auto Print(llvm::raw_ostream& out) const -> void {
  65. switch (index) {
  66. case 0:
  67. out << "false";
  68. break;
  69. case 1:
  70. out << "true";
  71. break;
  72. default:
  73. CARBON_FATAL() << "Invalid bool value " << index;
  74. }
  75. }
  76. };
  77. constexpr SemanticsBoolValue SemanticsBoolValue::False = SemanticsBoolValue(0);
  78. constexpr SemanticsBoolValue SemanticsBoolValue::True = SemanticsBoolValue(1);
  79. // The ID of an integer literal.
  80. struct SemanticsIntegerLiteralId : public IndexBase {
  81. using IndexBase::IndexBase;
  82. auto Print(llvm::raw_ostream& out) const -> void {
  83. out << "int";
  84. IndexBase::Print(out);
  85. }
  86. };
  87. // The ID of a node block.
  88. struct SemanticsNodeBlockId : public IndexBase {
  89. // All SemanticsIR instances must provide the 0th node block as empty.
  90. static const SemanticsNodeBlockId Empty;
  91. // An explicitly invalid ID.
  92. static const SemanticsNodeBlockId Invalid;
  93. using IndexBase::IndexBase;
  94. auto Print(llvm::raw_ostream& out) const -> void {
  95. out << "block";
  96. IndexBase::Print(out);
  97. }
  98. };
  99. constexpr SemanticsNodeBlockId SemanticsNodeBlockId::Empty =
  100. SemanticsNodeBlockId(0);
  101. constexpr SemanticsNodeBlockId SemanticsNodeBlockId::Invalid =
  102. SemanticsNodeBlockId(SemanticsNodeBlockId::InvalidIndex);
  103. // The ID of a real literal.
  104. struct SemanticsRealLiteralId : public IndexBase {
  105. using IndexBase::IndexBase;
  106. auto Print(llvm::raw_ostream& out) const -> void {
  107. out << "real";
  108. IndexBase::Print(out);
  109. }
  110. };
  111. // The ID of a string.
  112. struct SemanticsStringId : public IndexBase {
  113. using IndexBase::IndexBase;
  114. auto Print(llvm::raw_ostream& out) const -> void {
  115. out << "str";
  116. IndexBase::Print(out);
  117. }
  118. };
  119. // The ID of a node block.
  120. struct SemanticsTypeId : public IndexBase {
  121. // The builtin TypeType.
  122. static const SemanticsTypeId TypeType;
  123. // The builtin InvalidType.
  124. static const SemanticsTypeId InvalidType;
  125. // An explicitly invalid ID.
  126. static const SemanticsTypeId Invalid;
  127. using IndexBase::IndexBase;
  128. auto Print(llvm::raw_ostream& out) const -> void {
  129. out << "type";
  130. if (index == TypeType.index) {
  131. out << "TypeType";
  132. } else if (index == InvalidType.index) {
  133. out << "InvalidType";
  134. } else {
  135. IndexBase::Print(out);
  136. }
  137. }
  138. };
  139. constexpr SemanticsTypeId SemanticsTypeId::TypeType =
  140. SemanticsTypeId(SemanticsTypeId::InvalidIndex - 2);
  141. constexpr SemanticsTypeId SemanticsTypeId::InvalidType =
  142. SemanticsTypeId(SemanticsTypeId::InvalidIndex - 1);
  143. constexpr SemanticsTypeId SemanticsTypeId::Invalid =
  144. SemanticsTypeId(SemanticsTypeId::InvalidIndex);
  145. // An index for member access.
  146. struct SemanticsMemberIndex : public IndexBase {
  147. using IndexBase::IndexBase;
  148. auto Print(llvm::raw_ostream& out) const -> void {
  149. out << "member";
  150. IndexBase::Print(out);
  151. }
  152. };
  153. // The standard structure for SemanticsNode. This is trying to provide a minimal
  154. // amount of information for a node:
  155. //
  156. // - parse_node for error placement.
  157. // - kind for run-time logic when the input Kind is unknown.
  158. // - type_id for quick type checking.
  159. // - Up to two Kind-specific members.
  160. //
  161. // For each Kind in SemanticsNodeKind, a typical flow looks like:
  162. //
  163. // - Create a `SemanticsNode` using `SemanticsNode::Kind::Make()`
  164. // - Access cross-Kind members using `node.type_id()` and similar.
  165. // - Access Kind-specific members using `node.GetAsKind()`, which depending on
  166. // the number of members will return one of NoArgs, a single value, or a
  167. // `std::pair` of values.
  168. // - Using the wrong `node.GetAsKind()` is a programming error, and should
  169. // CHECK-fail in debug modes (opt may too, but it's not an API guarantee).
  170. //
  171. // Internally, each Kind uses the `Factory*` types to provide a boilerplate
  172. // `Make` and `Get` methods.
  173. class SemanticsNode {
  174. public:
  175. struct NoArgs {};
  176. // Factory base classes are private, then used for public classes. This class
  177. // has two public and two private sections to prevent accidents.
  178. private:
  179. // Factory templates need to use the raw enum instead of the class wrapper.
  180. using KindTemplateEnum = Internal::SemanticsNodeKindRawEnum;
  181. // Provides Make and Get to support 0, 1, or 2 arguments for a SemanticsNode.
  182. // These are protected so that child factories can opt in to what pieces they
  183. // want to use.
  184. template <KindTemplateEnum Kind, typename... ArgTypes>
  185. class FactoryBase {
  186. protected:
  187. static auto Make(ParseTree::Node parse_node, SemanticsTypeId type_id,
  188. ArgTypes... arg_ids) -> SemanticsNode {
  189. return SemanticsNode(parse_node, SemanticsNodeKind::Create(Kind), type_id,
  190. arg_ids.index...);
  191. }
  192. static auto Get(SemanticsNode node) {
  193. struct Unused {};
  194. return GetImpl<ArgTypes..., Unused>(node);
  195. }
  196. private:
  197. // GetImpl handles the different return types based on ArgTypes.
  198. template <typename Arg0Type, typename Arg1Type, typename>
  199. static auto GetImpl(SemanticsNode node) -> std::pair<Arg0Type, Arg1Type> {
  200. CARBON_CHECK(node.kind() == Kind);
  201. return {Arg0Type(node.arg0_), Arg1Type(node.arg1_)};
  202. }
  203. template <typename Arg0Type, typename>
  204. static auto GetImpl(SemanticsNode node) -> Arg0Type {
  205. CARBON_CHECK(node.kind() == Kind);
  206. return Arg0Type(node.arg0_);
  207. }
  208. template <typename>
  209. static auto GetImpl(SemanticsNode node) -> NoArgs {
  210. CARBON_CHECK(node.kind() == Kind);
  211. return NoArgs();
  212. }
  213. };
  214. // Provide Get along with a Make that requires a type.
  215. template <KindTemplateEnum Kind, typename... ArgTypes>
  216. class Factory : public FactoryBase<Kind, ArgTypes...> {
  217. public:
  218. using FactoryBase<Kind, ArgTypes...>::Make;
  219. using FactoryBase<Kind, ArgTypes...>::Get;
  220. };
  221. // Provides Get along with a Make that assumes a non-changing type.
  222. template <KindTemplateEnum Kind, typename... ArgTypes>
  223. class FactoryNoType : public FactoryBase<Kind, ArgTypes...> {
  224. public:
  225. static auto Make(ParseTree::Node parse_node, ArgTypes... args) {
  226. return FactoryBase<Kind, ArgTypes...>::Make(
  227. parse_node, SemanticsTypeId::Invalid, args...);
  228. }
  229. using FactoryBase<Kind, ArgTypes...>::Get;
  230. };
  231. public:
  232. // Invalid is in the SemanticsNodeKind enum, but should never be used.
  233. class Invalid {
  234. public:
  235. static auto Get(SemanticsNode /*node*/) -> SemanticsNode::NoArgs {
  236. CARBON_FATAL() << "Invalid access";
  237. }
  238. };
  239. using Assign = SemanticsNode::Factory<SemanticsNodeKind::Assign,
  240. SemanticsNodeId /*lhs_id*/,
  241. SemanticsNodeId /*rhs_id*/>;
  242. using BinaryOperatorAdd =
  243. SemanticsNode::Factory<SemanticsNodeKind::BinaryOperatorAdd,
  244. SemanticsNodeId /*lhs_id*/,
  245. SemanticsNodeId /*rhs_id*/>;
  246. using BindName = SemanticsNode::Factory<SemanticsNodeKind::BindName,
  247. SemanticsStringId /*name_id*/,
  248. SemanticsNodeId /*node_id*/>;
  249. using BlockArg =
  250. Factory<SemanticsNodeKind::BlockArg, SemanticsNodeBlockId /*block_id*/>;
  251. using BoolLiteral =
  252. Factory<SemanticsNodeKind::BoolLiteral, SemanticsBoolValue /*value*/>;
  253. using Branch = FactoryNoType<SemanticsNodeKind::Branch,
  254. SemanticsNodeBlockId /*target_id*/>;
  255. using BranchIf = FactoryNoType<SemanticsNodeKind::BranchIf,
  256. SemanticsNodeBlockId /*target_id*/,
  257. SemanticsNodeId /*cond_id*/>;
  258. using BranchWithArg = FactoryNoType<SemanticsNodeKind::BranchWithArg,
  259. SemanticsNodeBlockId /*target_id*/,
  260. SemanticsNodeId /*arg*/>;
  261. class Builtin {
  262. public:
  263. static auto Make(SemanticsBuiltinKind builtin_kind, SemanticsTypeId type_id)
  264. -> SemanticsNode {
  265. // Builtins won't have a ParseTree node associated, so we provide the
  266. // default invalid one.
  267. // This can't use the standard Make function because of the `AsInt()` cast
  268. // instead of `.index`.
  269. return SemanticsNode(ParseTree::Node::Invalid, SemanticsNodeKind::Builtin,
  270. type_id, builtin_kind.AsInt());
  271. }
  272. static auto Get(SemanticsNode node) -> SemanticsBuiltinKind {
  273. return SemanticsBuiltinKind::FromInt(node.arg0_);
  274. }
  275. };
  276. using Call =
  277. Factory<SemanticsNodeKind::Call, SemanticsNodeBlockId /*refs_id*/,
  278. SemanticsFunctionId /*function_id*/>;
  279. using CodeBlock = FactoryNoType<SemanticsNodeKind::CodeBlock,
  280. SemanticsNodeBlockId /*node_block_id*/>;
  281. class CrossReference
  282. : public FactoryBase<SemanticsNodeKind::CrossReference,
  283. SemanticsCrossReferenceIRId /*ir_id*/,
  284. SemanticsNodeId /*node_id*/> {
  285. public:
  286. static auto Make(SemanticsTypeId type_id, SemanticsCrossReferenceIRId ir_id,
  287. SemanticsNodeId node_id) -> SemanticsNode {
  288. // A node's parse tree node must refer to a node in the current parse
  289. // tree. This cannot use the cross-referenced node's parse tree node
  290. // because it will be in a different parse tree.
  291. return FactoryBase::Make(ParseTree::Node::Invalid, type_id, ir_id,
  292. node_id);
  293. }
  294. using FactoryBase::Get;
  295. };
  296. using FunctionDeclaration =
  297. FactoryNoType<SemanticsNodeKind::FunctionDeclaration,
  298. SemanticsFunctionId /*function_id*/>;
  299. using IntegerLiteral = Factory<SemanticsNodeKind::IntegerLiteral,
  300. SemanticsIntegerLiteralId /*integer_id*/>;
  301. using RealLiteral = Factory<SemanticsNodeKind::RealLiteral,
  302. SemanticsRealLiteralId /*real_id*/>;
  303. using Return = FactoryNoType<SemanticsNodeKind::Return>;
  304. using ReturnExpression =
  305. Factory<SemanticsNodeKind::ReturnExpression, SemanticsNodeId /*expr_id*/>;
  306. using StringLiteral = Factory<SemanticsNodeKind::StringLiteral,
  307. SemanticsStringId /*string_id*/>;
  308. using StructMemberAccess = Factory<SemanticsNodeKind::StructMemberAccess,
  309. SemanticsNodeId /*struct_id*/,
  310. SemanticsMemberIndex /*ref_index*/>;
  311. using StructType =
  312. Factory<SemanticsNodeKind::StructType, SemanticsNodeBlockId /*refs_id*/>;
  313. using StructTypeField = Factory<SemanticsNodeKind::StructTypeField,
  314. SemanticsStringId /*name_id*/>;
  315. using StructValue =
  316. Factory<SemanticsNodeKind::StructValue, SemanticsNodeBlockId /*refs_id*/>;
  317. using StubReference =
  318. Factory<SemanticsNodeKind::StubReference, SemanticsNodeId /*node_id*/>;
  319. using UnaryOperatorNot = Factory<SemanticsNodeKind::UnaryOperatorNot,
  320. SemanticsNodeId /*operand_id*/>;
  321. using VarStorage = Factory<SemanticsNodeKind::VarStorage>;
  322. SemanticsNode()
  323. : SemanticsNode(ParseTree::Node::Invalid, SemanticsNodeKind::Invalid,
  324. SemanticsTypeId::Invalid) {}
  325. // Provide `node.GetAsKind()` as an instance method for all kinds, essentially
  326. // an alias for`SemanticsNode::Kind::Get(node)`.
  327. #define CARBON_SEMANTICS_NODE_KIND(Name) \
  328. auto GetAs##Name() const { return Name::Get(*this); }
  329. #include "toolchain/semantics/semantics_node_kind.def"
  330. auto parse_node() const -> ParseTree::Node { return parse_node_; }
  331. auto kind() const -> SemanticsNodeKind { return kind_; }
  332. auto type_id() const -> SemanticsTypeId { return type_id_; }
  333. auto Print(llvm::raw_ostream& out) const -> void;
  334. private:
  335. // Builtins have peculiar construction, so they are a friend rather than using
  336. // a factory base class.
  337. friend struct SemanticsNodeForBuiltin;
  338. explicit SemanticsNode(ParseTree::Node parse_node, SemanticsNodeKind kind,
  339. SemanticsTypeId type_id,
  340. int32_t arg0 = SemanticsNodeId::InvalidIndex,
  341. int32_t arg1 = SemanticsNodeId::InvalidIndex)
  342. : parse_node_(parse_node),
  343. kind_(kind),
  344. type_id_(type_id),
  345. arg0_(arg0),
  346. arg1_(arg1) {}
  347. ParseTree::Node parse_node_;
  348. SemanticsNodeKind kind_;
  349. SemanticsTypeId type_id_;
  350. // Use GetAsKind to access arg0 and arg1.
  351. int32_t arg0_;
  352. int32_t arg1_;
  353. };
  354. // TODO: This is currently 20 bytes because we sometimes have 2 arguments for a
  355. // pair of SemanticsNodes. However, SemanticsNodeKind is 1 byte; if args
  356. // were 3.5 bytes, we could potentially shrink SemanticsNode by 4 bytes. This
  357. // may be worth investigating further.
  358. static_assert(sizeof(SemanticsNode) == 20, "Unexpected SemanticsNode size");
  359. // Provides base support for use of Id types as DenseMap/DenseSet keys.
  360. // Instantiated below.
  361. template <typename Id>
  362. struct SemanticsIdMapInfo {
  363. static inline auto getEmptyKey() -> Id {
  364. return Id(llvm::DenseMapInfo<int32_t>::getEmptyKey());
  365. }
  366. static inline auto getTombstoneKey() -> Id {
  367. return Id(llvm::DenseMapInfo<int32_t>::getTombstoneKey());
  368. }
  369. static auto getHashValue(const Id& val) -> unsigned {
  370. return llvm::DenseMapInfo<int32_t>::getHashValue(val.index);
  371. }
  372. static auto isEqual(const Id& lhs, const Id& rhs) -> bool {
  373. return lhs == rhs;
  374. }
  375. };
  376. } // namespace Carbon
  377. // Support use of Id types as DenseMap/DenseSet keys.
  378. template <>
  379. struct llvm::DenseMapInfo<Carbon::SemanticsNodeBlockId>
  380. : public Carbon::SemanticsIdMapInfo<Carbon::SemanticsNodeBlockId> {};
  381. template <>
  382. struct llvm::DenseMapInfo<Carbon::SemanticsNodeId>
  383. : public Carbon::SemanticsIdMapInfo<Carbon::SemanticsNodeId> {};
  384. template <>
  385. struct llvm::DenseMapInfo<Carbon::SemanticsStringId>
  386. : public Carbon::SemanticsIdMapInfo<Carbon::SemanticsStringId> {};
  387. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_H_