semantics_node.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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 call.
  44. struct SemanticsCallId : public IndexBase {
  45. using IndexBase::IndexBase;
  46. auto Print(llvm::raw_ostream& out) const -> void {
  47. out << "call";
  48. IndexBase::Print(out);
  49. }
  50. };
  51. // The ID of a callable, such as a function.
  52. struct SemanticsCallableId : public IndexBase {
  53. using IndexBase::IndexBase;
  54. auto Print(llvm::raw_ostream& out) const -> void {
  55. out << "callable";
  56. IndexBase::Print(out);
  57. }
  58. };
  59. // The ID of a cross-referenced IR.
  60. struct SemanticsCrossReferenceIRId : public IndexBase {
  61. using IndexBase::IndexBase;
  62. auto Print(llvm::raw_ostream& out) const -> void {
  63. out << "ir";
  64. IndexBase::Print(out);
  65. }
  66. };
  67. // The ID of an integer literal.
  68. struct SemanticsIntegerLiteralId : public IndexBase {
  69. using IndexBase::IndexBase;
  70. auto Print(llvm::raw_ostream& out) const -> void {
  71. out << "int";
  72. IndexBase::Print(out);
  73. }
  74. };
  75. // The ID of a node block.
  76. struct SemanticsNodeBlockId : public IndexBase {
  77. // All SemanticsIR instances must provide the 0th node block as empty.
  78. static const SemanticsNodeBlockId Empty;
  79. // An explicitly invalid ID.
  80. static const SemanticsNodeBlockId Invalid;
  81. using IndexBase::IndexBase;
  82. auto Print(llvm::raw_ostream& out) const -> void {
  83. out << "block";
  84. IndexBase::Print(out);
  85. }
  86. };
  87. constexpr SemanticsNodeBlockId SemanticsNodeBlockId::Empty =
  88. SemanticsNodeBlockId(0);
  89. constexpr SemanticsNodeBlockId SemanticsNodeBlockId::Invalid =
  90. SemanticsNodeBlockId(SemanticsNodeBlockId::InvalidIndex);
  91. // The ID of a real literal.
  92. struct SemanticsRealLiteralId : public IndexBase {
  93. using IndexBase::IndexBase;
  94. auto Print(llvm::raw_ostream& out) const -> void {
  95. out << "real";
  96. IndexBase::Print(out);
  97. }
  98. };
  99. // The ID of a string.
  100. struct SemanticsStringId : public IndexBase {
  101. using IndexBase::IndexBase;
  102. auto Print(llvm::raw_ostream& out) const -> void {
  103. out << "str";
  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 = Factory<SemanticsNodeKind::Call, SemanticsCallId /*call_id*/,
  219. SemanticsCallableId /*callable_id*/>;
  220. using CodeBlock = FactoryPreTyped<SemanticsNodeKind::CodeBlock,
  221. SemanticsNodeId::InvalidIndex,
  222. SemanticsNodeBlockId /*node_block_id*/>;
  223. class CrossReference
  224. : public FactoryBase<SemanticsNodeKind::CrossReference,
  225. SemanticsCrossReferenceIRId /*ir_id*/,
  226. SemanticsNodeId /*node_id*/> {
  227. public:
  228. static auto Make(SemanticsNodeId type_id, SemanticsCrossReferenceIRId ir_id,
  229. SemanticsNodeId node_id) -> SemanticsNode {
  230. // A node's parse tree node must refer to a node in the current parse
  231. // tree. This cannot use the cross-referenced node's parse tree node
  232. // because it will be in a different parse tree.
  233. return FactoryBase::Make(ParseTree::Node::Invalid, type_id, ir_id,
  234. node_id);
  235. }
  236. using FactoryBase::Get;
  237. };
  238. using FunctionDeclaration = FactoryPreTyped<
  239. SemanticsNodeKind::FunctionDeclaration, SemanticsNodeId::InvalidIndex,
  240. SemanticsStringId /*name_id*/, SemanticsCallableId /*signature_id*/>;
  241. using FunctionDefinition = FactoryPreTyped<
  242. SemanticsNodeKind::FunctionDefinition, SemanticsNodeId::InvalidIndex,
  243. SemanticsNodeId /*decl_id*/, SemanticsNodeBlockId /*node_block_id*/>;
  244. using IntegerLiteral =
  245. FactoryPreTyped<SemanticsNodeKind::IntegerLiteral,
  246. SemanticsBuiltinKind::IntegerType.AsInt(),
  247. SemanticsIntegerLiteralId /*integer_id*/>;
  248. using RealLiteral =
  249. FactoryPreTyped<SemanticsNodeKind::RealLiteral,
  250. SemanticsBuiltinKind::FloatingPointType.AsInt(),
  251. SemanticsRealLiteralId /*real_id*/>;
  252. using Return =
  253. FactoryPreTyped<SemanticsNodeKind::Return, SemanticsNodeId::InvalidIndex>;
  254. using ReturnExpression =
  255. Factory<SemanticsNodeKind::ReturnExpression, SemanticsNodeId /*expr_id*/>;
  256. using StringLiteral =
  257. FactoryPreTyped<SemanticsNodeKind::StringLiteral,
  258. SemanticsBuiltinKind::StringType.AsInt(),
  259. SemanticsStringId /*string_id*/>;
  260. using StructType = FactoryPreTyped<
  261. SemanticsNodeKind::StructType, SemanticsBuiltinKind::TypeType.AsInt(),
  262. SemanticsNodeBlockId /*ir_id*/, SemanticsNodeBlockId /*refs_id*/>;
  263. using StructTypeField = Factory<SemanticsNodeKind::StructTypeField,
  264. SemanticsStringId /*name_id*/>;
  265. using StructValue =
  266. Factory<SemanticsNodeKind::StructValue, SemanticsNodeBlockId /*ir_id*/,
  267. SemanticsNodeBlockId /*refs_id*/>;
  268. using StubReference =
  269. Factory<SemanticsNodeKind::StubReference, SemanticsNodeId /*node_id*/>;
  270. using VarStorage = Factory<SemanticsNodeKind::VarStorage>;
  271. SemanticsNode()
  272. : SemanticsNode(ParseTree::Node::Invalid, SemanticsNodeKind::Invalid,
  273. SemanticsNodeId::Invalid) {}
  274. // Provide `node.GetAsKind()` as an instance method for all kinds, essentially
  275. // an alias for`SemanticsNode::Kind::Get(node)`.
  276. #define CARBON_SEMANTICS_NODE_KIND(Name) \
  277. auto GetAs##Name() const { return Name::Get(*this); }
  278. #include "toolchain/semantics/semantics_node_kind.def"
  279. auto parse_node() const -> ParseTree::Node { return parse_node_; }
  280. auto kind() const -> SemanticsNodeKind { return kind_; }
  281. auto type_id() const -> SemanticsNodeId { return type_id_; }
  282. auto Print(llvm::raw_ostream& out) const -> void;
  283. private:
  284. // Builtins have peculiar construction, so they are a friend rather than using
  285. // a factory base class.
  286. friend struct SemanticsNodeForBuiltin;
  287. explicit SemanticsNode(ParseTree::Node parse_node, SemanticsNodeKind kind,
  288. SemanticsNodeId type_id,
  289. int32_t arg0 = SemanticsNodeId::InvalidIndex,
  290. int32_t arg1 = SemanticsNodeId::InvalidIndex)
  291. : parse_node_(parse_node),
  292. kind_(kind),
  293. type_id_(type_id),
  294. arg0_(arg0),
  295. arg1_(arg1) {}
  296. ParseTree::Node parse_node_;
  297. SemanticsNodeKind kind_;
  298. SemanticsNodeId type_id_;
  299. // Use GetAsKind to access arg0 and arg1.
  300. int32_t arg0_;
  301. int32_t arg1_;
  302. };
  303. // TODO: This is currently 20 bytes because we sometimes have 2 arguments for a
  304. // pair of SemanticsNodes. However, SemanticsNodeKind is 1 byte; if args
  305. // were 3.5 bytes, we could potentially shrink SemanticsNode by 4 bytes. This
  306. // may be worth investigating further.
  307. static_assert(sizeof(SemanticsNode) == 20, "Unexpected SemanticsNode size");
  308. } // namespace Carbon
  309. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_H_