typed_nodes.h 30 KB

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