typed_nodes.h 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  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/lex/token_index.h"
  8. #include "toolchain/parse/node_ids.h"
  9. #include "toolchain/parse/node_kind.h"
  10. namespace Carbon::Parse {
  11. // Helpers for defining different kinds of parse nodes.
  12. // ----------------------------------------------------
  13. // A pair of a list item and its optional following comma.
  14. template <typename Element, typename Comma>
  15. struct ListItem {
  16. Element value;
  17. std::optional<Comma> comma;
  18. };
  19. // A list of items, parameterized by the kind of the elements and comma.
  20. template <typename Element, typename Comma>
  21. using CommaSeparatedList = llvm::SmallVector<ListItem<Element, Comma>>;
  22. // This class provides a shorthand for defining parse node kinds for leaf nodes.
  23. template <const NodeKind& KindT, typename TokenKind,
  24. NodeCategory::RawEnumType Category = NodeCategory::None>
  25. struct LeafNode {
  26. static constexpr auto Kind =
  27. KindT.Define({.category = Category, .child_count = 0});
  28. TokenKind token;
  29. };
  30. // ----------------------------------------------------------------------------
  31. // Each node kind (in node_kind.def) should have a corresponding type defined
  32. // here which describes the expected child structure of that parse node.
  33. //
  34. // Each of these types should start with a `static constexpr Kind` member
  35. // initialized by calling `Define` on the corresponding `NodeKind`, and passing
  36. // in the `NodeCategory` of that kind. This will both associate the category
  37. // with the node kind and create the necessary kind object for the typed node.
  38. //
  39. // This should be followed by field declarations that describe the child nodes,
  40. // in order, that occur in the parse tree. The `Extract...` functions on the
  41. // parse tree use struct reflection on these fields to guide the extraction of
  42. // the child nodes from the tree into an object of this type with these fields
  43. // for convenient access.
  44. //
  45. // The types of these fields are special and describe the specific child node
  46. // structure of the parse node. Many of these types are defined in `node_ids.h`.
  47. //
  48. // Valid primitive types here are:
  49. // - `NodeId` to match any single child node
  50. // - `FooId` to require that child to have kind `NodeKind::Foo`
  51. // - `AnyCatId` to require that child to have a kind in category `Cat`
  52. // - `NodeIdOneOf<A, B>` to require the child to have kind `NodeKind::A` or
  53. // `NodeKind::B`
  54. // - `NodeIdNot<A>` to match any single child whose kind is not `NodeKind::A`
  55. //
  56. // There a few, restricted composite field types allowed that compose types in
  57. // various ways, where all of the `T`s and `U`s below are themselves valid field
  58. // types:
  59. // - `llvm::SmallVector<T>` to match any number of children matching `T`
  60. // - `std::optional<T>` to match 0 or 1 children matching `T`
  61. // - `std::tuple<T...>` to match children matching `T...`
  62. // - Any provided `Aggregate` type that is a simple aggregate type such as
  63. // `struct Aggregate { T x; U y; }`,
  64. // to match children with types `T` and `U`.
  65. //
  66. // In addition to the fields describing the child nodes, each parse node should
  67. // also have exactly one field that describes the token corresponding to the
  68. // parse node itself. This field should have the name `token`. The type of the
  69. // field should be `Lex::*TokenIndex`, describing the kind of the token, such as
  70. // `Lex::SemiTokenIndex` for a `;` token. If the parse node can correspond to
  71. // any kind of token, `Lex::TokenIndex` can be used instead, but should only be
  72. // used when the node kind is either not used in a finished tree, such as
  73. // `Placeholder`, or is always invalid, such as `InvalidParse`. The location of
  74. // the field relative to the child nodes indicates the location within the
  75. // corresponding grammar production where the token appears.
  76. // ----------------------------------------------------------------------------
  77. // Error nodes
  78. // -----------
  79. // An invalid parse. Used to balance the parse tree. This type is here only to
  80. // ensure we have a type for each parse node kind. This node kind always has an
  81. // error, so can never be extracted.
  82. using InvalidParse = LeafNode<NodeKind::InvalidParse, Lex::TokenIndex,
  83. NodeCategory::Decl | NodeCategory::Expr>;
  84. // An invalid subtree. Always has an error so can never be extracted.
  85. using InvalidParseStart =
  86. LeafNode<NodeKind::InvalidParseStart, Lex::TokenIndex>;
  87. struct InvalidParseSubtree {
  88. static constexpr auto Kind = NodeKind::InvalidParseSubtree.Define(
  89. {.category = NodeCategory::Decl,
  90. .bracketed_by = InvalidParseStart::Kind});
  91. InvalidParseStartId start;
  92. llvm::SmallVector<NodeIdNot<InvalidParseStart>> extra;
  93. Lex::TokenIndex token;
  94. };
  95. // A placeholder node to be replaced; it will never exist in a valid parse tree.
  96. // Its token kind is not enforced even when valid.
  97. using Placeholder = LeafNode<NodeKind::Placeholder, Lex::TokenIndex>;
  98. // File nodes
  99. // ----------
  100. // The start of the file.
  101. using FileStart = LeafNode<NodeKind::FileStart, Lex::FileStartTokenIndex>;
  102. // The end of the file.
  103. using FileEnd = LeafNode<NodeKind::FileEnd, Lex::FileEndTokenIndex>;
  104. // General-purpose nodes
  105. // ---------------------
  106. // An empty declaration, such as `;`.
  107. using EmptyDecl = LeafNode<NodeKind::EmptyDecl, Lex::SemiTokenIndex,
  108. NodeCategory::Decl | NodeCategory::Statement>;
  109. // A name in a non-expression context, such as a declaration.
  110. using IdentifierName =
  111. LeafNode<NodeKind::IdentifierName, Lex::IdentifierTokenIndex,
  112. NodeCategory::MemberName>;
  113. // A name in an expression context.
  114. using IdentifierNameExpr =
  115. LeafNode<NodeKind::IdentifierNameExpr, Lex::IdentifierTokenIndex,
  116. NodeCategory::Expr>;
  117. // The `self` value and `Self` type identifier keywords. Typically of the form
  118. // `self: Self`.
  119. using SelfValueName =
  120. LeafNode<NodeKind::SelfValueName, Lex::SelfValueIdentifierTokenIndex>;
  121. using SelfValueNameExpr =
  122. LeafNode<NodeKind::SelfValueNameExpr, Lex::SelfValueIdentifierTokenIndex,
  123. NodeCategory::Expr>;
  124. using SelfTypeNameExpr =
  125. LeafNode<NodeKind::SelfTypeNameExpr, Lex::SelfTypeIdentifierTokenIndex,
  126. NodeCategory::Expr>;
  127. // The `base` value keyword, introduced by `base: B`. Typically referenced in
  128. // an expression, as in `x.base` or `{.base = ...}`, but can also be used as a
  129. // declared name, as in `{.base: partial B}`.
  130. using BaseName =
  131. LeafNode<NodeKind::BaseName, Lex::BaseTokenIndex, NodeCategory::MemberName>;
  132. // An unqualified name and optionally a following sequence of parameters.
  133. // For example, `A`, `A(n: i32)`, or `A[T:! type](n: T)`.
  134. struct NameAndParams {
  135. IdentifierNameId name;
  136. std::optional<ImplicitParamListId> implicit_params;
  137. std::optional<TuplePatternId> params;
  138. };
  139. // A name qualifier: `A.`, `A(T:! type).`, or `A[T:! type](N:! T).`.
  140. struct NameQualifier {
  141. static constexpr auto Kind =
  142. NodeKind::NameQualifier.Define({.bracketed_by = IdentifierName::Kind});
  143. NameAndParams name_and_params;
  144. Lex::PeriodTokenIndex token;
  145. };
  146. // A complete name in a declaration: `A.C(T:! type).F(n: i32)`.
  147. // Note that this includes the parameters of the entity itself.
  148. struct DeclName {
  149. llvm::SmallVector<NameQualifierId> qualifiers;
  150. NameAndParams name_and_params;
  151. };
  152. // Library, package, import, export
  153. // --------------------------------
  154. // The `package` keyword in an expression.
  155. using PackageExpr =
  156. LeafNode<NodeKind::PackageExpr, Lex::PackageTokenIndex, NodeCategory::Expr>;
  157. // The name of a package or library for `package`, `import`, and `library`.
  158. using PackageName = LeafNode<NodeKind::PackageName, Lex::IdentifierTokenIndex>;
  159. using LibraryName =
  160. LeafNode<NodeKind::LibraryName, Lex::StringLiteralTokenIndex>;
  161. using DefaultLibrary =
  162. LeafNode<NodeKind::DefaultLibrary, Lex::DefaultTokenIndex>;
  163. using PackageIntroducer =
  164. LeafNode<NodeKind::PackageIntroducer, Lex::PackageTokenIndex>;
  165. // `library` in `package` or `import`.
  166. struct LibrarySpecifier {
  167. static constexpr auto Kind =
  168. NodeKind::LibrarySpecifier.Define({.child_count = 1});
  169. Lex::LibraryTokenIndex token;
  170. NodeIdOneOf<LibraryName, DefaultLibrary> name;
  171. };
  172. // First line of the file, such as:
  173. // `impl package MyPackage library "MyLibrary";`
  174. struct PackageDecl {
  175. static constexpr auto Kind =
  176. NodeKind::PackageDecl.Define({.category = NodeCategory::Decl,
  177. .bracketed_by = PackageIntroducer::Kind});
  178. PackageIntroducerId introducer;
  179. llvm::SmallVector<AnyModifierId> modifiers;
  180. std::optional<PackageNameId> name;
  181. std::optional<LibrarySpecifierId> library;
  182. Lex::SemiTokenIndex token;
  183. };
  184. // `import TheirPackage library "TheirLibrary";`
  185. using ImportIntroducer =
  186. LeafNode<NodeKind::ImportIntroducer, Lex::ImportTokenIndex>;
  187. struct ImportDecl {
  188. static constexpr auto Kind = NodeKind::ImportDecl.Define(
  189. {.category = NodeCategory::Decl, .bracketed_by = ImportIntroducer::Kind});
  190. ImportIntroducerId introducer;
  191. llvm::SmallVector<AnyModifierId> modifiers;
  192. std::optional<PackageNameId> name;
  193. std::optional<LibrarySpecifierId> library;
  194. Lex::SemiTokenIndex token;
  195. };
  196. // `library` as declaration.
  197. using LibraryIntroducer =
  198. LeafNode<NodeKind::LibraryIntroducer, Lex::LibraryTokenIndex>;
  199. struct LibraryDecl {
  200. static constexpr auto Kind =
  201. NodeKind::LibraryDecl.Define({.category = NodeCategory::Decl,
  202. .bracketed_by = LibraryIntroducer::Kind});
  203. LibraryIntroducerId introducer;
  204. llvm::SmallVector<AnyModifierId> modifiers;
  205. NodeIdOneOf<LibraryName, DefaultLibrary> library_name;
  206. Lex::SemiTokenIndex token;
  207. };
  208. // `export` as a declaration.
  209. using ExportIntroducer =
  210. LeafNode<NodeKind::ExportIntroducer, Lex::ExportTokenIndex>;
  211. struct ExportDecl {
  212. static constexpr auto Kind = NodeKind::ExportDecl.Define(
  213. {.category = NodeCategory::Decl, .bracketed_by = ExportIntroducer::Kind});
  214. ExportIntroducerId introducer;
  215. llvm::SmallVector<AnyModifierId> modifiers;
  216. DeclName name;
  217. Lex::SemiTokenIndex token;
  218. };
  219. // Namespace nodes
  220. // ---------------
  221. using NamespaceStart =
  222. LeafNode<NodeKind::NamespaceStart, Lex::NamespaceTokenIndex>;
  223. // A namespace: `namespace N;`.
  224. struct Namespace {
  225. static constexpr auto Kind = NodeKind::Namespace.Define(
  226. {.category = NodeCategory::Decl, .bracketed_by = NamespaceStart::Kind});
  227. NamespaceStartId introducer;
  228. llvm::SmallVector<AnyModifierId> modifiers;
  229. DeclName name;
  230. Lex::SemiTokenIndex token;
  231. };
  232. // Pattern nodes
  233. // -------------
  234. // A pattern binding, such as `name: Type`.
  235. struct BindingPattern {
  236. static constexpr auto Kind = NodeKind::BindingPattern.Define(
  237. {.category = NodeCategory::Pattern, .child_count = 2});
  238. NodeIdOneOf<IdentifierName, SelfValueName> name;
  239. Lex::ColonTokenIndex token;
  240. AnyExprId type;
  241. };
  242. // `name:! Type`
  243. struct CompileTimeBindingPattern {
  244. static constexpr auto Kind = NodeKind::CompileTimeBindingPattern.Define(
  245. {.category = NodeCategory::Pattern, .child_count = 2});
  246. NodeIdOneOf<IdentifierName, SelfValueName> name;
  247. Lex::ColonExclaimTokenIndex token;
  248. AnyExprId type;
  249. };
  250. // An address-of binding: `addr self: Self*`.
  251. struct Addr {
  252. static constexpr auto Kind = NodeKind::Addr.Define(
  253. {.category = NodeCategory::Pattern, .child_count = 1});
  254. Lex::AddrTokenIndex token;
  255. AnyPatternId inner;
  256. };
  257. // A template binding: `template T:! type`.
  258. struct Template {
  259. static constexpr auto Kind = NodeKind::Template.Define(
  260. {.category = NodeCategory::Pattern, .child_count = 1});
  261. Lex::TemplateTokenIndex token;
  262. // This is a CompileTimeBindingPatternId in any valid program.
  263. // TODO: Should the parser enforce that?
  264. AnyPatternId inner;
  265. };
  266. using TuplePatternStart =
  267. LeafNode<NodeKind::TuplePatternStart, Lex::OpenParenTokenIndex>;
  268. using PatternListComma =
  269. LeafNode<NodeKind::PatternListComma, Lex::CommaTokenIndex>;
  270. // A parameter list or tuple pattern: `(a: i32, b: i32)`.
  271. struct TuplePattern {
  272. static constexpr auto Kind =
  273. NodeKind::TuplePattern.Define({.category = NodeCategory::Pattern,
  274. .bracketed_by = TuplePatternStart::Kind});
  275. TuplePatternStartId left_paren;
  276. CommaSeparatedList<AnyPatternId, PatternListCommaId> params;
  277. Lex::CloseParenTokenIndex token;
  278. };
  279. using ImplicitParamListStart = LeafNode<NodeKind::ImplicitParamListStart,
  280. Lex::OpenSquareBracketTokenIndex>;
  281. // An implicit parameter list: `[T:! type, self: Self]`.
  282. struct ImplicitParamList {
  283. static constexpr auto Kind = NodeKind::ImplicitParamList.Define(
  284. {.bracketed_by = ImplicitParamListStart::Kind});
  285. ImplicitParamListStartId left_square;
  286. CommaSeparatedList<AnyPatternId, PatternListCommaId> params;
  287. Lex::CloseSquareBracketTokenIndex token;
  288. };
  289. // Function nodes
  290. // --------------
  291. using FunctionIntroducer =
  292. LeafNode<NodeKind::FunctionIntroducer, Lex::FnTokenIndex>;
  293. // A return type: `-> i32`.
  294. struct ReturnType {
  295. static constexpr auto Kind = NodeKind::ReturnType.Define({.child_count = 1});
  296. Lex::MinusGreaterTokenIndex token;
  297. AnyExprId type;
  298. };
  299. // A function signature: `fn F() -> i32`.
  300. template <const NodeKind& KindT, typename TokenKind,
  301. NodeCategory::RawEnumType Category>
  302. struct FunctionSignature {
  303. static constexpr auto Kind = KindT.Define(
  304. {.category = Category, .bracketed_by = FunctionIntroducer::Kind});
  305. FunctionIntroducerId introducer;
  306. llvm::SmallVector<AnyModifierId> modifiers;
  307. DeclName name;
  308. std::optional<ReturnTypeId> return_type;
  309. TokenKind token;
  310. };
  311. using FunctionDecl = FunctionSignature<NodeKind::FunctionDecl,
  312. Lex::SemiTokenIndex, NodeCategory::Decl>;
  313. using FunctionDefinitionStart =
  314. FunctionSignature<NodeKind::FunctionDefinitionStart,
  315. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  316. // A function definition: `fn F() -> i32 { ... }`.
  317. struct FunctionDefinition {
  318. static constexpr auto Kind = NodeKind::FunctionDefinition.Define(
  319. {.category = NodeCategory::Decl,
  320. .bracketed_by = FunctionDefinitionStart::Kind});
  321. FunctionDefinitionStartId signature;
  322. llvm::SmallVector<AnyStatementId> body;
  323. Lex::CloseCurlyBraceTokenIndex token;
  324. };
  325. using BuiltinFunctionDefinitionStart =
  326. FunctionSignature<NodeKind::BuiltinFunctionDefinitionStart,
  327. Lex::EqualTokenIndex, NodeCategory::None>;
  328. using BuiltinName =
  329. LeafNode<NodeKind::BuiltinName, Lex::StringLiteralTokenIndex>;
  330. // A builtin function definition: `fn F() -> i32 = "builtin name";`
  331. struct BuiltinFunctionDefinition {
  332. static constexpr auto Kind = NodeKind::BuiltinFunctionDefinition.Define(
  333. {.category = NodeCategory::Decl,
  334. .bracketed_by = BuiltinFunctionDefinitionStart::Kind});
  335. BuiltinFunctionDefinitionStartId signature;
  336. BuiltinNameId builtin_name;
  337. Lex::SemiTokenIndex token;
  338. };
  339. // `alias` nodes
  340. // -------------
  341. using AliasIntroducer =
  342. LeafNode<NodeKind::AliasIntroducer, Lex::AliasTokenIndex>;
  343. using AliasInitializer =
  344. LeafNode<NodeKind::AliasInitializer, Lex::EqualTokenIndex>;
  345. // An `alias` declaration: `alias a = b;`.
  346. struct Alias {
  347. static constexpr auto Kind = NodeKind::Alias.Define(
  348. {.category = NodeCategory::Decl | NodeCategory::Statement,
  349. .bracketed_by = AliasIntroducer::Kind});
  350. AliasIntroducerId introducer;
  351. llvm::SmallVector<AnyModifierId> modifiers;
  352. DeclName name;
  353. AliasInitializerId equals;
  354. AnyExprId initializer;
  355. Lex::SemiTokenIndex token;
  356. };
  357. // `let` nodes
  358. // -----------
  359. using LetIntroducer = LeafNode<NodeKind::LetIntroducer, Lex::LetTokenIndex>;
  360. using LetInitializer = LeafNode<NodeKind::LetInitializer, Lex::EqualTokenIndex>;
  361. // A `let` declaration: `let a: i32 = 5;`.
  362. struct LetDecl {
  363. static constexpr auto Kind = NodeKind::LetDecl.Define(
  364. {.category = NodeCategory::Decl | NodeCategory::Statement,
  365. .bracketed_by = LetIntroducer::Kind});
  366. LetIntroducerId introducer;
  367. llvm::SmallVector<AnyModifierId> modifiers;
  368. AnyPatternId pattern;
  369. struct Initializer {
  370. LetInitializerId equals;
  371. AnyExprId initializer;
  372. };
  373. std::optional<Initializer> initializer;
  374. Lex::SemiTokenIndex token;
  375. };
  376. // `var` nodes
  377. // -----------
  378. using VariableIntroducer =
  379. LeafNode<NodeKind::VariableIntroducer, Lex::VarTokenIndex>;
  380. using ReturnedModifier =
  381. LeafNode<NodeKind::ReturnedModifier, Lex::ReturnedTokenIndex>;
  382. using VariableInitializer =
  383. LeafNode<NodeKind::VariableInitializer, Lex::EqualTokenIndex>;
  384. // A `var` declaration: `var a: i32;` or `var a: i32 = 5;`.
  385. struct VariableDecl {
  386. static constexpr auto Kind = NodeKind::VariableDecl.Define(
  387. {.category = NodeCategory::Decl | NodeCategory::Statement,
  388. .bracketed_by = VariableIntroducer::Kind});
  389. VariableIntroducerId introducer;
  390. llvm::SmallVector<AnyModifierId> modifiers;
  391. std::optional<ReturnedModifierId> returned;
  392. AnyPatternId pattern;
  393. struct Initializer {
  394. VariableInitializerId equals;
  395. AnyExprId value;
  396. };
  397. std::optional<Initializer> initializer;
  398. Lex::SemiTokenIndex token;
  399. };
  400. // Statement nodes
  401. // ---------------
  402. using CodeBlockStart =
  403. LeafNode<NodeKind::CodeBlockStart, Lex::OpenCurlyBraceTokenIndex>;
  404. // A code block: `{ statement; statement; ... }`.
  405. struct CodeBlock {
  406. static constexpr auto Kind =
  407. NodeKind::CodeBlock.Define({.bracketed_by = CodeBlockStart::Kind});
  408. CodeBlockStartId left_brace;
  409. llvm::SmallVector<AnyStatementId> statements;
  410. Lex::CloseCurlyBraceTokenIndex token;
  411. };
  412. // An expression statement: `F(x);`.
  413. struct ExprStatement {
  414. static constexpr auto Kind = NodeKind::ExprStatement.Define(
  415. {.category = NodeCategory::Statement, .child_count = 1});
  416. AnyExprId expr;
  417. Lex::SemiTokenIndex token;
  418. };
  419. using BreakStatementStart =
  420. LeafNode<NodeKind::BreakStatementStart, Lex::BreakTokenIndex>;
  421. // A break statement: `break;`.
  422. struct BreakStatement {
  423. static constexpr auto Kind = NodeKind::BreakStatement.Define(
  424. {.category = NodeCategory::Statement,
  425. .bracketed_by = BreakStatementStart::Kind,
  426. .child_count = 1});
  427. BreakStatementStartId introducer;
  428. Lex::SemiTokenIndex token;
  429. };
  430. using ContinueStatementStart =
  431. LeafNode<NodeKind::ContinueStatementStart, Lex::ContinueTokenIndex>;
  432. // A continue statement: `continue;`.
  433. struct ContinueStatement {
  434. static constexpr auto Kind = NodeKind::ContinueStatement.Define(
  435. {.category = NodeCategory::Statement,
  436. .bracketed_by = ContinueStatementStart::Kind,
  437. .child_count = 1});
  438. ContinueStatementStartId introducer;
  439. Lex::SemiTokenIndex token;
  440. };
  441. using ReturnStatementStart =
  442. LeafNode<NodeKind::ReturnStatementStart, Lex::ReturnTokenIndex>;
  443. using ReturnVarModifier =
  444. LeafNode<NodeKind::ReturnVarModifier, Lex::VarTokenIndex>;
  445. // A return statement: `return;` or `return expr;` or `return var;`.
  446. struct ReturnStatement {
  447. static constexpr auto Kind = NodeKind::ReturnStatement.Define(
  448. {.category = NodeCategory::Statement,
  449. .bracketed_by = ReturnStatementStart::Kind});
  450. ReturnStatementStartId introducer;
  451. std::optional<AnyExprId> expr;
  452. std::optional<ReturnVarModifierId> var;
  453. Lex::SemiTokenIndex token;
  454. };
  455. using ForHeaderStart =
  456. LeafNode<NodeKind::ForHeaderStart, Lex::OpenParenTokenIndex>;
  457. // The `var ... in` portion of a `for` statement.
  458. struct ForIn {
  459. static constexpr auto Kind = NodeKind::ForIn.Define(
  460. {.bracketed_by = VariableIntroducer::Kind, .child_count = 2});
  461. VariableIntroducerId introducer;
  462. Lex::InTokenIndex token;
  463. AnyPatternId pattern;
  464. };
  465. // The `for (var ... in ...)` portion of a `for` statement.
  466. struct ForHeader {
  467. static constexpr auto Kind =
  468. NodeKind::ForHeader.Define({.bracketed_by = ForHeaderStart::Kind});
  469. ForHeaderStartId introducer;
  470. ForInId var;
  471. AnyExprId range;
  472. Lex::CloseParenTokenIndex token;
  473. };
  474. // A complete `for (...) { ... }` statement.
  475. struct ForStatement {
  476. static constexpr auto Kind =
  477. NodeKind::ForStatement.Define({.category = NodeCategory::Statement,
  478. .bracketed_by = ForHeader::Kind,
  479. .child_count = 2});
  480. Lex::ForTokenIndex token;
  481. ForHeaderId header;
  482. CodeBlockId body;
  483. };
  484. using IfConditionStart =
  485. LeafNode<NodeKind::IfConditionStart, Lex::OpenParenTokenIndex>;
  486. // The condition portion of an `if` statement: `(expr)`.
  487. struct IfCondition {
  488. static constexpr auto Kind = NodeKind::IfCondition.Define(
  489. {.bracketed_by = IfConditionStart::Kind, .child_count = 2});
  490. IfConditionStartId left_paren;
  491. AnyExprId condition;
  492. Lex::CloseParenTokenIndex token;
  493. };
  494. using IfStatementElse =
  495. LeafNode<NodeKind::IfStatementElse, Lex::ElseTokenIndex>;
  496. // An `if` statement: `if (expr) { ... } else { ... }`.
  497. struct IfStatement {
  498. static constexpr auto Kind = NodeKind::IfStatement.Define(
  499. {.category = NodeCategory::Statement, .bracketed_by = IfCondition::Kind});
  500. Lex::IfTokenIndex token;
  501. IfConditionId head;
  502. CodeBlockId then;
  503. struct Else {
  504. IfStatementElseId else_token;
  505. NodeIdOneOf<CodeBlock, IfStatement> body;
  506. };
  507. std::optional<Else> else_clause;
  508. };
  509. using WhileConditionStart =
  510. LeafNode<NodeKind::WhileConditionStart, Lex::OpenParenTokenIndex>;
  511. // The condition portion of a `while` statement: `(expr)`.
  512. struct WhileCondition {
  513. static constexpr auto Kind = NodeKind::WhileCondition.Define(
  514. {.bracketed_by = WhileConditionStart::Kind, .child_count = 2});
  515. WhileConditionStartId left_paren;
  516. AnyExprId condition;
  517. Lex::CloseParenTokenIndex token;
  518. };
  519. // A `while` statement: `while (expr) { ... }`.
  520. struct WhileStatement {
  521. static constexpr auto Kind =
  522. NodeKind::WhileStatement.Define({.category = NodeCategory::Statement,
  523. .bracketed_by = WhileCondition::Kind,
  524. .child_count = 2});
  525. Lex::WhileTokenIndex token;
  526. WhileConditionId head;
  527. CodeBlockId body;
  528. };
  529. using MatchConditionStart =
  530. LeafNode<NodeKind::MatchConditionStart, Lex::OpenParenTokenIndex>;
  531. struct MatchCondition {
  532. static constexpr auto Kind = NodeKind::MatchCondition.Define(
  533. {.bracketed_by = MatchConditionStart::Kind, .child_count = 2});
  534. MatchConditionStartId left_paren;
  535. AnyExprId condition;
  536. Lex::CloseParenTokenIndex token;
  537. };
  538. using MatchIntroducer =
  539. LeafNode<NodeKind::MatchIntroducer, Lex::MatchTokenIndex>;
  540. struct MatchStatementStart {
  541. static constexpr auto Kind = NodeKind::MatchStatementStart.Define(
  542. {.bracketed_by = MatchIntroducer::Kind, .child_count = 2});
  543. MatchIntroducerId introducer;
  544. MatchConditionId condition;
  545. Lex::OpenCurlyBraceTokenIndex token;
  546. };
  547. using MatchCaseIntroducer =
  548. LeafNode<NodeKind::MatchCaseIntroducer, Lex::CaseTokenIndex>;
  549. using MatchCaseGuardIntroducer =
  550. LeafNode<NodeKind::MatchCaseGuardIntroducer, Lex::IfTokenIndex>;
  551. using MatchCaseGuardStart =
  552. LeafNode<NodeKind::MatchCaseGuardStart, Lex::OpenParenTokenIndex>;
  553. struct MatchCaseGuard {
  554. static constexpr auto Kind = NodeKind::MatchCaseGuard.Define(
  555. {.bracketed_by = MatchCaseGuardIntroducer::Kind, .child_count = 3});
  556. MatchCaseGuardIntroducerId introducer;
  557. MatchCaseGuardStartId left_paren;
  558. AnyExprId condition;
  559. Lex::CloseParenTokenIndex token;
  560. };
  561. using MatchCaseEqualGreater =
  562. LeafNode<NodeKind::MatchCaseEqualGreater, Lex::EqualGreaterTokenIndex>;
  563. struct MatchCaseStart {
  564. static constexpr auto Kind = NodeKind::MatchCaseStart.Define(
  565. {.bracketed_by = MatchCaseIntroducer::Kind});
  566. MatchCaseIntroducerId introducer;
  567. AnyPatternId pattern;
  568. std::optional<MatchCaseGuardId> guard;
  569. MatchCaseEqualGreaterId equal_greater_token;
  570. Lex::OpenCurlyBraceTokenIndex token;
  571. };
  572. struct MatchCase {
  573. static constexpr auto Kind =
  574. NodeKind::MatchCase.Define({.bracketed_by = MatchCaseStart::Kind});
  575. MatchCaseStartId head;
  576. llvm::SmallVector<AnyStatementId> statements;
  577. Lex::CloseCurlyBraceTokenIndex token;
  578. };
  579. using MatchDefaultIntroducer =
  580. LeafNode<NodeKind::MatchDefaultIntroducer, Lex::DefaultTokenIndex>;
  581. using MatchDefaultEqualGreater =
  582. LeafNode<NodeKind::MatchDefaultEqualGreater, Lex::EqualGreaterTokenIndex>;
  583. struct MatchDefaultStart {
  584. static constexpr auto Kind = NodeKind::MatchDefaultStart.Define(
  585. {.bracketed_by = MatchDefaultIntroducer::Kind, .child_count = 2});
  586. MatchDefaultIntroducerId introducer;
  587. MatchDefaultEqualGreaterId equal_greater_token;
  588. Lex::OpenCurlyBraceTokenIndex token;
  589. };
  590. struct MatchDefault {
  591. static constexpr auto Kind =
  592. NodeKind::MatchDefault.Define({.bracketed_by = MatchDefaultStart::Kind});
  593. MatchDefaultStartId introducer;
  594. llvm::SmallVector<AnyStatementId> statements;
  595. Lex::CloseCurlyBraceTokenIndex token;
  596. };
  597. // A `match` statement: `match (expr) { case (...) => {...} default => {...}}`.
  598. struct MatchStatement {
  599. static constexpr auto Kind = NodeKind::MatchStatement.Define(
  600. {.category = NodeCategory::Statement,
  601. .bracketed_by = MatchStatementStart::Kind});
  602. MatchStatementStartId head;
  603. llvm::SmallVector<MatchCaseId> cases;
  604. std::optional<MatchDefaultId> default_case;
  605. Lex::CloseCurlyBraceTokenIndex token;
  606. };
  607. // Expression nodes
  608. // ----------------
  609. using ArrayExprStart =
  610. LeafNode<NodeKind::ArrayExprStart, Lex::OpenSquareBracketTokenIndex>;
  611. // The start of an array type, `[i32;`.
  612. //
  613. // TODO: Consider flattening this into `ArrayExpr`.
  614. struct ArrayExprSemi {
  615. static constexpr auto Kind = NodeKind::ArrayExprSemi.Define(
  616. {.bracketed_by = ArrayExprStart::Kind, .child_count = 2});
  617. ArrayExprStartId left_square;
  618. AnyExprId type;
  619. Lex::SemiTokenIndex token;
  620. };
  621. // An array type, such as `[i32; 3]` or `[i32;]`.
  622. struct ArrayExpr {
  623. static constexpr auto Kind = NodeKind::ArrayExpr.Define(
  624. {.category = NodeCategory::Expr, .bracketed_by = ArrayExprSemi::Kind});
  625. ArrayExprSemiId start;
  626. std::optional<AnyExprId> bound;
  627. Lex::CloseSquareBracketTokenIndex token;
  628. };
  629. // The opening portion of an indexing expression: `a[`.
  630. //
  631. // TODO: Consider flattening this into `IndexExpr`.
  632. struct IndexExprStart {
  633. static constexpr auto Kind =
  634. NodeKind::IndexExprStart.Define({.child_count = 1});
  635. AnyExprId sequence;
  636. Lex::OpenSquareBracketTokenIndex token;
  637. };
  638. // An indexing expression, such as `a[1]`.
  639. struct IndexExpr {
  640. static constexpr auto Kind =
  641. NodeKind::IndexExpr.Define({.category = NodeCategory::Expr,
  642. .bracketed_by = IndexExprStart::Kind,
  643. .child_count = 2});
  644. IndexExprStartId start;
  645. AnyExprId index;
  646. Lex::CloseSquareBracketTokenIndex token;
  647. };
  648. using ParenExprStart =
  649. LeafNode<NodeKind::ParenExprStart, Lex::OpenParenTokenIndex>;
  650. // A parenthesized expression: `(a)`.
  651. struct ParenExpr {
  652. static constexpr auto Kind = NodeKind::ParenExpr.Define(
  653. {.category = NodeCategory::Expr | NodeCategory::MemberExpr,
  654. .bracketed_by = ParenExprStart::Kind,
  655. .child_count = 2});
  656. ParenExprStartId start;
  657. AnyExprId expr;
  658. Lex::CloseParenTokenIndex token;
  659. };
  660. using TupleLiteralStart =
  661. LeafNode<NodeKind::TupleLiteralStart, Lex::OpenParenTokenIndex>;
  662. using TupleLiteralComma =
  663. LeafNode<NodeKind::TupleLiteralComma, Lex::CommaTokenIndex>;
  664. // A tuple literal: `()`, `(a, b, c)`, or `(a,)`.
  665. struct TupleLiteral {
  666. static constexpr auto Kind =
  667. NodeKind::TupleLiteral.Define({.category = NodeCategory::Expr,
  668. .bracketed_by = TupleLiteralStart::Kind});
  669. TupleLiteralStartId start;
  670. CommaSeparatedList<AnyExprId, TupleLiteralCommaId> elements;
  671. Lex::CloseParenTokenIndex token;
  672. };
  673. // The opening portion of a call expression: `F(`.
  674. //
  675. // TODO: Consider flattening this into `CallExpr`.
  676. struct CallExprStart {
  677. static constexpr auto Kind =
  678. NodeKind::CallExprStart.Define({.child_count = 1});
  679. AnyExprId callee;
  680. Lex::OpenParenTokenIndex token;
  681. };
  682. using CallExprComma = LeafNode<NodeKind::CallExprComma, Lex::CommaTokenIndex>;
  683. // A call expression: `F(a, b, c)`.
  684. struct CallExpr {
  685. static constexpr auto Kind = NodeKind::CallExpr.Define(
  686. {.category = NodeCategory::Expr, .bracketed_by = CallExprStart::Kind});
  687. CallExprStartId start;
  688. CommaSeparatedList<AnyExprId, CallExprCommaId> arguments;
  689. Lex::CloseParenTokenIndex token;
  690. };
  691. // A member access expression: `a.b` or `a.(b)`.
  692. struct MemberAccessExpr {
  693. static constexpr auto Kind = NodeKind::MemberAccessExpr.Define(
  694. {.category = NodeCategory::Expr, .child_count = 2});
  695. AnyExprId lhs;
  696. Lex::PeriodTokenIndex token;
  697. AnyMemberNameOrMemberExprId rhs;
  698. };
  699. // An indirect member access expression: `a->b` or `a->(b)`.
  700. struct PointerMemberAccessExpr {
  701. static constexpr auto Kind = NodeKind::PointerMemberAccessExpr.Define(
  702. {.category = NodeCategory::Expr, .child_count = 2});
  703. AnyExprId lhs;
  704. Lex::MinusGreaterTokenIndex token;
  705. AnyMemberNameOrMemberExprId rhs;
  706. };
  707. // A prefix operator expression.
  708. template <const NodeKind& KindT, typename TokenKind>
  709. struct PrefixOperator {
  710. static constexpr auto Kind =
  711. KindT.Define({.category = NodeCategory::Expr, .child_count = 1});
  712. TokenKind token;
  713. AnyExprId operand;
  714. };
  715. // An infix operator expression.
  716. template <const NodeKind& KindT, typename TokenKind>
  717. struct InfixOperator {
  718. static constexpr auto Kind =
  719. KindT.Define({.category = NodeCategory::Expr, .child_count = 2});
  720. AnyExprId lhs;
  721. TokenKind token;
  722. AnyExprId rhs;
  723. };
  724. // A postfix operator expression.
  725. template <const NodeKind& KindT, typename TokenKind>
  726. struct PostfixOperator {
  727. static constexpr auto Kind =
  728. KindT.Define({.category = NodeCategory::Expr, .child_count = 1});
  729. AnyExprId operand;
  730. TokenKind token;
  731. };
  732. // Literals, operators, and modifiers
  733. #define CARBON_PARSE_NODE_KIND(...)
  734. #define CARBON_PARSE_NODE_KIND_TOKEN_LITERAL(Name, LexTokenKind) \
  735. using Name = LeafNode<NodeKind::Name, Lex::LexTokenKind##TokenIndex, \
  736. NodeCategory::Expr>;
  737. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name) \
  738. using Name##Modifier = \
  739. LeafNode<NodeKind::Name##Modifier, Lex::Name##TokenIndex, \
  740. NodeCategory::Modifier>;
  741. #define CARBON_PARSE_NODE_KIND_PREFIX_OPERATOR(Name) \
  742. using PrefixOperator##Name = \
  743. PrefixOperator<NodeKind::PrefixOperator##Name, Lex::Name##TokenIndex>;
  744. #define CARBON_PARSE_NODE_KIND_INFIX_OPERATOR(Name) \
  745. using InfixOperator##Name = \
  746. InfixOperator<NodeKind::InfixOperator##Name, Lex::Name##TokenIndex>;
  747. #define CARBON_PARSE_NODE_KIND_POSTFIX_OPERATOR(Name) \
  748. using PostfixOperator##Name = \
  749. PostfixOperator<NodeKind::PostfixOperator##Name, Lex::Name##TokenIndex>;
  750. #include "toolchain/parse/node_kind.def"
  751. // The first operand of a short-circuiting infix operator: `a and` or `a or`.
  752. // The complete operator expression will be an InfixOperator with this as the
  753. // `lhs`.
  754. // TODO: Make this be a template if we ever need to write generic code to cover
  755. // both cases at once, say in check.
  756. struct ShortCircuitOperandAnd {
  757. static constexpr auto Kind =
  758. NodeKind::ShortCircuitOperandAnd.Define({.child_count = 1});
  759. AnyExprId operand;
  760. // This is a virtual token. The `and` token is owned by the
  761. // ShortCircuitOperatorAnd node.
  762. Lex::AndTokenIndex token;
  763. };
  764. struct ShortCircuitOperandOr {
  765. static constexpr auto Kind =
  766. NodeKind::ShortCircuitOperandOr.Define({.child_count = 1});
  767. AnyExprId operand;
  768. // This is a virtual token. The `or` token is owned by the
  769. // ShortCircuitOperatorOr node.
  770. Lex::OrTokenIndex token;
  771. };
  772. struct ShortCircuitOperatorAnd {
  773. static constexpr auto Kind = NodeKind::ShortCircuitOperatorAnd.Define(
  774. {.category = NodeCategory::Expr,
  775. .bracketed_by = ShortCircuitOperandAnd::Kind,
  776. .child_count = 2});
  777. ShortCircuitOperandAndId lhs;
  778. Lex::AndTokenIndex token;
  779. AnyExprId rhs;
  780. };
  781. struct ShortCircuitOperatorOr {
  782. static constexpr auto Kind = NodeKind::ShortCircuitOperatorOr.Define(
  783. {.category = NodeCategory::Expr,
  784. .bracketed_by = ShortCircuitOperandOr::Kind,
  785. .child_count = 2});
  786. ShortCircuitOperandOrId lhs;
  787. Lex::OrTokenIndex token;
  788. AnyExprId rhs;
  789. };
  790. // The `if` portion of an `if` expression: `if expr`.
  791. struct IfExprIf {
  792. static constexpr auto Kind = NodeKind::IfExprIf.Define({.child_count = 1});
  793. Lex::IfTokenIndex token;
  794. AnyExprId condition;
  795. };
  796. // The `then` portion of an `if` expression: `then expr`.
  797. struct IfExprThen {
  798. static constexpr auto Kind = NodeKind::IfExprThen.Define({.child_count = 1});
  799. Lex::ThenTokenIndex token;
  800. AnyExprId result;
  801. };
  802. // A full `if` expression: `if expr then expr else expr`.
  803. struct IfExprElse {
  804. static constexpr auto Kind =
  805. NodeKind::IfExprElse.Define({.category = NodeCategory::Expr,
  806. .bracketed_by = IfExprIf::Kind,
  807. .child_count = 3});
  808. IfExprIfId start;
  809. IfExprThenId then;
  810. Lex::ElseTokenIndex token;
  811. AnyExprId else_result;
  812. };
  813. // Choice nodes
  814. // ------------
  815. using ChoiceIntroducer =
  816. LeafNode<NodeKind::ChoiceIntroducer, Lex::ChoiceTokenIndex>;
  817. struct ChoiceSignature {
  818. static constexpr auto Kind = NodeKind::ChoiceDefinitionStart.Define(
  819. {.category = NodeCategory::None, .bracketed_by = ChoiceIntroducer::Kind});
  820. ChoiceIntroducerId introducer;
  821. llvm::SmallVector<AnyModifierId> modifiers;
  822. DeclName name;
  823. Lex::OpenCurlyBraceTokenIndex token;
  824. };
  825. using ChoiceDefinitionStart = ChoiceSignature;
  826. using ChoiceAlternativeListComma =
  827. LeafNode<NodeKind::ChoiceAlternativeListComma, Lex::CommaTokenIndex>;
  828. struct ChoiceDefinition {
  829. static constexpr auto Kind = NodeKind::ChoiceDefinition.Define(
  830. {.category = NodeCategory::Decl,
  831. .bracketed_by = ChoiceDefinitionStart::Kind});
  832. ChoiceDefinitionStartId signature;
  833. struct Alternative {
  834. IdentifierNameId name;
  835. std::optional<TuplePatternId> parameters;
  836. };
  837. CommaSeparatedList<Alternative, ChoiceAlternativeListCommaId> alternatives;
  838. Lex::CloseCurlyBraceTokenIndex token;
  839. };
  840. // Struct type and value literals
  841. // ----------------------------------------
  842. // `{`
  843. using StructLiteralStart =
  844. LeafNode<NodeKind::StructLiteralStart, Lex::OpenCurlyBraceTokenIndex>;
  845. using StructTypeLiteralStart =
  846. LeafNode<NodeKind::StructTypeLiteralStart, Lex::OpenCurlyBraceTokenIndex>;
  847. // `,`
  848. using StructComma = LeafNode<NodeKind::StructComma, Lex::CommaTokenIndex>;
  849. // `.a`
  850. struct StructFieldDesignator {
  851. static constexpr auto Kind =
  852. NodeKind::StructFieldDesignator.Define({.child_count = 1});
  853. Lex::PeriodTokenIndex token;
  854. NodeIdOneOf<IdentifierName, BaseName> name;
  855. };
  856. // `.a = 0`
  857. struct StructField {
  858. static constexpr auto Kind = NodeKind::StructField.Define(
  859. {.bracketed_by = StructFieldDesignator::Kind, .child_count = 2});
  860. StructFieldDesignatorId designator;
  861. Lex::EqualTokenIndex token;
  862. AnyExprId expr;
  863. };
  864. // `.a: i32`
  865. struct StructTypeField {
  866. static constexpr auto Kind = NodeKind::StructTypeField.Define(
  867. {.bracketed_by = StructFieldDesignator::Kind, .child_count = 2});
  868. StructFieldDesignatorId designator;
  869. Lex::ColonTokenIndex token;
  870. AnyExprId type_expr;
  871. };
  872. // Struct literals, such as `{.a = 0}`.
  873. struct StructLiteral {
  874. static constexpr auto Kind = NodeKind::StructLiteral.Define(
  875. {.category = NodeCategory::Expr,
  876. .bracketed_by = StructLiteralStart::Kind});
  877. StructLiteralStartId start;
  878. CommaSeparatedList<StructFieldId, StructCommaId> fields;
  879. Lex::CloseCurlyBraceTokenIndex token;
  880. };
  881. // Struct type literals, such as `{.a: i32}`.
  882. struct StructTypeLiteral {
  883. static constexpr auto Kind = NodeKind::StructTypeLiteral.Define(
  884. {.category = NodeCategory::Expr,
  885. .bracketed_by = StructTypeLiteralStart::Kind});
  886. StructTypeLiteralStartId start;
  887. CommaSeparatedList<StructTypeFieldId, StructCommaId> fields;
  888. Lex::CloseCurlyBraceTokenIndex token;
  889. };
  890. // `class` declarations and definitions
  891. // ------------------------------------
  892. // `class`
  893. using ClassIntroducer =
  894. LeafNode<NodeKind::ClassIntroducer, Lex::ClassTokenIndex>;
  895. // A class signature `class C`
  896. template <const NodeKind& KindT, typename TokenKind,
  897. NodeCategory::RawEnumType Category>
  898. struct ClassSignature {
  899. static constexpr auto Kind = KindT.Define(
  900. {.category = Category, .bracketed_by = ClassIntroducer::Kind});
  901. ClassIntroducerId introducer;
  902. llvm::SmallVector<AnyModifierId> modifiers;
  903. DeclName name;
  904. TokenKind token;
  905. };
  906. // `class C;`
  907. using ClassDecl = ClassSignature<NodeKind::ClassDecl, Lex::SemiTokenIndex,
  908. NodeCategory::Decl>;
  909. // `class C {`
  910. using ClassDefinitionStart =
  911. ClassSignature<NodeKind::ClassDefinitionStart,
  912. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  913. // `class C { ... }`
  914. struct ClassDefinition {
  915. static constexpr auto Kind = NodeKind::ClassDefinition.Define(
  916. {.category = NodeCategory::Decl,
  917. .bracketed_by = ClassDefinitionStart::Kind});
  918. ClassDefinitionStartId signature;
  919. llvm::SmallVector<AnyDeclId> members;
  920. Lex::CloseCurlyBraceTokenIndex token;
  921. };
  922. // Adapter declaration
  923. // -------------------
  924. // `adapt`
  925. using AdaptIntroducer =
  926. LeafNode<NodeKind::AdaptIntroducer, Lex::AdaptTokenIndex>;
  927. // `adapt SomeType;`
  928. struct AdaptDecl {
  929. static constexpr auto Kind = NodeKind::AdaptDecl.Define(
  930. {.category = NodeCategory::Decl, .bracketed_by = AdaptIntroducer::Kind});
  931. AdaptIntroducerId introducer;
  932. llvm::SmallVector<AnyModifierId> modifiers;
  933. AnyExprId adapted_type;
  934. Lex::SemiTokenIndex token;
  935. };
  936. // Base class declaration
  937. // ----------------------
  938. // `base`
  939. using BaseIntroducer = LeafNode<NodeKind::BaseIntroducer, Lex::BaseTokenIndex>;
  940. using BaseColon = LeafNode<NodeKind::BaseColon, Lex::ColonTokenIndex>;
  941. // `extend base: BaseClass;`
  942. struct BaseDecl {
  943. static constexpr auto Kind = NodeKind::BaseDecl.Define(
  944. {.category = NodeCategory::Decl, .bracketed_by = BaseIntroducer::Kind});
  945. BaseIntroducerId introducer;
  946. llvm::SmallVector<AnyModifierId> modifiers;
  947. BaseColonId colon;
  948. AnyExprId base_class;
  949. Lex::SemiTokenIndex token;
  950. };
  951. // Interface declarations and definitions
  952. // --------------------------------------
  953. // `interface`
  954. using InterfaceIntroducer =
  955. LeafNode<NodeKind::InterfaceIntroducer, Lex::InterfaceTokenIndex>;
  956. // `interface I`
  957. template <const NodeKind& KindT, typename TokenKind,
  958. NodeCategory::RawEnumType Category>
  959. struct InterfaceSignature {
  960. static constexpr auto Kind = KindT.Define(
  961. {.category = Category, .bracketed_by = InterfaceIntroducer::Kind});
  962. InterfaceIntroducerId introducer;
  963. llvm::SmallVector<AnyModifierId> modifiers;
  964. DeclName name;
  965. TokenKind token;
  966. };
  967. // `interface I;`
  968. using InterfaceDecl =
  969. InterfaceSignature<NodeKind::InterfaceDecl, Lex::SemiTokenIndex,
  970. NodeCategory::Decl>;
  971. // `interface I {`
  972. using InterfaceDefinitionStart =
  973. InterfaceSignature<NodeKind::InterfaceDefinitionStart,
  974. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  975. // `interface I { ... }`
  976. struct InterfaceDefinition {
  977. static constexpr auto Kind = NodeKind::InterfaceDefinition.Define(
  978. {.category = NodeCategory::Decl,
  979. .bracketed_by = InterfaceDefinitionStart::Kind});
  980. InterfaceDefinitionStartId signature;
  981. llvm::SmallVector<AnyDeclId> members;
  982. Lex::CloseCurlyBraceTokenIndex token;
  983. };
  984. // `impl`...`as` declarations and definitions
  985. // ------------------------------------------
  986. // `impl`
  987. using ImplIntroducer = LeafNode<NodeKind::ImplIntroducer, Lex::ImplTokenIndex>;
  988. // `forall [...]`
  989. struct ImplForall {
  990. static constexpr auto Kind = NodeKind::ImplForall.Define({.child_count = 1});
  991. Lex::ForallTokenIndex token;
  992. ImplicitParamListId params;
  993. };
  994. // `as` with no type before it
  995. using DefaultSelfImplAs = LeafNode<NodeKind::DefaultSelfImplAs,
  996. Lex::AsTokenIndex, NodeCategory::ImplAs>;
  997. // `<type> as`
  998. struct TypeImplAs {
  999. static constexpr auto Kind = NodeKind::TypeImplAs.Define(
  1000. {.category = NodeCategory::ImplAs, .child_count = 1});
  1001. AnyExprId type_expr;
  1002. Lex::AsTokenIndex token;
  1003. };
  1004. // `impl T as I`
  1005. template <const NodeKind& KindT, typename TokenKind,
  1006. NodeCategory::RawEnumType Category>
  1007. struct ImplSignature {
  1008. static constexpr auto Kind = KindT.Define(
  1009. {.category = Category, .bracketed_by = ImplIntroducer::Kind});
  1010. ImplIntroducerId introducer;
  1011. llvm::SmallVector<AnyModifierId> modifiers;
  1012. std::optional<ImplForallId> forall;
  1013. AnyImplAsId as;
  1014. AnyExprId interface;
  1015. TokenKind token;
  1016. };
  1017. // `impl T as I;`
  1018. using ImplDecl =
  1019. ImplSignature<NodeKind::ImplDecl, Lex::SemiTokenIndex, NodeCategory::Decl>;
  1020. // `impl T as I {`
  1021. using ImplDefinitionStart =
  1022. ImplSignature<NodeKind::ImplDefinitionStart, Lex::OpenCurlyBraceTokenIndex,
  1023. NodeCategory::None>;
  1024. // `impl T as I { ... }`
  1025. struct ImplDefinition {
  1026. static constexpr auto Kind = NodeKind::ImplDefinition.Define(
  1027. {.category = NodeCategory::Decl,
  1028. .bracketed_by = ImplDefinitionStart::Kind});
  1029. ImplDefinitionStartId signature;
  1030. llvm::SmallVector<AnyDeclId> members;
  1031. Lex::CloseCurlyBraceTokenIndex token;
  1032. };
  1033. // Named constraint declarations and definitions
  1034. // ---------------------------------------------
  1035. // `constraint`
  1036. using NamedConstraintIntroducer =
  1037. LeafNode<NodeKind::NamedConstraintIntroducer, Lex::ConstraintTokenIndex>;
  1038. // `constraint NC`
  1039. template <const NodeKind& KindT, typename TokenKind,
  1040. NodeCategory::RawEnumType Category>
  1041. struct NamedConstraintSignature {
  1042. static constexpr auto Kind = KindT.Define(
  1043. {.category = Category, .bracketed_by = NamedConstraintIntroducer::Kind});
  1044. NamedConstraintIntroducerId introducer;
  1045. llvm::SmallVector<AnyModifierId> modifiers;
  1046. DeclName name;
  1047. TokenKind token;
  1048. };
  1049. // `constraint NC;`
  1050. using NamedConstraintDecl =
  1051. NamedConstraintSignature<NodeKind::NamedConstraintDecl, Lex::SemiTokenIndex,
  1052. NodeCategory::Decl>;
  1053. // `constraint NC {`
  1054. using NamedConstraintDefinitionStart =
  1055. NamedConstraintSignature<NodeKind::NamedConstraintDefinitionStart,
  1056. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  1057. // `constraint NC { ... }`
  1058. struct NamedConstraintDefinition {
  1059. static constexpr auto Kind = NodeKind::NamedConstraintDefinition.Define(
  1060. {.category = NodeCategory::Decl,
  1061. .bracketed_by = NamedConstraintDefinitionStart::Kind});
  1062. NamedConstraintDefinitionStartId signature;
  1063. llvm::SmallVector<AnyDeclId> members;
  1064. Lex::CloseCurlyBraceTokenIndex token;
  1065. };
  1066. // ---------------------------------------------------------------------------
  1067. // A complete source file. Note that there is no corresponding parse node for
  1068. // the file. The file is instead the complete contents of the parse tree.
  1069. struct File {
  1070. FileStartId start;
  1071. llvm::SmallVector<AnyDeclId> decls;
  1072. FileEndId end;
  1073. };
  1074. // Define `Foo` as the node type for the ID type `FooId`.
  1075. #define CARBON_PARSE_NODE_KIND(KindName) \
  1076. template <> \
  1077. struct NodeForId<KindName##Id> { \
  1078. using TypedNode = KindName; \
  1079. };
  1080. #include "toolchain/parse/node_kind.def"
  1081. } // namespace Carbon::Parse
  1082. #endif // CARBON_TOOLCHAIN_PARSE_TYPED_NODES_H_