typed_nodes.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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_PARSE_TYPED_NODES_H_
  5. #define CARBON_TOOLCHAIN_PARSE_TYPED_NODES_H_
  6. #include "toolchain/parse/node_ids.h"
  7. #include "toolchain/parse/node_kind.h"
  8. namespace Carbon::Parse {
  9. // Helpers for defining different kinds of parse nodes.
  10. // ----------------------------------------------------
  11. // A pair of a list item and its optional following comma.
  12. template <typename Element, typename Comma>
  13. struct ListItem {
  14. Element value;
  15. std::optional<Comma> comma;
  16. };
  17. // A list of items, parameterized by the kind of the elements and comma.
  18. template <typename Element, typename Comma>
  19. using CommaSeparatedList = llvm::SmallVector<ListItem<Element, Comma>>;
  20. // This class provides a shorthand for defining parse node kinds for leaf nodes.
  21. template <const NodeKind& KindT, NodeCategory Category = NodeCategory::None>
  22. struct LeafNode {
  23. static constexpr auto Kind = KindT.Define(Category);
  24. };
  25. // ----------------------------------------------------------------------------
  26. // Each node kind (in node_kind.def) should have a corresponding type defined
  27. // here which describes the expected child structure of that parse node.
  28. //
  29. // Each of these types should start with a `static constexpr Kind` member
  30. // initialized by calling `Define` on the corresponding `NodeKind`, and passing
  31. // in the `NodeCategory` of that kind. This will both associate the category
  32. // with the node kind and create the necessary kind object for the typed node.
  33. //
  34. // This should be followed by field declarations that describe the child nodes,
  35. // in order, that occur in the parse tree. The `Extract...` functions on the
  36. // parse tree use struct reflection on these fields to guide the extraction of
  37. // the child nodes from the tree into an object of this type with these fields
  38. // for convenient access.
  39. //
  40. // The types of these fields are special and describe the specific child node
  41. // structure of the parse node. Many of these types are defined in `node_ids.h`.
  42. //
  43. // Valid primitive types here are:
  44. // - `NodeId` to match any single child node
  45. // - `FooId` to require that child to have kind `NodeKind::Foo`
  46. // - `AnyCatId` to require that child to have a kind in category `Cat`
  47. // - `NodeIdOneOf<A, B>` to require the child to have kind `NodeKind::A` or
  48. // `NodeKind::B`
  49. // - `NodeIdNot<A>` to match any single child whose kind is not `NodeKind::A`
  50. //
  51. // There a few, restricted composite field types allowed that compose types in
  52. // various ways, where all of the `T`s and `U`s below are themselves valid field
  53. // types:
  54. // - `llvm::SmallVector<T>` to match any number of children matching `T`
  55. // - `std::optional<T>` to match 0 or 1 children matching `T`
  56. // - `std::tuple<T...>` to match children matching `T...`
  57. // - Any provided `Aggregate` type that is a simple aggregate type such as
  58. // `struct Aggregate { T x; U y; }`,
  59. // to match children with types `T` and `U`.
  60. // ----------------------------------------------------------------------------
  61. // Error nodes
  62. // -----------
  63. // An invalid parse. Used to balance the parse tree. This type is here only to
  64. // ensure we have a type for each parse node kind. This node kind always has an
  65. // error, so can never be extracted.
  66. using InvalidParse =
  67. LeafNode<NodeKind::InvalidParse, NodeCategory::Decl | NodeCategory::Expr>;
  68. // An invalid subtree. Always has an error so can never be extracted.
  69. using InvalidParseStart = LeafNode<NodeKind::InvalidParseStart>;
  70. struct InvalidParseSubtree {
  71. static constexpr auto Kind =
  72. NodeKind::InvalidParseSubtree.Define(NodeCategory::Decl);
  73. InvalidParseStartId start;
  74. llvm::SmallVector<NodeIdNot<InvalidParseStart>> extra;
  75. };
  76. // A placeholder node to be replaced; it will never exist in a valid parse tree.
  77. // Its token kind is not enforced even when valid.
  78. using Placeholder = LeafNode<NodeKind::Placeholder>;
  79. // File nodes
  80. // ----------
  81. // The start of the file.
  82. using FileStart = LeafNode<NodeKind::FileStart>;
  83. // The end of the file.
  84. using FileEnd = LeafNode<NodeKind::FileEnd>;
  85. // General-purpose nodes
  86. // ---------------------
  87. // An empty declaration, such as `;`.
  88. using EmptyDecl =
  89. LeafNode<NodeKind::EmptyDecl, NodeCategory::Decl | NodeCategory::Statement>;
  90. // A name in a non-expression context, such as a declaration.
  91. using IdentifierName =
  92. LeafNode<NodeKind::IdentifierName,
  93. NodeCategory::NameComponent | NodeCategory::MemberName>;
  94. // A name in an expression context.
  95. using IdentifierNameExpr =
  96. LeafNode<NodeKind::IdentifierNameExpr, NodeCategory::Expr>;
  97. // The `self` value and `Self` type identifier keywords. Typically of the form
  98. // `self: Self`.
  99. using SelfValueName = LeafNode<NodeKind::SelfValueName>;
  100. using SelfValueNameExpr =
  101. LeafNode<NodeKind::SelfValueNameExpr, NodeCategory::Expr>;
  102. using SelfTypeNameExpr =
  103. LeafNode<NodeKind::SelfTypeNameExpr, NodeCategory::Expr>;
  104. // The `base` value keyword, introduced by `base: B`. Typically referenced in
  105. // an expression, as in `x.base` or `{.base = ...}`, but can also be used as a
  106. // declared name, as in `{.base: partial B}`.
  107. using BaseName = LeafNode<NodeKind::BaseName, NodeCategory::MemberName>;
  108. // A qualified name: `A.B`.
  109. struct QualifiedName {
  110. static constexpr auto Kind =
  111. NodeKind::QualifiedName.Define(NodeCategory::NameComponent);
  112. // For now, this is either an IdentifierName or a QualifiedName.
  113. AnyNameComponentId lhs;
  114. // TODO: This will eventually need to support more general expressions, for
  115. // example `GenericType(type_args).ChildType(child_type_args).Name`.
  116. IdentifierNameId rhs;
  117. };
  118. // Library, package, import
  119. // ------------------------
  120. // The `package` keyword in an expression.
  121. using PackageExpr = LeafNode<NodeKind::PackageExpr, NodeCategory::Expr>;
  122. // The name of a package or library for `package`, `import`, and `library`.
  123. using PackageName = LeafNode<NodeKind::PackageName>;
  124. using LibraryName = LeafNode<NodeKind::LibraryName>;
  125. using DefaultLibrary = LeafNode<NodeKind::DefaultLibrary>;
  126. using PackageIntroducer = LeafNode<NodeKind::PackageIntroducer>;
  127. using PackageApi = LeafNode<NodeKind::PackageApi>;
  128. using PackageImpl = LeafNode<NodeKind::PackageImpl>;
  129. // `library` in `package` or `import`.
  130. struct LibrarySpecifier {
  131. static constexpr auto Kind = NodeKind::LibrarySpecifier.Define();
  132. NodeIdOneOf<LibraryName, DefaultLibrary> name;
  133. };
  134. // First line of the file, such as:
  135. // `package MyPackage library "MyLibrary" impl;`
  136. struct PackageDirective {
  137. static constexpr auto Kind =
  138. NodeKind::PackageDirective.Define(NodeCategory::Decl);
  139. PackageIntroducerId introducer;
  140. std::optional<PackageNameId> name;
  141. std::optional<LibrarySpecifierId> library;
  142. NodeIdOneOf<PackageApi, PackageImpl> api_or_impl;
  143. };
  144. // `import TheirPackage library "TheirLibrary";`
  145. using ImportIntroducer = LeafNode<NodeKind::ImportIntroducer>;
  146. struct ImportDirective {
  147. static constexpr auto Kind =
  148. NodeKind::ImportDirective.Define(NodeCategory::Decl);
  149. ImportIntroducerId introducer;
  150. std::optional<PackageNameId> name;
  151. std::optional<LibrarySpecifierId> library;
  152. };
  153. // `library` as directive.
  154. using LibraryIntroducer = LeafNode<NodeKind::LibraryIntroducer>;
  155. struct LibraryDirective {
  156. static constexpr auto Kind =
  157. NodeKind::LibraryDirective.Define(NodeCategory::Decl);
  158. LibraryIntroducerId introducer;
  159. NodeIdOneOf<LibraryName, DefaultLibrary> library_name;
  160. NodeIdOneOf<PackageApi, PackageImpl> api_or_impl;
  161. };
  162. // Namespace nodes
  163. // ---------------
  164. using NamespaceStart = LeafNode<NodeKind::NamespaceStart>;
  165. // A namespace: `namespace N;`.
  166. struct Namespace {
  167. static constexpr auto Kind = NodeKind::Namespace.Define(NodeCategory::Decl);
  168. NamespaceStartId introducer;
  169. llvm::SmallVector<AnyModifierId> modifiers;
  170. NodeIdOneOf<IdentifierName, QualifiedName> name;
  171. };
  172. // Pattern nodes
  173. // -------------
  174. // A pattern binding, such as `name: Type`.
  175. struct BindingPattern {
  176. static constexpr auto Kind =
  177. NodeKind::BindingPattern.Define(NodeCategory::Pattern);
  178. NodeIdOneOf<IdentifierName, SelfValueName> name;
  179. AnyExprId type;
  180. };
  181. // `name:! Type`
  182. struct GenericBindingPattern {
  183. static constexpr auto Kind =
  184. NodeKind::GenericBindingPattern.Define(NodeCategory::Pattern);
  185. NodeIdOneOf<IdentifierName, SelfValueName> name;
  186. AnyExprId type;
  187. };
  188. // An address-of binding: `addr self: Self*`.
  189. struct Address {
  190. static constexpr auto Kind = NodeKind::Address.Define(NodeCategory::Pattern);
  191. AnyPatternId inner;
  192. };
  193. // A template binding: `template T:! type`.
  194. struct Template {
  195. static constexpr auto Kind = NodeKind::Template.Define(NodeCategory::Pattern);
  196. // This is a GenericBindingPatternId in any valid program.
  197. // TODO: Should the parser enforce that?
  198. AnyPatternId inner;
  199. };
  200. using TuplePatternStart = LeafNode<NodeKind::TuplePatternStart>;
  201. using PatternListComma = LeafNode<NodeKind::PatternListComma>;
  202. // A parameter list or tuple pattern: `(a: i32, b: i32)`.
  203. struct TuplePattern {
  204. static constexpr auto Kind =
  205. NodeKind::TuplePattern.Define(NodeCategory::Pattern);
  206. TuplePatternStartId left_paren;
  207. CommaSeparatedList<AnyPatternId, PatternListCommaId> params;
  208. };
  209. using ImplicitParamListStart = LeafNode<NodeKind::ImplicitParamListStart>;
  210. // An implicit parameter list: `[T:! type, self: Self]`.
  211. struct ImplicitParamList {
  212. static constexpr auto Kind = NodeKind::ImplicitParamList.Define();
  213. ImplicitParamListStartId left_square;
  214. CommaSeparatedList<AnyPatternId, PatternListCommaId> params;
  215. };
  216. // Function nodes
  217. // --------------
  218. using FunctionIntroducer = LeafNode<NodeKind::FunctionIntroducer>;
  219. // A return type: `-> i32`.
  220. struct ReturnType {
  221. static constexpr auto Kind = NodeKind::ReturnType.Define();
  222. AnyExprId type;
  223. };
  224. // A function signature: `fn F() -> i32`.
  225. template <const NodeKind& KindT>
  226. struct FunctionSignature {
  227. static constexpr auto Kind = KindT.Define(NodeCategory::Decl);
  228. FunctionIntroducerId introducer;
  229. llvm::SmallVector<AnyModifierId> modifiers;
  230. // For now, this is either an IdentifierName or a QualifiedName.
  231. AnyNameComponentId name;
  232. std::optional<ImplicitParamListId> implicit_params;
  233. TuplePatternId params;
  234. std::optional<ReturnTypeId> return_type;
  235. };
  236. using FunctionDecl = FunctionSignature<NodeKind::FunctionDecl>;
  237. using FunctionDefinitionStart =
  238. FunctionSignature<NodeKind::FunctionDefinitionStart>;
  239. // A function definition: `fn F() -> i32 { ... }`.
  240. struct FunctionDefinition {
  241. static constexpr auto Kind =
  242. NodeKind::FunctionDefinition.Define(NodeCategory::Decl);
  243. FunctionDefinitionStartId signature;
  244. llvm::SmallVector<AnyStatementId> body;
  245. };
  246. // `let` nodes
  247. // -----------
  248. using LetIntroducer = LeafNode<NodeKind::LetIntroducer>;
  249. using LetInitializer = LeafNode<NodeKind::LetInitializer>;
  250. // A `let` declaration: `let a: i32 = 5;`.
  251. struct LetDecl {
  252. static constexpr auto Kind =
  253. NodeKind::LetDecl.Define(NodeCategory::Decl | NodeCategory::Statement);
  254. LetIntroducerId introducer;
  255. llvm::SmallVector<AnyModifierId> modifiers;
  256. AnyPatternId pattern;
  257. LetInitializerId equals;
  258. AnyExprId initializer;
  259. };
  260. // `var` nodes
  261. // -----------
  262. using VariableIntroducer = LeafNode<NodeKind::VariableIntroducer>;
  263. using ReturnedModifier = LeafNode<NodeKind::ReturnedModifier>;
  264. // The initializer part of a `var` declaration.
  265. struct VariableInitializer {
  266. static constexpr auto Kind = NodeKind::VariableInitializer.Define();
  267. AnyExprId value;
  268. };
  269. // A `var` declaration: `var a: i32;` or `var a: i32 = 5;`.
  270. struct VariableDecl {
  271. static constexpr auto Kind = NodeKind::VariableDecl.Define(
  272. NodeCategory::Decl | NodeCategory::Statement);
  273. VariableIntroducerId introducer;
  274. llvm::SmallVector<AnyModifierId> modifiers;
  275. std::optional<ReturnedModifierId> returned;
  276. AnyPatternId pattern;
  277. std::optional<VariableInitializerId> initializer;
  278. };
  279. // Statement nodes
  280. // ---------------
  281. using CodeBlockStart = LeafNode<NodeKind::CodeBlockStart>;
  282. // A code block: `{ statement; statement; ... }`.
  283. struct CodeBlock {
  284. static constexpr auto Kind = NodeKind::CodeBlock.Define();
  285. CodeBlockStartId left_brace;
  286. llvm::SmallVector<AnyStatementId> statements;
  287. };
  288. // An expression statement: `F(x);`.
  289. struct ExprStatement {
  290. static constexpr auto Kind =
  291. NodeKind::ExprStatement.Define(NodeCategory::Statement);
  292. AnyExprId expr;
  293. };
  294. using BreakStatementStart = LeafNode<NodeKind::BreakStatementStart>;
  295. // A break statement: `break;`.
  296. struct BreakStatement {
  297. static constexpr auto Kind =
  298. NodeKind::BreakStatement.Define(NodeCategory::Statement);
  299. BreakStatementStartId introducer;
  300. };
  301. using ContinueStatementStart = LeafNode<NodeKind::ContinueStatementStart>;
  302. // A continue statement: `continue;`.
  303. struct ContinueStatement {
  304. static constexpr auto Kind =
  305. NodeKind::ContinueStatement.Define(NodeCategory::Statement);
  306. ContinueStatementStartId introducer;
  307. };
  308. using ReturnStatementStart = LeafNode<NodeKind::ReturnStatementStart>;
  309. using ReturnVarModifier = LeafNode<NodeKind::ReturnVarModifier>;
  310. // A return statement: `return;` or `return expr;` or `return var;`.
  311. struct ReturnStatement {
  312. static constexpr auto Kind =
  313. NodeKind::ReturnStatement.Define(NodeCategory::Statement);
  314. ReturnStatementStartId introducer;
  315. std::optional<AnyExprId> expr;
  316. std::optional<ReturnVarModifierId> var;
  317. };
  318. using ForHeaderStart = LeafNode<NodeKind::ForHeaderStart>;
  319. // The `var ... in` portion of a `for` statement.
  320. struct ForIn {
  321. static constexpr auto Kind = NodeKind::ForIn.Define();
  322. VariableIntroducerId introducer;
  323. AnyPatternId pattern;
  324. };
  325. // The `for (var ... in ...)` portion of a `for` statement.
  326. struct ForHeader {
  327. static constexpr auto Kind = NodeKind::ForHeader.Define();
  328. ForHeaderStartId introducer;
  329. ForInId var;
  330. AnyExprId range;
  331. };
  332. // A complete `for (...) { ... }` statement.
  333. struct ForStatement {
  334. static constexpr auto Kind =
  335. NodeKind::ForStatement.Define(NodeCategory::Statement);
  336. ForHeaderId header;
  337. CodeBlockId body;
  338. };
  339. using IfConditionStart = LeafNode<NodeKind::IfConditionStart>;
  340. // The condition portion of an `if` statement: `(expr)`.
  341. struct IfCondition {
  342. static constexpr auto Kind = NodeKind::IfCondition.Define();
  343. IfConditionStartId left_paren;
  344. AnyExprId condition;
  345. };
  346. using IfStatementElse = LeafNode<NodeKind::IfStatementElse>;
  347. // An `if` statement: `if (expr) { ... } else { ... }`.
  348. struct IfStatement {
  349. static constexpr auto Kind =
  350. NodeKind::IfStatement.Define(NodeCategory::Statement);
  351. IfConditionId head;
  352. CodeBlockId then;
  353. struct Else {
  354. IfStatementElseId else_token;
  355. NodeIdOneOf<CodeBlock, IfStatement> body;
  356. };
  357. std::optional<Else> else_clause;
  358. };
  359. using WhileConditionStart = LeafNode<NodeKind::WhileConditionStart>;
  360. // The condition portion of a `while` statement: `(expr)`.
  361. struct WhileCondition {
  362. static constexpr auto Kind = NodeKind::WhileCondition.Define();
  363. WhileConditionStartId left_paren;
  364. AnyExprId condition;
  365. };
  366. // A `while` statement: `while (expr) { ... }`.
  367. struct WhileStatement {
  368. static constexpr auto Kind =
  369. NodeKind::WhileStatement.Define(NodeCategory::Statement);
  370. WhileConditionId head;
  371. CodeBlockId body;
  372. };
  373. // Expression nodes
  374. // ----------------
  375. using ArrayExprStart = LeafNode<NodeKind::ArrayExprStart, NodeCategory::Expr>;
  376. // The start of an array type, `[i32;`.
  377. //
  378. // TODO: Consider flattening this into `ArrayExpr`.
  379. struct ArrayExprSemi {
  380. static constexpr auto Kind = NodeKind::ArrayExprSemi.Define();
  381. ArrayExprStartId left_square;
  382. AnyExprId type;
  383. };
  384. // An array type, such as `[i32; 3]` or `[i32;]`.
  385. struct ArrayExpr {
  386. static constexpr auto Kind = NodeKind::ArrayExpr.Define(NodeCategory::Expr);
  387. ArrayExprSemiId start;
  388. std::optional<AnyExprId> bound;
  389. };
  390. // The opening portion of an indexing expression: `a[`.
  391. //
  392. // TODO: Consider flattening this into `IndexExpr`.
  393. struct IndexExprStart {
  394. static constexpr auto Kind = NodeKind::IndexExprStart.Define();
  395. AnyExprId sequence;
  396. };
  397. // An indexing expression, such as `a[1]`.
  398. struct IndexExpr {
  399. static constexpr auto Kind = NodeKind::IndexExpr.Define(NodeCategory::Expr);
  400. IndexExprStartId start;
  401. AnyExprId index;
  402. };
  403. using ExprOpenParen = LeafNode<NodeKind::ExprOpenParen>;
  404. // A parenthesized expression: `(a)`.
  405. struct ParenExpr {
  406. static constexpr auto Kind = NodeKind::ParenExpr.Define(NodeCategory::Expr);
  407. ExprOpenParenId left_paren;
  408. AnyExprId expr;
  409. };
  410. using TupleLiteralComma = LeafNode<NodeKind::TupleLiteralComma>;
  411. // A tuple literal: `()`, `(a, b, c)`, or `(a,)`.
  412. struct TupleLiteral {
  413. static constexpr auto Kind =
  414. NodeKind::TupleLiteral.Define(NodeCategory::Expr);
  415. ExprOpenParenId left_paren;
  416. CommaSeparatedList<AnyExprId, TupleLiteralCommaId> elements;
  417. };
  418. // The opening portion of a call expression: `F(`.
  419. //
  420. // TODO: Consider flattening this into `CallExpr`.
  421. struct CallExprStart {
  422. static constexpr auto Kind = NodeKind::CallExprStart.Define();
  423. AnyExprId callee;
  424. };
  425. using CallExprComma = LeafNode<NodeKind::CallExprComma>;
  426. // A call expression: `F(a, b, c)`.
  427. struct CallExpr {
  428. static constexpr auto Kind = NodeKind::CallExpr.Define(NodeCategory::Expr);
  429. CallExprStartId start;
  430. CommaSeparatedList<AnyExprId, CallExprCommaId> arguments;
  431. };
  432. // A simple member access expression: `a.b`.
  433. struct MemberAccessExpr {
  434. static constexpr auto Kind =
  435. NodeKind::MemberAccessExpr.Define(NodeCategory::Expr);
  436. AnyExprId lhs;
  437. AnyMemberNameId rhs;
  438. };
  439. // A simple indirect member access expression: `a->b`.
  440. struct PointerMemberAccessExpr {
  441. static constexpr auto Kind =
  442. NodeKind::PointerMemberAccessExpr.Define(NodeCategory::Expr);
  443. AnyExprId lhs;
  444. AnyMemberNameId rhs;
  445. };
  446. // A prefix operator expression.
  447. template <const NodeKind& KindT>
  448. struct PrefixOperator {
  449. static constexpr auto Kind = KindT.Define(NodeCategory::Expr);
  450. AnyExprId operand;
  451. };
  452. // An infix operator expression.
  453. template <const NodeKind& KindT>
  454. struct InfixOperator {
  455. static constexpr auto Kind = KindT.Define(NodeCategory::Expr);
  456. AnyExprId lhs;
  457. AnyExprId rhs;
  458. };
  459. // A postfix operator expression.
  460. template <const NodeKind& KindT>
  461. struct PostfixOperator {
  462. static constexpr auto Kind = KindT.Define(NodeCategory::Expr);
  463. AnyExprId operand;
  464. };
  465. // Literals, operators, and modifiers
  466. #define CARBON_PARSE_NODE_KIND(...)
  467. #define CARBON_PARSE_NODE_KIND_TOKEN_LITERAL(Name, ...) \
  468. using Name = LeafNode<NodeKind::Name, NodeCategory::Expr>;
  469. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name, ...) \
  470. using Name##Modifier = \
  471. LeafNode<NodeKind::Name##Modifier, NodeCategory::Modifier>;
  472. #define CARBON_PARSE_NODE_KIND_PREFIX_OPERATOR(Name, ...) \
  473. using PrefixOperator##Name = PrefixOperator<NodeKind::PrefixOperator##Name>;
  474. #define CARBON_PARSE_NODE_KIND_INFIX_OPERATOR(Name, ...) \
  475. using InfixOperator##Name = InfixOperator<NodeKind::InfixOperator##Name>;
  476. #define CARBON_PARSE_NODE_KIND_POSTFIX_OPERATOR(Name, ...) \
  477. using PostfixOperator##Name = \
  478. PostfixOperator<NodeKind::PostfixOperator##Name>;
  479. #include "toolchain/parse/node_kind.def"
  480. // The first operand of a short-circuiting infix operator: `a and` or `a or`.
  481. // The complete operator expression will be an InfixOperator with this as the
  482. // `lhs`.
  483. // TODO: Make this be a template if we ever need to write generic code to cover
  484. // both cases at once, say in check.
  485. struct ShortCircuitOperandAnd {
  486. static constexpr auto Kind = NodeKind::ShortCircuitOperandAnd.Define();
  487. AnyExprId operand;
  488. };
  489. struct ShortCircuitOperandOr {
  490. static constexpr auto Kind = NodeKind::ShortCircuitOperandOr.Define();
  491. AnyExprId operand;
  492. };
  493. struct ShortCircuitOperatorAnd {
  494. static constexpr auto Kind =
  495. NodeKind::ShortCircuitOperatorAnd.Define(NodeCategory::Expr);
  496. ShortCircuitOperandAndId lhs;
  497. AnyExprId rhs;
  498. };
  499. struct ShortCircuitOperatorOr {
  500. static constexpr auto Kind =
  501. NodeKind::ShortCircuitOperatorOr.Define(NodeCategory::Expr);
  502. ShortCircuitOperandOrId lhs;
  503. AnyExprId rhs;
  504. };
  505. // The `if` portion of an `if` expression: `if expr`.
  506. struct IfExprIf {
  507. static constexpr auto Kind = NodeKind::IfExprIf.Define();
  508. AnyExprId condition;
  509. };
  510. // The `then` portion of an `if` expression: `then expr`.
  511. struct IfExprThen {
  512. static constexpr auto Kind = NodeKind::IfExprThen.Define();
  513. AnyExprId result;
  514. };
  515. // A full `if` expression: `if expr then expr else expr`.
  516. struct IfExprElse {
  517. static constexpr auto Kind = NodeKind::IfExprElse.Define(NodeCategory::Expr);
  518. IfExprIfId start;
  519. IfExprThenId then;
  520. AnyExprId else_result;
  521. };
  522. // Struct literals and struct type literals
  523. // ----------------------------------------
  524. // `{`
  525. using StructLiteralOrStructTypeLiteralStart =
  526. LeafNode<NodeKind::StructLiteralOrStructTypeLiteralStart>;
  527. // `,`
  528. using StructComma = LeafNode<NodeKind::StructComma>;
  529. // `.a`
  530. struct StructFieldDesignator {
  531. static constexpr auto Kind = NodeKind::StructFieldDesignator.Define();
  532. NodeIdOneOf<IdentifierName, BaseName> name;
  533. };
  534. // `.a = 0`
  535. struct StructFieldValue {
  536. static constexpr auto Kind = NodeKind::StructFieldValue.Define();
  537. StructFieldDesignatorId designator;
  538. AnyExprId expr;
  539. };
  540. // `.a: i32`
  541. struct StructFieldType {
  542. static constexpr auto Kind = NodeKind::StructFieldType.Define();
  543. StructFieldDesignatorId designator;
  544. AnyExprId type_expr;
  545. };
  546. // Struct literals, such as `{.a = 0}`.
  547. struct StructLiteral {
  548. static constexpr auto Kind =
  549. NodeKind::StructLiteral.Define(NodeCategory::Expr);
  550. StructLiteralOrStructTypeLiteralStartId introducer;
  551. CommaSeparatedList<StructFieldValueId, StructCommaId> fields;
  552. };
  553. // Struct type literals, such as `{.a: i32}`.
  554. struct StructTypeLiteral {
  555. static constexpr auto Kind =
  556. NodeKind::StructTypeLiteral.Define(NodeCategory::Expr);
  557. StructLiteralOrStructTypeLiteralStartId introducer;
  558. CommaSeparatedList<StructFieldTypeId, StructCommaId> fields;
  559. };
  560. // `class` declarations and definitions
  561. // ------------------------------------
  562. // `class`
  563. using ClassIntroducer = LeafNode<NodeKind::ClassIntroducer>;
  564. // A class signature `class C`
  565. template <const NodeKind& KindT, NodeCategory Category>
  566. struct ClassSignature {
  567. static constexpr auto Kind = KindT.Define(Category);
  568. ClassIntroducerId introducer;
  569. llvm::SmallVector<AnyModifierId> modifiers;
  570. AnyNameComponentId name;
  571. std::optional<ImplicitParamListId> implicit_params;
  572. std::optional<TuplePatternId> params;
  573. };
  574. // `class C;`
  575. using ClassDecl = ClassSignature<NodeKind::ClassDecl, NodeCategory::Decl>;
  576. // `class C {`
  577. using ClassDefinitionStart =
  578. ClassSignature<NodeKind::ClassDefinitionStart, NodeCategory::None>;
  579. // `class C { ... }`
  580. struct ClassDefinition {
  581. static constexpr auto Kind =
  582. NodeKind::ClassDefinition.Define(NodeCategory::Decl);
  583. ClassDefinitionStartId signature;
  584. llvm::SmallVector<AnyDeclId> members;
  585. };
  586. // Base class declaration
  587. // ----------------------
  588. // `base`
  589. using BaseIntroducer = LeafNode<NodeKind::BaseIntroducer>;
  590. using BaseColon = LeafNode<NodeKind::BaseColon>;
  591. // `extend base: BaseClass;`
  592. struct BaseDecl {
  593. static constexpr auto Kind = NodeKind::BaseDecl.Define(NodeCategory::Decl);
  594. BaseIntroducerId introducer;
  595. llvm::SmallVector<AnyModifierId> modifiers;
  596. BaseColonId colon;
  597. AnyExprId base_class;
  598. };
  599. // Interface declarations and definitions
  600. // --------------------------------------
  601. // `interface`
  602. using InterfaceIntroducer = LeafNode<NodeKind::InterfaceIntroducer>;
  603. // `interface I`
  604. template <const NodeKind& KindT, NodeCategory Category>
  605. struct InterfaceSignature {
  606. static constexpr auto Kind = KindT.Define(Category);
  607. InterfaceIntroducerId introducer;
  608. llvm::SmallVector<AnyModifierId> modifiers;
  609. AnyNameComponentId name;
  610. std::optional<ImplicitParamListId> implicit_params;
  611. std::optional<TuplePatternId> params;
  612. };
  613. // `interface I;`
  614. using InterfaceDecl =
  615. InterfaceSignature<NodeKind::InterfaceDecl, NodeCategory::Decl>;
  616. // `interface I {`
  617. using InterfaceDefinitionStart =
  618. InterfaceSignature<NodeKind::InterfaceDefinitionStart, NodeCategory::None>;
  619. // `interface I { ... }`
  620. struct InterfaceDefinition {
  621. static constexpr auto Kind =
  622. NodeKind::InterfaceDefinition.Define(NodeCategory::Decl);
  623. InterfaceDefinitionStartId signature;
  624. llvm::SmallVector<AnyDeclId> members;
  625. };
  626. // `impl`...`as` declarations and definitions
  627. // ------------------------------------------
  628. // `impl`
  629. using ImplIntroducer = LeafNode<NodeKind::ImplIntroducer>;
  630. // `as`
  631. using ImplAs = LeafNode<NodeKind::ImplAs>;
  632. // `forall [...]`
  633. struct ImplForall {
  634. static constexpr auto Kind = NodeKind::ImplForall.Define();
  635. ImplicitParamListId params;
  636. };
  637. // `impl T as I`
  638. template <const NodeKind& KindT, NodeCategory Category>
  639. struct ImplSignature {
  640. static constexpr auto Kind = KindT.Define(Category);
  641. ImplIntroducerId introducer;
  642. llvm::SmallVector<AnyModifierId> modifiers;
  643. std::optional<ImplForallId> forall;
  644. std::optional<AnyExprId> type_expr;
  645. ImplAsId as;
  646. AnyExprId interface;
  647. };
  648. // `impl T as I;`
  649. using ImplDecl = ImplSignature<NodeKind::ImplDecl, NodeCategory::Decl>;
  650. // `impl T as I {`
  651. using ImplDefinitionStart =
  652. ImplSignature<NodeKind::ImplDefinitionStart, NodeCategory::None>;
  653. // `impl T as I { ... }`
  654. struct ImplDefinition {
  655. static constexpr auto Kind =
  656. NodeKind::ImplDefinition.Define(NodeCategory::Decl);
  657. ImplDefinitionStartId signature;
  658. llvm::SmallVector<AnyDeclId> members;
  659. };
  660. // Named constraint declarations and definitions
  661. // ---------------------------------------------
  662. // `constraint`
  663. using NamedConstraintIntroducer = LeafNode<NodeKind::NamedConstraintIntroducer>;
  664. // `constraint NC`
  665. template <const NodeKind& KindT, NodeCategory Category>
  666. struct NamedConstraintSignature {
  667. static constexpr auto Kind = KindT.Define(Category);
  668. NamedConstraintIntroducerId introducer;
  669. llvm::SmallVector<AnyModifierId> modifiers;
  670. AnyNameComponentId name;
  671. std::optional<ImplicitParamListId> implicit_params;
  672. std::optional<TuplePatternId> params;
  673. };
  674. // `constraint NC;`
  675. using NamedConstraintDecl =
  676. NamedConstraintSignature<NodeKind::NamedConstraintDecl, NodeCategory::Decl>;
  677. // `constraint NC {`
  678. using NamedConstraintDefinitionStart =
  679. NamedConstraintSignature<NodeKind::NamedConstraintDefinitionStart,
  680. NodeCategory::None>;
  681. // `constraint NC { ... }`
  682. struct NamedConstraintDefinition {
  683. static constexpr auto Kind =
  684. NodeKind::NamedConstraintDefinition.Define(NodeCategory::Decl);
  685. NamedConstraintDefinitionStartId signature;
  686. llvm::SmallVector<AnyDeclId> members;
  687. };
  688. // ---------------------------------------------------------------------------
  689. // A complete source file. Note that there is no corresponding parse node for
  690. // the file. The file is instead the complete contents of the parse tree.
  691. struct File {
  692. FileStartId start;
  693. llvm::SmallVector<AnyDeclId> decls;
  694. FileEndId end;
  695. };
  696. // Define `Foo` as the node type for the ID type `FooId`.
  697. #define CARBON_PARSE_NODE_KIND(KindName) \
  698. template <> \
  699. struct NodeForId<KindName##Id> { \
  700. using TypedNode = KindName; \
  701. };
  702. #include "toolchain/parse/node_kind.def"
  703. } // namespace Carbon::Parse
  704. #endif // CARBON_TOOLCHAIN_PARSE_TYPED_NODES_H_