semantics_node.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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 callable, such as a function.
  44. struct SemanticsCallableId : public IndexBase {
  45. using IndexBase::IndexBase;
  46. auto Print(llvm::raw_ostream& out) const -> void {
  47. out << "callable";
  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. // The ID of an integer literal.
  60. struct SemanticsIntegerLiteralId : public IndexBase {
  61. using IndexBase::IndexBase;
  62. auto Print(llvm::raw_ostream& out) const -> void {
  63. out << "int";
  64. IndexBase::Print(out);
  65. }
  66. };
  67. // The ID of a node block.
  68. struct SemanticsNodeBlockId : public IndexBase {
  69. // All SemanticsIR instances must provide the 0th node block as empty.
  70. static const SemanticsNodeBlockId Empty;
  71. // An explicitly invalid ID.
  72. static const SemanticsNodeBlockId Invalid;
  73. using IndexBase::IndexBase;
  74. auto Print(llvm::raw_ostream& out) const -> void {
  75. out << "block";
  76. IndexBase::Print(out);
  77. }
  78. };
  79. constexpr SemanticsNodeBlockId SemanticsNodeBlockId::Empty =
  80. SemanticsNodeBlockId(0);
  81. constexpr SemanticsNodeBlockId SemanticsNodeBlockId::Invalid =
  82. SemanticsNodeBlockId(SemanticsNodeBlockId::InvalidIndex);
  83. // The ID of a real literal.
  84. struct SemanticsRealLiteralId : public IndexBase {
  85. using IndexBase::IndexBase;
  86. auto Print(llvm::raw_ostream& out) const -> void {
  87. out << "real";
  88. IndexBase::Print(out);
  89. }
  90. };
  91. // The ID of a string.
  92. struct SemanticsStringId : public IndexBase {
  93. using IndexBase::IndexBase;
  94. auto Print(llvm::raw_ostream& out) const -> void {
  95. out << "str";
  96. IndexBase::Print(out);
  97. }
  98. };
  99. // An index for member access.
  100. struct SemanticsMemberIndex : public IndexBase {
  101. using IndexBase::IndexBase;
  102. auto Print(llvm::raw_ostream& out) const -> void {
  103. out << "member";
  104. IndexBase::Print(out);
  105. }
  106. };
  107. // The standard structure for SemanticsNode. This is trying to provide a minimal
  108. // amount of information for a node:
  109. //
  110. // - parse_node for error placement.
  111. // - kind for run-time logic when the input Kind is unknown.
  112. // - type_id for quick type checking.
  113. // - Up to two Kind-specific members.
  114. //
  115. // For each Kind in SemanticsNodeKind, a typical flow looks like:
  116. //
  117. // - Create a `SemanticsNode` using `SemanticsNode::Kind::Make()`
  118. // - Access cross-Kind members using `node.type_id()` and similar.
  119. // - Access Kind-specific members using `node.GetAsKind()`, which depending on
  120. // the number of members will return one of NoArgs, a single value, or a
  121. // `std::pair` of values.
  122. // - Using the wrong `node.GetAsKind()` is a programming error, and should
  123. // CHECK-fail in debug modes (opt may too, but it's not an API guarantee).
  124. //
  125. // Internally, each Kind uses the `Factory*` types to provide a boilerplate
  126. // `Make` and `Get` methods.
  127. class SemanticsNode {
  128. public:
  129. struct NoArgs {};
  130. // Factory base classes are private, then used for public classes. This class
  131. // has two public and two private sections to prevent accidents.
  132. private:
  133. // Factory templates need to use the raw enum instead of the class wrapper.
  134. using KindTemplateEnum = Internal::SemanticsNodeKindRawEnum;
  135. // Provides Make and Get to support 0, 1, or 2 arguments for a SemanticsNode.
  136. // These are protected so that child factories can opt in to what pieces they
  137. // want to use.
  138. template <KindTemplateEnum Kind, typename... ArgTypes>
  139. class FactoryBase {
  140. protected:
  141. static auto Make(ParseTree::Node parse_node, SemanticsNodeId type_id,
  142. ArgTypes... arg_ids) -> SemanticsNode {
  143. return SemanticsNode(parse_node, SemanticsNodeKind::Create(Kind), type_id,
  144. arg_ids.index...);
  145. }
  146. static auto Get(SemanticsNode node) {
  147. struct Unused {};
  148. return GetImpl<ArgTypes..., Unused>(node);
  149. }
  150. private:
  151. // GetImpl handles the different return types based on ArgTypes.
  152. template <typename Arg0Type, typename Arg1Type, typename>
  153. static auto GetImpl(SemanticsNode node) -> std::pair<Arg0Type, Arg1Type> {
  154. CARBON_CHECK(node.kind() == Kind);
  155. return {Arg0Type(node.arg0_), Arg1Type(node.arg1_)};
  156. }
  157. template <typename Arg0Type, typename>
  158. static auto GetImpl(SemanticsNode node) -> Arg0Type {
  159. CARBON_CHECK(node.kind() == Kind);
  160. return Arg0Type(node.arg0_);
  161. }
  162. template <typename>
  163. static auto GetImpl(SemanticsNode node) -> NoArgs {
  164. CARBON_CHECK(node.kind() == Kind);
  165. return NoArgs();
  166. }
  167. };
  168. // Provide Get along with a Make that requires a type.
  169. template <KindTemplateEnum Kind, typename... ArgTypes>
  170. class Factory : public FactoryBase<Kind, ArgTypes...> {
  171. public:
  172. using FactoryBase<Kind, ArgTypes...>::Make;
  173. using FactoryBase<Kind, ArgTypes...>::Get;
  174. };
  175. // Provides Get along with a Make that assumes a non-changing type.
  176. template <KindTemplateEnum Kind, int32_t TypeIndex, typename... ArgTypes>
  177. class FactoryPreTyped : public FactoryBase<Kind, ArgTypes...> {
  178. public:
  179. static auto Make(ParseTree::Node parse_node, ArgTypes... args) {
  180. SemanticsNodeId type_id(TypeIndex);
  181. return FactoryBase<Kind, ArgTypes...>::Make(parse_node, type_id, args...);
  182. }
  183. using FactoryBase<Kind, ArgTypes...>::Get;
  184. };
  185. public:
  186. // Invalid is in the SemanticsNodeKind enum, but should never be used.
  187. class Invalid {
  188. public:
  189. static auto Get(SemanticsNode /*node*/) -> SemanticsNode::NoArgs {
  190. CARBON_FATAL() << "Invalid access";
  191. }
  192. };
  193. using Assign = SemanticsNode::Factory<SemanticsNodeKind::Assign,
  194. SemanticsNodeId /*lhs_id*/,
  195. SemanticsNodeId /*rhs_id*/>;
  196. using BinaryOperatorAdd =
  197. SemanticsNode::Factory<SemanticsNodeKind::BinaryOperatorAdd,
  198. SemanticsNodeId /*lhs_id*/,
  199. SemanticsNodeId /*rhs_id*/>;
  200. using BindName = SemanticsNode::Factory<SemanticsNodeKind::BindName,
  201. SemanticsStringId /*name_id*/,
  202. SemanticsNodeId /*node_id*/>;
  203. class Builtin {
  204. public:
  205. static auto Make(SemanticsBuiltinKind builtin_kind, SemanticsNodeId type_id)
  206. -> SemanticsNode {
  207. // Builtins won't have a ParseTree node associated, so we provide the
  208. // default invalid one.
  209. // This can't use the standard Make function because of the `AsInt()` cast
  210. // instead of `.index`.
  211. return SemanticsNode(ParseTree::Node::Invalid, SemanticsNodeKind::Builtin,
  212. type_id, builtin_kind.AsInt());
  213. }
  214. static auto Get(SemanticsNode node) -> SemanticsBuiltinKind {
  215. return SemanticsBuiltinKind::FromInt(node.arg0_);
  216. }
  217. };
  218. using Call =
  219. Factory<SemanticsNodeKind::Call, SemanticsNodeBlockId /*refs_id*/,
  220. SemanticsCallableId /*callable_id*/>;
  221. using CodeBlock = FactoryPreTyped<SemanticsNodeKind::CodeBlock,
  222. SemanticsNodeId::InvalidIndex,
  223. SemanticsNodeBlockId /*node_block_id*/>;
  224. class CrossReference
  225. : public FactoryBase<SemanticsNodeKind::CrossReference,
  226. SemanticsCrossReferenceIRId /*ir_id*/,
  227. SemanticsNodeId /*node_id*/> {
  228. public:
  229. static auto Make(SemanticsNodeId type_id, SemanticsCrossReferenceIRId ir_id,
  230. SemanticsNodeId node_id) -> SemanticsNode {
  231. // A node's parse tree node must refer to a node in the current parse
  232. // tree. This cannot use the cross-referenced node's parse tree node
  233. // because it will be in a different parse tree.
  234. return FactoryBase::Make(ParseTree::Node::Invalid, type_id, ir_id,
  235. node_id);
  236. }
  237. using FactoryBase::Get;
  238. };
  239. using FunctionDeclaration = FactoryPreTyped<
  240. SemanticsNodeKind::FunctionDeclaration, SemanticsNodeId::InvalidIndex,
  241. SemanticsStringId /*name_id*/, SemanticsCallableId /*signature_id*/>;
  242. using FunctionDefinition = FactoryPreTyped<
  243. SemanticsNodeKind::FunctionDefinition, SemanticsNodeId::InvalidIndex,
  244. SemanticsNodeId /*decl_id*/, SemanticsNodeBlockId /*node_block_id*/>;
  245. using IntegerLiteral =
  246. FactoryPreTyped<SemanticsNodeKind::IntegerLiteral,
  247. SemanticsBuiltinKind::IntegerType.AsInt(),
  248. SemanticsIntegerLiteralId /*integer_id*/>;
  249. using RealLiteral =
  250. FactoryPreTyped<SemanticsNodeKind::RealLiteral,
  251. SemanticsBuiltinKind::FloatingPointType.AsInt(),
  252. SemanticsRealLiteralId /*real_id*/>;
  253. using Return =
  254. FactoryPreTyped<SemanticsNodeKind::Return, SemanticsNodeId::InvalidIndex>;
  255. using ReturnExpression =
  256. Factory<SemanticsNodeKind::ReturnExpression, SemanticsNodeId /*expr_id*/>;
  257. using StringLiteral =
  258. FactoryPreTyped<SemanticsNodeKind::StringLiteral,
  259. SemanticsBuiltinKind::StringType.AsInt(),
  260. SemanticsStringId /*string_id*/>;
  261. using StructMemberAccess = Factory<SemanticsNodeKind::StructMemberAccess,
  262. SemanticsNodeId /*struct_id*/,
  263. SemanticsMemberIndex /*ref_index*/>;
  264. using StructType = FactoryPreTyped<SemanticsNodeKind::StructType,
  265. SemanticsBuiltinKind::TypeType.AsInt(),
  266. SemanticsNodeBlockId /*refs_id*/>;
  267. using StructTypeField = Factory<SemanticsNodeKind::StructTypeField,
  268. SemanticsStringId /*name_id*/>;
  269. using StructValue =
  270. Factory<SemanticsNodeKind::StructValue, SemanticsNodeBlockId /*refs_id*/>;
  271. using StubReference =
  272. Factory<SemanticsNodeKind::StubReference, SemanticsNodeId /*node_id*/>;
  273. using VarStorage = Factory<SemanticsNodeKind::VarStorage>;
  274. SemanticsNode()
  275. : SemanticsNode(ParseTree::Node::Invalid, SemanticsNodeKind::Invalid,
  276. SemanticsNodeId::Invalid) {}
  277. // Provide `node.GetAsKind()` as an instance method for all kinds, essentially
  278. // an alias for`SemanticsNode::Kind::Get(node)`.
  279. #define CARBON_SEMANTICS_NODE_KIND(Name) \
  280. auto GetAs##Name() const { return Name::Get(*this); }
  281. #include "toolchain/semantics/semantics_node_kind.def"
  282. auto parse_node() const -> ParseTree::Node { return parse_node_; }
  283. auto kind() const -> SemanticsNodeKind { return kind_; }
  284. auto type_id() const -> SemanticsNodeId { return type_id_; }
  285. auto Print(llvm::raw_ostream& out) const -> void;
  286. private:
  287. // Builtins have peculiar construction, so they are a friend rather than using
  288. // a factory base class.
  289. friend struct SemanticsNodeForBuiltin;
  290. explicit SemanticsNode(ParseTree::Node parse_node, SemanticsNodeKind kind,
  291. SemanticsNodeId type_id,
  292. int32_t arg0 = SemanticsNodeId::InvalidIndex,
  293. int32_t arg1 = SemanticsNodeId::InvalidIndex)
  294. : parse_node_(parse_node),
  295. kind_(kind),
  296. type_id_(type_id),
  297. arg0_(arg0),
  298. arg1_(arg1) {}
  299. ParseTree::Node parse_node_;
  300. SemanticsNodeKind kind_;
  301. SemanticsNodeId type_id_;
  302. // Use GetAsKind to access arg0 and arg1.
  303. int32_t arg0_;
  304. int32_t arg1_;
  305. };
  306. // TODO: This is currently 20 bytes because we sometimes have 2 arguments for a
  307. // pair of SemanticsNodes. However, SemanticsNodeKind is 1 byte; if args
  308. // were 3.5 bytes, we could potentially shrink SemanticsNode by 4 bytes. This
  309. // may be worth investigating further.
  310. static_assert(sizeof(SemanticsNode) == 20, "Unexpected SemanticsNode size");
  311. } // namespace Carbon
  312. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_H_