typed_nodes.h 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413
  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. AnyMemberAccessId 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. AnyMemberAccessId 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. using IntLiteral = LeafNode<NodeKind::IntLiteral, Lex::IntLiteralTokenIndex,
  752. NodeCategory::Expr | NodeCategory::IntConst>;
  753. // `extern` as a standalone modifier.
  754. using ExternModifier = LeafNode<NodeKind::ExternModifier, Lex::ExternTokenIndex,
  755. NodeCategory::Modifier>;
  756. // `extern library <owning_library>` modifiers.
  757. struct ExternModifierWithLibrary {
  758. static constexpr auto Kind = NodeKind::ExternModifierWithLibrary.Define(
  759. {.category = NodeCategory::Modifier, .child_count = 1});
  760. Lex::ExternTokenIndex token;
  761. LibrarySpecifierId library;
  762. };
  763. // The first operand of a short-circuiting infix operator: `a and` or `a or`.
  764. // The complete operator expression will be an InfixOperator with this as the
  765. // `lhs`.
  766. // TODO: Make this be a template if we ever need to write generic code to cover
  767. // both cases at once, say in check.
  768. struct ShortCircuitOperandAnd {
  769. static constexpr auto Kind =
  770. NodeKind::ShortCircuitOperandAnd.Define({.child_count = 1});
  771. AnyExprId operand;
  772. // This is a virtual token. The `and` token is owned by the
  773. // ShortCircuitOperatorAnd node.
  774. Lex::AndTokenIndex token;
  775. };
  776. struct ShortCircuitOperandOr {
  777. static constexpr auto Kind =
  778. NodeKind::ShortCircuitOperandOr.Define({.child_count = 1});
  779. AnyExprId operand;
  780. // This is a virtual token. The `or` token is owned by the
  781. // ShortCircuitOperatorOr node.
  782. Lex::OrTokenIndex token;
  783. };
  784. struct ShortCircuitOperatorAnd {
  785. static constexpr auto Kind = NodeKind::ShortCircuitOperatorAnd.Define(
  786. {.category = NodeCategory::Expr,
  787. .bracketed_by = ShortCircuitOperandAnd::Kind,
  788. .child_count = 2});
  789. ShortCircuitOperandAndId lhs;
  790. Lex::AndTokenIndex token;
  791. AnyExprId rhs;
  792. };
  793. struct ShortCircuitOperatorOr {
  794. static constexpr auto Kind = NodeKind::ShortCircuitOperatorOr.Define(
  795. {.category = NodeCategory::Expr,
  796. .bracketed_by = ShortCircuitOperandOr::Kind,
  797. .child_count = 2});
  798. ShortCircuitOperandOrId lhs;
  799. Lex::OrTokenIndex token;
  800. AnyExprId rhs;
  801. };
  802. // The `if` portion of an `if` expression: `if expr`.
  803. struct IfExprIf {
  804. static constexpr auto Kind = NodeKind::IfExprIf.Define({.child_count = 1});
  805. Lex::IfTokenIndex token;
  806. AnyExprId condition;
  807. };
  808. // The `then` portion of an `if` expression: `then expr`.
  809. struct IfExprThen {
  810. static constexpr auto Kind = NodeKind::IfExprThen.Define({.child_count = 1});
  811. Lex::ThenTokenIndex token;
  812. AnyExprId result;
  813. };
  814. // A full `if` expression: `if expr then expr else expr`.
  815. struct IfExprElse {
  816. static constexpr auto Kind =
  817. NodeKind::IfExprElse.Define({.category = NodeCategory::Expr,
  818. .bracketed_by = IfExprIf::Kind,
  819. .child_count = 3});
  820. IfExprIfId start;
  821. IfExprThenId then;
  822. Lex::ElseTokenIndex token;
  823. AnyExprId else_result;
  824. };
  825. // A `where` expression (TODO: `require` and `observe` declarations)
  826. // The `Self` in a context where it is treated as a name rather than an
  827. // expression, such as `.Self`.
  828. using SelfTypeName =
  829. LeafNode<NodeKind::SelfTypeName, Lex::SelfTypeIdentifierTokenIndex>;
  830. // `.Member` or `.Self` in an expression context, used in `where` and `require`
  831. // clauses.
  832. // TODO: Do we want to support `.1`, a designator for accessing a tuple member?
  833. struct DesignatorExpr {
  834. static constexpr auto Kind = NodeKind::DesignatorExpr.Define(
  835. {.category = NodeCategory::Expr, .child_count = 1});
  836. Lex::PeriodTokenIndex token;
  837. NodeIdOneOf<IdentifierName, SelfTypeName> name;
  838. };
  839. struct RequirementEqual {
  840. static constexpr auto Kind = NodeKind::RequirementEqual.Define(
  841. {.category = NodeCategory::Requirement, .child_count = 2});
  842. DesignatorExprId lhs;
  843. Lex::EqualTokenIndex token;
  844. AnyExprId rhs;
  845. };
  846. struct RequirementEqualEqual {
  847. static constexpr auto Kind = NodeKind::RequirementEqualEqual.Define(
  848. {.category = NodeCategory::Requirement, .child_count = 2});
  849. AnyExprId lhs;
  850. Lex::EqualEqualTokenIndex token;
  851. AnyExprId rhs;
  852. };
  853. struct RequirementImpls {
  854. static constexpr auto Kind = NodeKind::RequirementImpls.Define(
  855. {.category = NodeCategory::Requirement, .child_count = 2});
  856. AnyExprId lhs;
  857. Lex::ImplsTokenIndex token;
  858. AnyExprId rhs;
  859. };
  860. // An `and` token separating requirements in a `where` expression.
  861. using RequirementAnd = LeafNode<NodeKind::RequirementAnd, Lex::AndTokenIndex>;
  862. struct WhereOperand {
  863. static constexpr auto Kind =
  864. NodeKind::WhereOperand.Define({.child_count = 1});
  865. AnyExprId type;
  866. // This is a virtual token. The `where` token is owned by the
  867. // WhereExpr node.
  868. Lex::WhereTokenIndex token;
  869. };
  870. struct WhereExpr {
  871. static constexpr auto Kind = NodeKind::WhereExpr.Define(
  872. {.category = NodeCategory::Expr, .bracketed_by = WhereOperand::Kind});
  873. WhereOperandId introducer;
  874. Lex::WhereTokenIndex token;
  875. CommaSeparatedList<AnyRequirementId, RequirementAndId> requirements;
  876. };
  877. // Choice nodes
  878. // ------------
  879. using ChoiceIntroducer =
  880. LeafNode<NodeKind::ChoiceIntroducer, Lex::ChoiceTokenIndex>;
  881. struct ChoiceSignature {
  882. static constexpr auto Kind = NodeKind::ChoiceDefinitionStart.Define(
  883. {.category = NodeCategory::None, .bracketed_by = ChoiceIntroducer::Kind});
  884. ChoiceIntroducerId introducer;
  885. llvm::SmallVector<AnyModifierId> modifiers;
  886. DeclName name;
  887. Lex::OpenCurlyBraceTokenIndex token;
  888. };
  889. using ChoiceDefinitionStart = ChoiceSignature;
  890. using ChoiceAlternativeListComma =
  891. LeafNode<NodeKind::ChoiceAlternativeListComma, Lex::CommaTokenIndex>;
  892. struct ChoiceDefinition {
  893. static constexpr auto Kind = NodeKind::ChoiceDefinition.Define(
  894. {.category = NodeCategory::Decl,
  895. .bracketed_by = ChoiceDefinitionStart::Kind});
  896. ChoiceDefinitionStartId signature;
  897. struct Alternative {
  898. IdentifierNameId name;
  899. std::optional<TuplePatternId> parameters;
  900. };
  901. CommaSeparatedList<Alternative, ChoiceAlternativeListCommaId> alternatives;
  902. Lex::CloseCurlyBraceTokenIndex token;
  903. };
  904. // Struct type and value literals
  905. // ----------------------------------------
  906. // `{`
  907. using StructLiteralStart =
  908. LeafNode<NodeKind::StructLiteralStart, Lex::OpenCurlyBraceTokenIndex>;
  909. using StructTypeLiteralStart =
  910. LeafNode<NodeKind::StructTypeLiteralStart, Lex::OpenCurlyBraceTokenIndex>;
  911. // `,`
  912. using StructComma = LeafNode<NodeKind::StructComma, Lex::CommaTokenIndex>;
  913. // `.a`
  914. struct StructFieldDesignator {
  915. static constexpr auto Kind =
  916. NodeKind::StructFieldDesignator.Define({.child_count = 1});
  917. Lex::PeriodTokenIndex token;
  918. NodeIdOneOf<IdentifierName, BaseName> name;
  919. };
  920. // `.a = 0`
  921. struct StructField {
  922. static constexpr auto Kind = NodeKind::StructField.Define(
  923. {.bracketed_by = StructFieldDesignator::Kind, .child_count = 2});
  924. StructFieldDesignatorId designator;
  925. Lex::EqualTokenIndex token;
  926. AnyExprId expr;
  927. };
  928. // `.a: i32`
  929. struct StructTypeField {
  930. static constexpr auto Kind = NodeKind::StructTypeField.Define(
  931. {.bracketed_by = StructFieldDesignator::Kind, .child_count = 2});
  932. StructFieldDesignatorId designator;
  933. Lex::ColonTokenIndex token;
  934. AnyExprId type_expr;
  935. };
  936. // Struct literals, such as `{.a = 0}`.
  937. struct StructLiteral {
  938. static constexpr auto Kind = NodeKind::StructLiteral.Define(
  939. {.category = NodeCategory::Expr,
  940. .bracketed_by = StructLiteralStart::Kind});
  941. StructLiteralStartId start;
  942. CommaSeparatedList<StructFieldId, StructCommaId> fields;
  943. Lex::CloseCurlyBraceTokenIndex token;
  944. };
  945. // Struct type literals, such as `{.a: i32}`.
  946. struct StructTypeLiteral {
  947. static constexpr auto Kind = NodeKind::StructTypeLiteral.Define(
  948. {.category = NodeCategory::Expr,
  949. .bracketed_by = StructTypeLiteralStart::Kind});
  950. StructTypeLiteralStartId start;
  951. CommaSeparatedList<StructTypeFieldId, StructCommaId> fields;
  952. Lex::CloseCurlyBraceTokenIndex token;
  953. };
  954. // `class` declarations and definitions
  955. // ------------------------------------
  956. // `class`
  957. using ClassIntroducer =
  958. LeafNode<NodeKind::ClassIntroducer, Lex::ClassTokenIndex>;
  959. // A class signature `class C`
  960. template <const NodeKind& KindT, typename TokenKind,
  961. NodeCategory::RawEnumType Category>
  962. struct ClassSignature {
  963. static constexpr auto Kind = KindT.Define(
  964. {.category = Category, .bracketed_by = ClassIntroducer::Kind});
  965. ClassIntroducerId introducer;
  966. llvm::SmallVector<AnyModifierId> modifiers;
  967. DeclName name;
  968. TokenKind token;
  969. };
  970. // `class C;`
  971. using ClassDecl = ClassSignature<NodeKind::ClassDecl, Lex::SemiTokenIndex,
  972. NodeCategory::Decl>;
  973. // `class C {`
  974. using ClassDefinitionStart =
  975. ClassSignature<NodeKind::ClassDefinitionStart,
  976. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  977. // `class C { ... }`
  978. struct ClassDefinition {
  979. static constexpr auto Kind = NodeKind::ClassDefinition.Define(
  980. {.category = NodeCategory::Decl,
  981. .bracketed_by = ClassDefinitionStart::Kind});
  982. ClassDefinitionStartId signature;
  983. llvm::SmallVector<AnyDeclId> members;
  984. Lex::CloseCurlyBraceTokenIndex token;
  985. };
  986. // Adapter declaration
  987. // -------------------
  988. // `adapt`
  989. using AdaptIntroducer =
  990. LeafNode<NodeKind::AdaptIntroducer, Lex::AdaptTokenIndex>;
  991. // `adapt SomeType;`
  992. struct AdaptDecl {
  993. static constexpr auto Kind = NodeKind::AdaptDecl.Define(
  994. {.category = NodeCategory::Decl, .bracketed_by = AdaptIntroducer::Kind});
  995. AdaptIntroducerId introducer;
  996. llvm::SmallVector<AnyModifierId> modifiers;
  997. AnyExprId adapted_type;
  998. Lex::SemiTokenIndex token;
  999. };
  1000. // Base class declaration
  1001. // ----------------------
  1002. // `base`
  1003. using BaseIntroducer = LeafNode<NodeKind::BaseIntroducer, Lex::BaseTokenIndex>;
  1004. using BaseColon = LeafNode<NodeKind::BaseColon, Lex::ColonTokenIndex>;
  1005. // `extend base: BaseClass;`
  1006. struct BaseDecl {
  1007. static constexpr auto Kind = NodeKind::BaseDecl.Define(
  1008. {.category = NodeCategory::Decl, .bracketed_by = BaseIntroducer::Kind});
  1009. BaseIntroducerId introducer;
  1010. llvm::SmallVector<AnyModifierId> modifiers;
  1011. BaseColonId colon;
  1012. AnyExprId base_class;
  1013. Lex::SemiTokenIndex token;
  1014. };
  1015. // Interface declarations and definitions
  1016. // --------------------------------------
  1017. // `interface`
  1018. using InterfaceIntroducer =
  1019. LeafNode<NodeKind::InterfaceIntroducer, Lex::InterfaceTokenIndex>;
  1020. // `interface I`
  1021. template <const NodeKind& KindT, typename TokenKind,
  1022. NodeCategory::RawEnumType Category>
  1023. struct InterfaceSignature {
  1024. static constexpr auto Kind = KindT.Define(
  1025. {.category = Category, .bracketed_by = InterfaceIntroducer::Kind});
  1026. InterfaceIntroducerId introducer;
  1027. llvm::SmallVector<AnyModifierId> modifiers;
  1028. DeclName name;
  1029. TokenKind token;
  1030. };
  1031. // `interface I;`
  1032. using InterfaceDecl =
  1033. InterfaceSignature<NodeKind::InterfaceDecl, Lex::SemiTokenIndex,
  1034. NodeCategory::Decl>;
  1035. // `interface I {`
  1036. using InterfaceDefinitionStart =
  1037. InterfaceSignature<NodeKind::InterfaceDefinitionStart,
  1038. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  1039. // `interface I { ... }`
  1040. struct InterfaceDefinition {
  1041. static constexpr auto Kind = NodeKind::InterfaceDefinition.Define(
  1042. {.category = NodeCategory::Decl,
  1043. .bracketed_by = InterfaceDefinitionStart::Kind});
  1044. InterfaceDefinitionStartId signature;
  1045. llvm::SmallVector<AnyDeclId> members;
  1046. Lex::CloseCurlyBraceTokenIndex token;
  1047. };
  1048. // `impl`...`as` declarations and definitions
  1049. // ------------------------------------------
  1050. // `impl`
  1051. using ImplIntroducer = LeafNode<NodeKind::ImplIntroducer, Lex::ImplTokenIndex>;
  1052. // `forall [...]`
  1053. struct ImplForall {
  1054. static constexpr auto Kind = NodeKind::ImplForall.Define({.child_count = 1});
  1055. Lex::ForallTokenIndex token;
  1056. ImplicitParamListId params;
  1057. };
  1058. // `as` with no type before it
  1059. using DefaultSelfImplAs = LeafNode<NodeKind::DefaultSelfImplAs,
  1060. Lex::AsTokenIndex, NodeCategory::ImplAs>;
  1061. // `<type> as`
  1062. struct TypeImplAs {
  1063. static constexpr auto Kind = NodeKind::TypeImplAs.Define(
  1064. {.category = NodeCategory::ImplAs, .child_count = 1});
  1065. AnyExprId type_expr;
  1066. Lex::AsTokenIndex token;
  1067. };
  1068. // `impl T as I`
  1069. template <const NodeKind& KindT, typename TokenKind,
  1070. NodeCategory::RawEnumType Category>
  1071. struct ImplSignature {
  1072. static constexpr auto Kind = KindT.Define(
  1073. {.category = Category, .bracketed_by = ImplIntroducer::Kind});
  1074. ImplIntroducerId introducer;
  1075. llvm::SmallVector<AnyModifierId> modifiers;
  1076. std::optional<ImplForallId> forall;
  1077. AnyImplAsId as;
  1078. AnyExprId interface;
  1079. TokenKind token;
  1080. };
  1081. // `impl T as I;`
  1082. using ImplDecl =
  1083. ImplSignature<NodeKind::ImplDecl, Lex::SemiTokenIndex, NodeCategory::Decl>;
  1084. // `impl T as I {`
  1085. using ImplDefinitionStart =
  1086. ImplSignature<NodeKind::ImplDefinitionStart, Lex::OpenCurlyBraceTokenIndex,
  1087. NodeCategory::None>;
  1088. // `impl T as I { ... }`
  1089. struct ImplDefinition {
  1090. static constexpr auto Kind = NodeKind::ImplDefinition.Define(
  1091. {.category = NodeCategory::Decl,
  1092. .bracketed_by = ImplDefinitionStart::Kind});
  1093. ImplDefinitionStartId signature;
  1094. llvm::SmallVector<AnyDeclId> members;
  1095. Lex::CloseCurlyBraceTokenIndex token;
  1096. };
  1097. // Named constraint declarations and definitions
  1098. // ---------------------------------------------
  1099. // `constraint`
  1100. using NamedConstraintIntroducer =
  1101. LeafNode<NodeKind::NamedConstraintIntroducer, Lex::ConstraintTokenIndex>;
  1102. // `constraint NC`
  1103. template <const NodeKind& KindT, typename TokenKind,
  1104. NodeCategory::RawEnumType Category>
  1105. struct NamedConstraintSignature {
  1106. static constexpr auto Kind = KindT.Define(
  1107. {.category = Category, .bracketed_by = NamedConstraintIntroducer::Kind});
  1108. NamedConstraintIntroducerId introducer;
  1109. llvm::SmallVector<AnyModifierId> modifiers;
  1110. DeclName name;
  1111. TokenKind token;
  1112. };
  1113. // `constraint NC;`
  1114. using NamedConstraintDecl =
  1115. NamedConstraintSignature<NodeKind::NamedConstraintDecl, Lex::SemiTokenIndex,
  1116. NodeCategory::Decl>;
  1117. // `constraint NC {`
  1118. using NamedConstraintDefinitionStart =
  1119. NamedConstraintSignature<NodeKind::NamedConstraintDefinitionStart,
  1120. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  1121. // `constraint NC { ... }`
  1122. struct NamedConstraintDefinition {
  1123. static constexpr auto Kind = NodeKind::NamedConstraintDefinition.Define(
  1124. {.category = NodeCategory::Decl,
  1125. .bracketed_by = NamedConstraintDefinitionStart::Kind});
  1126. NamedConstraintDefinitionStartId signature;
  1127. llvm::SmallVector<AnyDeclId> members;
  1128. Lex::CloseCurlyBraceTokenIndex token;
  1129. };
  1130. // ---------------------------------------------------------------------------
  1131. // A complete source file. Note that there is no corresponding parse node for
  1132. // the file. The file is instead the complete contents of the parse tree.
  1133. struct File {
  1134. FileStartId start;
  1135. llvm::SmallVector<AnyDeclId> decls;
  1136. FileEndId end;
  1137. };
  1138. // Define `Foo` as the node type for the ID type `FooId`.
  1139. #define CARBON_PARSE_NODE_KIND(KindName) \
  1140. template <> \
  1141. struct NodeForId<KindName##Id> { \
  1142. using TypedNode = KindName; \
  1143. };
  1144. #include "toolchain/parse/node_kind.def"
  1145. } // namespace Carbon::Parse
  1146. #endif // CARBON_TOOLCHAIN_PARSE_TYPED_NODES_H_