typed_nodes.h 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  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 =
  108. LeafNode<NodeKind::EmptyDecl, Lex::SemiTokenIndex, NodeCategory::Decl>;
  109. // A name in a non-expression context, such as a declaration, that is known
  110. // to be followed by parameters.
  111. using IdentifierNameBeforeParams =
  112. LeafNode<NodeKind::IdentifierNameBeforeParams, Lex::IdentifierTokenIndex,
  113. NodeCategory::MemberName | NodeCategory::NonExprName>;
  114. using KeywordNameBeforeParams =
  115. LeafNode<NodeKind::KeywordNameBeforeParams, Lex::TokenIndex,
  116. NodeCategory::MemberName | NodeCategory::NonExprName>;
  117. // A name in a non-expression context, such as a declaration, that is known
  118. // to not be followed by parameters.
  119. using IdentifierNameNotBeforeParams =
  120. LeafNode<NodeKind::IdentifierNameNotBeforeParams, Lex::IdentifierTokenIndex,
  121. NodeCategory::MemberName | NodeCategory::NonExprName>;
  122. using KeywordNameNotBeforeParams =
  123. LeafNode<NodeKind::KeywordNameNotBeforeParams, Lex::TokenIndex,
  124. NodeCategory::MemberName | NodeCategory::NonExprName>;
  125. // A name in an expression context.
  126. using IdentifierNameExpr =
  127. LeafNode<NodeKind::IdentifierNameExpr, Lex::IdentifierTokenIndex,
  128. NodeCategory::Expr>;
  129. // The `self` value and `Self` type identifier keywords. Typically of the form
  130. // `self: Self`.
  131. using SelfValueName =
  132. LeafNode<NodeKind::SelfValueName, Lex::SelfValueIdentifierTokenIndex>;
  133. using SelfValueNameExpr =
  134. LeafNode<NodeKind::SelfValueNameExpr, Lex::SelfValueIdentifierTokenIndex,
  135. NodeCategory::Expr>;
  136. using SelfTypeNameExpr =
  137. LeafNode<NodeKind::SelfTypeNameExpr, Lex::SelfTypeIdentifierTokenIndex,
  138. NodeCategory::Expr>;
  139. // The `base` value keyword, introduced by `base: B`. Typically referenced in
  140. // an expression, as in `x.base` or `{.base = ...}`, but can also be used as a
  141. // declared name, as in `{.base: partial B}`.
  142. using BaseName =
  143. LeafNode<NodeKind::BaseName, Lex::BaseTokenIndex, NodeCategory::MemberName>;
  144. // The `_` token, when used in the name position of a binding pattern.
  145. using UnderscoreName =
  146. LeafNode<NodeKind::UnderscoreName, Lex::UnderscoreTokenIndex,
  147. NodeCategory::NonExprName>;
  148. // A name qualifier with parameters, such as `A(T:! type).` or `A[T:! type](N:!
  149. // T).`.
  150. struct IdentifierNameQualifierWithParams {
  151. static constexpr auto Kind =
  152. NodeKind::IdentifierNameQualifierWithParams.Define(
  153. {.bracketed_by = IdentifierNameBeforeParams::Kind});
  154. IdentifierNameBeforeParamsId name;
  155. std::optional<ImplicitParamListId> implicit_params;
  156. std::optional<ExplicitParamListId> params;
  157. Lex::PeriodTokenIndex token;
  158. };
  159. struct KeywordNameQualifierWithParams {
  160. static constexpr auto Kind = NodeKind::KeywordNameQualifierWithParams.Define(
  161. {.bracketed_by = KeywordNameBeforeParams::Kind});
  162. KeywordNameBeforeParamsId name;
  163. std::optional<ImplicitParamListId> implicit_params;
  164. std::optional<ExplicitParamListId> params;
  165. Lex::PeriodTokenIndex token;
  166. };
  167. // A name qualifier without parameters, such as `A.`.
  168. struct IdentifierNameQualifierWithoutParams {
  169. static constexpr auto Kind =
  170. NodeKind::IdentifierNameQualifierWithoutParams.Define(
  171. {.bracketed_by = IdentifierNameNotBeforeParams::Kind});
  172. IdentifierNameNotBeforeParamsId name;
  173. Lex::PeriodTokenIndex token;
  174. };
  175. struct KeywordNameQualifierWithoutParams {
  176. static constexpr auto Kind =
  177. NodeKind::KeywordNameQualifierWithoutParams.Define(
  178. {.bracketed_by = KeywordNameNotBeforeParams::Kind});
  179. KeywordNameNotBeforeParamsId name;
  180. Lex::PeriodTokenIndex token;
  181. };
  182. // A complete name in a declaration: `A.C(T:! type).F(n: i32)`.
  183. // Note that this includes the parameters of the entity itself.
  184. struct DeclName {
  185. llvm::SmallVector<NodeIdOneOf<
  186. IdentifierNameQualifierWithParams, IdentifierNameQualifierWithoutParams,
  187. KeywordNameQualifierWithParams, KeywordNameQualifierWithoutParams>>
  188. qualifiers;
  189. AnyNonExprNameId name;
  190. std::optional<ImplicitParamListId> implicit_params;
  191. std::optional<ExplicitParamListId> params;
  192. };
  193. // Library, package, import, export
  194. // --------------------------------
  195. // The `package` keyword in an expression.
  196. using PackageExpr =
  197. LeafNode<NodeKind::PackageExpr, Lex::PackageTokenIndex, NodeCategory::Expr>;
  198. // The `Core` keyword in an expression.
  199. using CoreNameExpr =
  200. LeafNode<NodeKind::CoreNameExpr, Lex::CoreTokenIndex, NodeCategory::Expr>;
  201. // The name of a package or library for `package`, `import`, and `library`.
  202. using IdentifierPackageName =
  203. LeafNode<NodeKind::IdentifierPackageName, Lex::IdentifierTokenIndex,
  204. NodeCategory::PackageName>;
  205. using CorePackageName = LeafNode<NodeKind::CorePackageName, Lex::CoreTokenIndex,
  206. NodeCategory::PackageName>;
  207. using LibraryName =
  208. LeafNode<NodeKind::LibraryName, Lex::StringLiteralTokenIndex>;
  209. using DefaultLibrary =
  210. LeafNode<NodeKind::DefaultLibrary, Lex::DefaultTokenIndex>;
  211. using PackageIntroducer =
  212. LeafNode<NodeKind::PackageIntroducer, Lex::PackageTokenIndex>;
  213. // `library` in `package` or `import`.
  214. struct LibrarySpecifier {
  215. static constexpr auto Kind =
  216. NodeKind::LibrarySpecifier.Define({.child_count = 1});
  217. Lex::LibraryTokenIndex token;
  218. NodeIdOneOf<LibraryName, DefaultLibrary> name;
  219. };
  220. // First line of the file, such as:
  221. // `impl package MyPackage library "MyLibrary";`
  222. struct PackageDecl {
  223. static constexpr auto Kind =
  224. NodeKind::PackageDecl.Define({.category = NodeCategory::Decl,
  225. .bracketed_by = PackageIntroducer::Kind});
  226. PackageIntroducerId introducer;
  227. llvm::SmallVector<AnyModifierId> modifiers;
  228. AnyPackageNameId name;
  229. std::optional<LibrarySpecifierId> library;
  230. Lex::SemiTokenIndex token;
  231. };
  232. // `import TheirPackage library "TheirLibrary";`
  233. using ImportIntroducer =
  234. LeafNode<NodeKind::ImportIntroducer, Lex::ImportTokenIndex>;
  235. struct ImportDecl {
  236. static constexpr auto Kind = NodeKind::ImportDecl.Define(
  237. {.category = NodeCategory::Decl, .bracketed_by = ImportIntroducer::Kind});
  238. ImportIntroducerId introducer;
  239. llvm::SmallVector<AnyModifierId> modifiers;
  240. std::optional<AnyPackageNameId> name;
  241. std::optional<LibrarySpecifierId> library;
  242. Lex::SemiTokenIndex token;
  243. };
  244. // `library` as declaration.
  245. using LibraryIntroducer =
  246. LeafNode<NodeKind::LibraryIntroducer, Lex::LibraryTokenIndex>;
  247. struct LibraryDecl {
  248. static constexpr auto Kind =
  249. NodeKind::LibraryDecl.Define({.category = NodeCategory::Decl,
  250. .bracketed_by = LibraryIntroducer::Kind});
  251. LibraryIntroducerId introducer;
  252. llvm::SmallVector<AnyModifierId> modifiers;
  253. NodeIdOneOf<LibraryName, DefaultLibrary> library_name;
  254. Lex::SemiTokenIndex token;
  255. };
  256. // `export` as a declaration.
  257. using ExportIntroducer =
  258. LeafNode<NodeKind::ExportIntroducer, Lex::ExportTokenIndex>;
  259. struct ExportDecl {
  260. static constexpr auto Kind = NodeKind::ExportDecl.Define(
  261. {.category = NodeCategory::Decl, .bracketed_by = ExportIntroducer::Kind});
  262. ExportIntroducerId introducer;
  263. llvm::SmallVector<AnyModifierId> modifiers;
  264. DeclName name;
  265. Lex::SemiTokenIndex token;
  266. };
  267. // Namespace nodes
  268. // ---------------
  269. using NamespaceStart =
  270. LeafNode<NodeKind::NamespaceStart, Lex::NamespaceTokenIndex>;
  271. // A namespace: `namespace N;`.
  272. struct Namespace {
  273. static constexpr auto Kind = NodeKind::Namespace.Define(
  274. {.category = NodeCategory::Decl, .bracketed_by = NamespaceStart::Kind});
  275. NamespaceStartId introducer;
  276. llvm::SmallVector<AnyModifierId> modifiers;
  277. DeclName name;
  278. Lex::SemiTokenIndex token;
  279. };
  280. // Pattern nodes
  281. // -------------
  282. // A pattern binding, such as `name: Type`, that isn't inside a `var` pattern.
  283. struct LetBindingPattern {
  284. static constexpr auto Kind = NodeKind::LetBindingPattern.Define(
  285. {.category = NodeCategory::Pattern, .child_count = 2});
  286. AnyRuntimeBindingPatternName name;
  287. Lex::ColonTokenIndex token;
  288. AnyExprId type;
  289. };
  290. // A pattern binding, such as `name: Type`, that is inside a `var` pattern.
  291. struct VarBindingPattern {
  292. static constexpr auto Kind = NodeKind::VarBindingPattern.Define(
  293. {.category = NodeCategory::Pattern, .child_count = 2});
  294. AnyRuntimeBindingPatternName name;
  295. Lex::ColonTokenIndex token;
  296. AnyExprId type;
  297. };
  298. // A template binding name: `template T`.
  299. struct TemplateBindingName {
  300. static constexpr auto Kind =
  301. NodeKind::TemplateBindingName.Define({.child_count = 1});
  302. Lex::TemplateTokenIndex token;
  303. AnyRuntimeBindingPatternName name;
  304. };
  305. // `name:! Type`
  306. struct CompileTimeBindingPattern {
  307. static constexpr auto Kind = NodeKind::CompileTimeBindingPattern.Define(
  308. {.category = NodeCategory::Pattern, .child_count = 2});
  309. // TODO: is there some way to reuse AnyRuntimeBindingPatternName here?
  310. NodeIdOneOf<IdentifierNameNotBeforeParams, SelfValueName, UnderscoreName,
  311. TemplateBindingName>
  312. name;
  313. Lex::ColonExclaimTokenIndex token;
  314. AnyExprId type;
  315. };
  316. // An address-of binding: `addr self: Self*`.
  317. struct Addr {
  318. static constexpr auto Kind = NodeKind::Addr.Define(
  319. {.category = NodeCategory::Pattern, .child_count = 1});
  320. Lex::AddrTokenIndex token;
  321. AnyPatternId inner;
  322. };
  323. using TuplePatternStart =
  324. LeafNode<NodeKind::TuplePatternStart, Lex::OpenParenTokenIndex>;
  325. using PatternListComma =
  326. LeafNode<NodeKind::PatternListComma, Lex::CommaTokenIndex>;
  327. // A tuple pattern that isn't an explicit parameter list: `(a: i32, b: i32)`.
  328. struct TuplePattern {
  329. static constexpr auto Kind =
  330. NodeKind::TuplePattern.Define({.category = NodeCategory::Pattern,
  331. .bracketed_by = TuplePatternStart::Kind});
  332. TuplePatternStartId left_paren;
  333. CommaSeparatedList<AnyPatternId, PatternListCommaId> params;
  334. Lex::CloseParenTokenIndex token;
  335. };
  336. using ExplicitParamListStart =
  337. LeafNode<NodeKind::ExplicitParamListStart, Lex::OpenParenTokenIndex>;
  338. // An explicit parameter list: `(a: i32, b: i32)`.
  339. struct ExplicitParamList {
  340. static constexpr auto Kind = NodeKind::ExplicitParamList.Define(
  341. {.bracketed_by = ExplicitParamListStart::Kind});
  342. ExplicitParamListStartId left_paren;
  343. CommaSeparatedList<AnyPatternId, PatternListCommaId> params;
  344. Lex::CloseParenTokenIndex token;
  345. };
  346. using ImplicitParamListStart = LeafNode<NodeKind::ImplicitParamListStart,
  347. Lex::OpenSquareBracketTokenIndex>;
  348. // An implicit parameter list: `[T:! type, self: Self]`.
  349. struct ImplicitParamList {
  350. static constexpr auto Kind = NodeKind::ImplicitParamList.Define(
  351. {.bracketed_by = ImplicitParamListStart::Kind});
  352. ImplicitParamListStartId left_square;
  353. CommaSeparatedList<AnyPatternId, PatternListCommaId> params;
  354. Lex::CloseSquareBracketTokenIndex token;
  355. };
  356. // Function nodes
  357. // --------------
  358. using FunctionIntroducer =
  359. LeafNode<NodeKind::FunctionIntroducer, Lex::FnTokenIndex>;
  360. // A return type: `-> i32`.
  361. struct ReturnType {
  362. static constexpr auto Kind = NodeKind::ReturnType.Define({.child_count = 1});
  363. Lex::MinusGreaterTokenIndex token;
  364. AnyExprId type;
  365. };
  366. // A function signature: `fn F() -> i32`.
  367. template <const NodeKind& KindT, typename TokenKind,
  368. NodeCategory::RawEnumType Category>
  369. struct FunctionSignature {
  370. static constexpr auto Kind = KindT.Define(
  371. {.category = Category, .bracketed_by = FunctionIntroducer::Kind});
  372. FunctionIntroducerId introducer;
  373. llvm::SmallVector<AnyModifierId> modifiers;
  374. DeclName name;
  375. std::optional<ReturnTypeId> return_type;
  376. TokenKind token;
  377. };
  378. using FunctionDecl = FunctionSignature<NodeKind::FunctionDecl,
  379. Lex::SemiTokenIndex, NodeCategory::Decl>;
  380. using FunctionDefinitionStart =
  381. FunctionSignature<NodeKind::FunctionDefinitionStart,
  382. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  383. // A function definition: `fn F() -> i32 { ... }`.
  384. struct FunctionDefinition {
  385. static constexpr auto Kind = NodeKind::FunctionDefinition.Define(
  386. {.category = NodeCategory::Decl,
  387. .bracketed_by = FunctionDefinitionStart::Kind});
  388. FunctionDefinitionStartId signature;
  389. llvm::SmallVector<AnyStatementId> body;
  390. Lex::CloseCurlyBraceTokenIndex token;
  391. };
  392. using BuiltinFunctionDefinitionStart =
  393. FunctionSignature<NodeKind::BuiltinFunctionDefinitionStart,
  394. Lex::EqualTokenIndex, NodeCategory::None>;
  395. using BuiltinName =
  396. LeafNode<NodeKind::BuiltinName, Lex::StringLiteralTokenIndex>;
  397. // A builtin function definition: `fn F() -> i32 = "builtin name";`
  398. struct BuiltinFunctionDefinition {
  399. static constexpr auto Kind = NodeKind::BuiltinFunctionDefinition.Define(
  400. {.category = NodeCategory::Decl,
  401. .bracketed_by = BuiltinFunctionDefinitionStart::Kind});
  402. BuiltinFunctionDefinitionStartId signature;
  403. BuiltinNameId builtin_name;
  404. Lex::SemiTokenIndex token;
  405. };
  406. // `alias` nodes
  407. // -------------
  408. using AliasIntroducer =
  409. LeafNode<NodeKind::AliasIntroducer, Lex::AliasTokenIndex>;
  410. using AliasInitializer =
  411. LeafNode<NodeKind::AliasInitializer, Lex::EqualTokenIndex>;
  412. // An `alias` declaration: `alias a = b;`.
  413. struct Alias {
  414. static constexpr auto Kind = NodeKind::Alias.Define(
  415. {.category = NodeCategory::Decl, .bracketed_by = AliasIntroducer::Kind});
  416. AliasIntroducerId introducer;
  417. llvm::SmallVector<AnyModifierId> modifiers;
  418. DeclName name;
  419. AliasInitializerId equals;
  420. AnyExprId initializer;
  421. Lex::SemiTokenIndex token;
  422. };
  423. // `let` nodes
  424. // -----------
  425. using LetIntroducer = LeafNode<NodeKind::LetIntroducer, Lex::LetTokenIndex>;
  426. using LetInitializer = LeafNode<NodeKind::LetInitializer, Lex::EqualTokenIndex>;
  427. // A `let` declaration: `let a: i32 = 5;`.
  428. struct LetDecl {
  429. static constexpr auto Kind = NodeKind::LetDecl.Define(
  430. {.category = NodeCategory::Decl, .bracketed_by = LetIntroducer::Kind});
  431. LetIntroducerId introducer;
  432. llvm::SmallVector<AnyModifierId> modifiers;
  433. AnyPatternId pattern;
  434. struct Initializer {
  435. LetInitializerId equals;
  436. AnyExprId initializer;
  437. };
  438. std::optional<Initializer> initializer;
  439. Lex::SemiTokenIndex token;
  440. };
  441. // `var` nodes
  442. // -----------
  443. using VariableIntroducer =
  444. LeafNode<NodeKind::VariableIntroducer, Lex::VarTokenIndex>;
  445. using ReturnedModifier =
  446. LeafNode<NodeKind::ReturnedModifier, Lex::ReturnedTokenIndex,
  447. NodeCategory::Modifier>;
  448. using VariableInitializer =
  449. LeafNode<NodeKind::VariableInitializer, Lex::EqualTokenIndex>;
  450. // A `var` declaration: `var a: i32;` or `var a: i32 = 5;`.
  451. struct VariableDecl {
  452. static constexpr auto Kind =
  453. NodeKind::VariableDecl.Define({.category = NodeCategory::Decl,
  454. .bracketed_by = VariableIntroducer::Kind});
  455. VariableIntroducerId introducer;
  456. llvm::SmallVector<AnyModifierId> modifiers;
  457. std::optional<ReturnedModifierId> returned;
  458. VariablePatternId pattern;
  459. struct Initializer {
  460. VariableInitializerId equals;
  461. AnyExprId value;
  462. };
  463. std::optional<Initializer> initializer;
  464. Lex::SemiTokenIndex token;
  465. };
  466. // A `var` pattern.
  467. struct VariablePattern {
  468. static constexpr auto Kind = NodeKind::VariablePattern.Define(
  469. {.category = NodeCategory::Pattern, .child_count = 1});
  470. Lex::VarTokenIndex token;
  471. AnyPatternId inner;
  472. };
  473. // Statement nodes
  474. // ---------------
  475. using CodeBlockStart =
  476. LeafNode<NodeKind::CodeBlockStart, Lex::OpenCurlyBraceTokenIndex>;
  477. // A code block: `{ statement; statement; ... }`.
  478. struct CodeBlock {
  479. static constexpr auto Kind =
  480. NodeKind::CodeBlock.Define({.bracketed_by = CodeBlockStart::Kind});
  481. CodeBlockStartId left_brace;
  482. llvm::SmallVector<AnyStatementId> statements;
  483. Lex::CloseCurlyBraceTokenIndex token;
  484. };
  485. // An expression statement: `F(x);`.
  486. struct ExprStatement {
  487. static constexpr auto Kind = NodeKind::ExprStatement.Define(
  488. {.category = NodeCategory::Statement, .child_count = 1});
  489. AnyExprId expr;
  490. Lex::SemiTokenIndex token;
  491. };
  492. using BreakStatementStart =
  493. LeafNode<NodeKind::BreakStatementStart, Lex::BreakTokenIndex>;
  494. // A break statement: `break;`.
  495. struct BreakStatement {
  496. static constexpr auto Kind = NodeKind::BreakStatement.Define(
  497. {.category = NodeCategory::Statement,
  498. .bracketed_by = BreakStatementStart::Kind,
  499. .child_count = 1});
  500. BreakStatementStartId introducer;
  501. Lex::SemiTokenIndex token;
  502. };
  503. using ContinueStatementStart =
  504. LeafNode<NodeKind::ContinueStatementStart, Lex::ContinueTokenIndex>;
  505. // A continue statement: `continue;`.
  506. struct ContinueStatement {
  507. static constexpr auto Kind = NodeKind::ContinueStatement.Define(
  508. {.category = NodeCategory::Statement,
  509. .bracketed_by = ContinueStatementStart::Kind,
  510. .child_count = 1});
  511. ContinueStatementStartId introducer;
  512. Lex::SemiTokenIndex token;
  513. };
  514. using ReturnStatementStart =
  515. LeafNode<NodeKind::ReturnStatementStart, Lex::ReturnTokenIndex>;
  516. using ReturnVarModifier = LeafNode<NodeKind::ReturnVarModifier,
  517. Lex::VarTokenIndex, NodeCategory::Modifier>;
  518. // A return statement: `return;` or `return expr;` or `return var;`.
  519. struct ReturnStatement {
  520. static constexpr auto Kind = NodeKind::ReturnStatement.Define(
  521. {.category = NodeCategory::Statement,
  522. .bracketed_by = ReturnStatementStart::Kind});
  523. ReturnStatementStartId introducer;
  524. // TODO: This should be optional<OneOf<AnyExprId, ReturnVarModifierId>>,
  525. // but we don't have support for OneOf between a node kind and a category.
  526. std::optional<AnyExprId> expr;
  527. std::optional<ReturnVarModifierId> var;
  528. Lex::SemiTokenIndex token;
  529. };
  530. using ForHeaderStart =
  531. LeafNode<NodeKind::ForHeaderStart, Lex::OpenParenTokenIndex>;
  532. // The `var ... in` portion of a `for` statement.
  533. struct ForIn {
  534. static constexpr auto Kind = NodeKind::ForIn.Define(
  535. {.bracketed_by = VariableIntroducer::Kind, .child_count = 2});
  536. VariableIntroducerId introducer;
  537. AnyPatternId pattern;
  538. Lex::InTokenIndex token;
  539. };
  540. // The `for (var ... in ...)` portion of a `for` statement.
  541. struct ForHeader {
  542. static constexpr auto Kind =
  543. NodeKind::ForHeader.Define({.bracketed_by = ForHeaderStart::Kind});
  544. ForHeaderStartId introducer;
  545. ForInId var;
  546. AnyExprId range;
  547. Lex::CloseParenTokenIndex token;
  548. };
  549. // A complete `for (...) { ... }` statement.
  550. struct ForStatement {
  551. static constexpr auto Kind =
  552. NodeKind::ForStatement.Define({.category = NodeCategory::Statement,
  553. .bracketed_by = ForHeader::Kind,
  554. .child_count = 2});
  555. Lex::ForTokenIndex token;
  556. ForHeaderId header;
  557. CodeBlockId body;
  558. };
  559. using IfConditionStart =
  560. LeafNode<NodeKind::IfConditionStart, Lex::OpenParenTokenIndex>;
  561. // The condition portion of an `if` statement: `(expr)`.
  562. struct IfCondition {
  563. static constexpr auto Kind = NodeKind::IfCondition.Define(
  564. {.bracketed_by = IfConditionStart::Kind, .child_count = 2});
  565. IfConditionStartId left_paren;
  566. AnyExprId condition;
  567. Lex::CloseParenTokenIndex token;
  568. };
  569. using IfStatementElse =
  570. LeafNode<NodeKind::IfStatementElse, Lex::ElseTokenIndex>;
  571. // An `if` statement: `if (expr) { ... } else { ... }`.
  572. struct IfStatement {
  573. static constexpr auto Kind = NodeKind::IfStatement.Define(
  574. {.category = NodeCategory::Statement, .bracketed_by = IfCondition::Kind});
  575. Lex::IfTokenIndex token;
  576. IfConditionId head;
  577. CodeBlockId then;
  578. struct Else {
  579. IfStatementElseId else_token;
  580. NodeIdOneOf<CodeBlock, IfStatement> body;
  581. };
  582. std::optional<Else> else_clause;
  583. };
  584. using WhileConditionStart =
  585. LeafNode<NodeKind::WhileConditionStart, Lex::OpenParenTokenIndex>;
  586. // The condition portion of a `while` statement: `(expr)`.
  587. struct WhileCondition {
  588. static constexpr auto Kind = NodeKind::WhileCondition.Define(
  589. {.bracketed_by = WhileConditionStart::Kind, .child_count = 2});
  590. WhileConditionStartId left_paren;
  591. AnyExprId condition;
  592. Lex::CloseParenTokenIndex token;
  593. };
  594. // A `while` statement: `while (expr) { ... }`.
  595. struct WhileStatement {
  596. static constexpr auto Kind =
  597. NodeKind::WhileStatement.Define({.category = NodeCategory::Statement,
  598. .bracketed_by = WhileCondition::Kind,
  599. .child_count = 2});
  600. Lex::WhileTokenIndex token;
  601. WhileConditionId head;
  602. CodeBlockId body;
  603. };
  604. using MatchConditionStart =
  605. LeafNode<NodeKind::MatchConditionStart, Lex::OpenParenTokenIndex>;
  606. struct MatchCondition {
  607. static constexpr auto Kind = NodeKind::MatchCondition.Define(
  608. {.bracketed_by = MatchConditionStart::Kind, .child_count = 2});
  609. MatchConditionStartId left_paren;
  610. AnyExprId condition;
  611. Lex::CloseParenTokenIndex token;
  612. };
  613. using MatchIntroducer =
  614. LeafNode<NodeKind::MatchIntroducer, Lex::MatchTokenIndex>;
  615. struct MatchStatementStart {
  616. static constexpr auto Kind = NodeKind::MatchStatementStart.Define(
  617. {.bracketed_by = MatchIntroducer::Kind, .child_count = 2});
  618. MatchIntroducerId introducer;
  619. MatchConditionId condition;
  620. Lex::OpenCurlyBraceTokenIndex token;
  621. };
  622. using MatchCaseIntroducer =
  623. LeafNode<NodeKind::MatchCaseIntroducer, Lex::CaseTokenIndex>;
  624. using MatchCaseGuardIntroducer =
  625. LeafNode<NodeKind::MatchCaseGuardIntroducer, Lex::IfTokenIndex>;
  626. using MatchCaseGuardStart =
  627. LeafNode<NodeKind::MatchCaseGuardStart, Lex::OpenParenTokenIndex>;
  628. struct MatchCaseGuard {
  629. static constexpr auto Kind = NodeKind::MatchCaseGuard.Define(
  630. {.bracketed_by = MatchCaseGuardIntroducer::Kind, .child_count = 3});
  631. MatchCaseGuardIntroducerId introducer;
  632. MatchCaseGuardStartId left_paren;
  633. AnyExprId condition;
  634. Lex::CloseParenTokenIndex token;
  635. };
  636. using MatchCaseEqualGreater =
  637. LeafNode<NodeKind::MatchCaseEqualGreater, Lex::EqualGreaterTokenIndex>;
  638. struct MatchCaseStart {
  639. static constexpr auto Kind = NodeKind::MatchCaseStart.Define(
  640. {.bracketed_by = MatchCaseIntroducer::Kind});
  641. MatchCaseIntroducerId introducer;
  642. AnyPatternId pattern;
  643. std::optional<MatchCaseGuardId> guard;
  644. MatchCaseEqualGreaterId equal_greater_token;
  645. Lex::OpenCurlyBraceTokenIndex token;
  646. };
  647. struct MatchCase {
  648. static constexpr auto Kind =
  649. NodeKind::MatchCase.Define({.bracketed_by = MatchCaseStart::Kind});
  650. MatchCaseStartId head;
  651. llvm::SmallVector<AnyStatementId> statements;
  652. Lex::CloseCurlyBraceTokenIndex token;
  653. };
  654. using MatchDefaultIntroducer =
  655. LeafNode<NodeKind::MatchDefaultIntroducer, Lex::DefaultTokenIndex>;
  656. using MatchDefaultEqualGreater =
  657. LeafNode<NodeKind::MatchDefaultEqualGreater, Lex::EqualGreaterTokenIndex>;
  658. struct MatchDefaultStart {
  659. static constexpr auto Kind = NodeKind::MatchDefaultStart.Define(
  660. {.bracketed_by = MatchDefaultIntroducer::Kind, .child_count = 2});
  661. MatchDefaultIntroducerId introducer;
  662. MatchDefaultEqualGreaterId equal_greater_token;
  663. Lex::OpenCurlyBraceTokenIndex token;
  664. };
  665. struct MatchDefault {
  666. static constexpr auto Kind =
  667. NodeKind::MatchDefault.Define({.bracketed_by = MatchDefaultStart::Kind});
  668. MatchDefaultStartId introducer;
  669. llvm::SmallVector<AnyStatementId> statements;
  670. Lex::CloseCurlyBraceTokenIndex token;
  671. };
  672. // A `match` statement: `match (expr) { case (...) => {...} default => {...}}`.
  673. struct MatchStatement {
  674. static constexpr auto Kind = NodeKind::MatchStatement.Define(
  675. {.category = NodeCategory::Statement,
  676. .bracketed_by = MatchStatementStart::Kind});
  677. MatchStatementStartId head;
  678. llvm::SmallVector<MatchCaseId> cases;
  679. std::optional<MatchDefaultId> default_case;
  680. Lex::CloseCurlyBraceTokenIndex token;
  681. };
  682. // Expression nodes
  683. // ----------------
  684. using ArrayExprKeyword =
  685. LeafNode<NodeKind::ArrayExprKeyword, Lex::ArrayTokenIndex>;
  686. using ArrayExprOpenParen =
  687. LeafNode<NodeKind::ArrayExprOpenParen, Lex::OpenParenTokenIndex>;
  688. using ArrayExprComma = LeafNode<NodeKind::ArrayExprComma, Lex::CommaTokenIndex>;
  689. // An array type, `array(T, N)`.
  690. struct ArrayExpr {
  691. static constexpr auto Kind = NodeKind::ArrayExpr.Define(
  692. {.category = NodeCategory::Expr, .child_count = 5});
  693. ArrayExprKeywordId keyword;
  694. ArrayExprOpenParenId start;
  695. AnyExprId type;
  696. ArrayExprCommaId comma;
  697. AnyExprId bound;
  698. Lex::CloseParenTokenIndex token;
  699. };
  700. // The opening portion of an indexing expression: `a[`.
  701. //
  702. // TODO: Consider flattening this into `IndexExpr`.
  703. struct IndexExprStart {
  704. static constexpr auto Kind =
  705. NodeKind::IndexExprStart.Define({.child_count = 1});
  706. AnyExprId sequence;
  707. Lex::OpenSquareBracketTokenIndex token;
  708. };
  709. // An indexing expression, such as `a[1]`.
  710. struct IndexExpr {
  711. static constexpr auto Kind =
  712. NodeKind::IndexExpr.Define({.category = NodeCategory::Expr,
  713. .bracketed_by = IndexExprStart::Kind,
  714. .child_count = 2});
  715. IndexExprStartId start;
  716. AnyExprId index;
  717. Lex::CloseSquareBracketTokenIndex token;
  718. };
  719. using ParenExprStart =
  720. LeafNode<NodeKind::ParenExprStart, Lex::OpenParenTokenIndex>;
  721. // A parenthesized expression: `(a)`.
  722. struct ParenExpr {
  723. static constexpr auto Kind = NodeKind::ParenExpr.Define(
  724. {.category = NodeCategory::Expr | NodeCategory::MemberExpr,
  725. .bracketed_by = ParenExprStart::Kind,
  726. .child_count = 2});
  727. ParenExprStartId start;
  728. AnyExprId expr;
  729. Lex::CloseParenTokenIndex token;
  730. };
  731. using TupleLiteralStart =
  732. LeafNode<NodeKind::TupleLiteralStart, Lex::OpenParenTokenIndex>;
  733. using TupleLiteralComma =
  734. LeafNode<NodeKind::TupleLiteralComma, Lex::CommaTokenIndex>;
  735. // A tuple literal: `()`, `(a, b, c)`, or `(a,)`.
  736. struct TupleLiteral {
  737. static constexpr auto Kind =
  738. NodeKind::TupleLiteral.Define({.category = NodeCategory::Expr,
  739. .bracketed_by = TupleLiteralStart::Kind});
  740. TupleLiteralStartId start;
  741. CommaSeparatedList<AnyExprId, TupleLiteralCommaId> elements;
  742. Lex::CloseParenTokenIndex token;
  743. };
  744. // The opening portion of a call expression: `F(`.
  745. //
  746. // TODO: Consider flattening this into `CallExpr`.
  747. struct CallExprStart {
  748. static constexpr auto Kind =
  749. NodeKind::CallExprStart.Define({.child_count = 1});
  750. AnyExprId callee;
  751. Lex::OpenParenTokenIndex token;
  752. };
  753. using CallExprComma = LeafNode<NodeKind::CallExprComma, Lex::CommaTokenIndex>;
  754. // A call expression: `F(a, b, c)`.
  755. struct CallExpr {
  756. static constexpr auto Kind = NodeKind::CallExpr.Define(
  757. {.category = NodeCategory::Expr, .bracketed_by = CallExprStart::Kind});
  758. CallExprStartId start;
  759. CommaSeparatedList<AnyExprId, CallExprCommaId> arguments;
  760. Lex::CloseParenTokenIndex token;
  761. };
  762. // A member access expression: `a.b` or `a.(b)`.
  763. struct MemberAccessExpr {
  764. static constexpr auto Kind = NodeKind::MemberAccessExpr.Define(
  765. {.category = NodeCategory::Expr, .child_count = 2});
  766. AnyExprId lhs;
  767. Lex::PeriodTokenIndex token;
  768. AnyMemberAccessId rhs;
  769. };
  770. // An indirect member access expression: `a->b` or `a->(b)`.
  771. struct PointerMemberAccessExpr {
  772. static constexpr auto Kind = NodeKind::PointerMemberAccessExpr.Define(
  773. {.category = NodeCategory::Expr, .child_count = 2});
  774. AnyExprId lhs;
  775. Lex::MinusGreaterTokenIndex token;
  776. AnyMemberAccessId rhs;
  777. };
  778. // A prefix operator expression.
  779. template <const NodeKind& KindT, typename TokenKind>
  780. struct PrefixOperator {
  781. static constexpr auto Kind =
  782. KindT.Define({.category = NodeCategory::Expr, .child_count = 1});
  783. TokenKind token;
  784. AnyExprId operand;
  785. };
  786. // An infix operator expression.
  787. template <const NodeKind& KindT, typename TokenKind>
  788. struct InfixOperator {
  789. static constexpr auto Kind =
  790. KindT.Define({.category = NodeCategory::Expr, .child_count = 2});
  791. AnyExprId lhs;
  792. TokenKind token;
  793. AnyExprId rhs;
  794. };
  795. // A postfix operator expression.
  796. template <const NodeKind& KindT, typename TokenKind>
  797. struct PostfixOperator {
  798. static constexpr auto Kind =
  799. KindT.Define({.category = NodeCategory::Expr, .child_count = 1});
  800. AnyExprId operand;
  801. TokenKind token;
  802. };
  803. // Literals, operators, and modifiers
  804. #define CARBON_PARSE_NODE_KIND(Name)
  805. #define CARBON_PARSE_NODE_KIND_TOKEN_LITERAL(Name, LexTokenKind) \
  806. using Name = LeafNode<NodeKind::Name, Lex::LexTokenKind##TokenIndex, \
  807. NodeCategory::Expr>;
  808. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name) \
  809. using Name##Modifier = \
  810. LeafNode<NodeKind::Name##Modifier, Lex::Name##TokenIndex, \
  811. NodeCategory::Modifier>;
  812. #define CARBON_PARSE_NODE_KIND_PREFIX_OPERATOR(Name) \
  813. using PrefixOperator##Name = \
  814. PrefixOperator<NodeKind::PrefixOperator##Name, Lex::Name##TokenIndex>;
  815. #define CARBON_PARSE_NODE_KIND_INFIX_OPERATOR(Name) \
  816. using InfixOperator##Name = \
  817. InfixOperator<NodeKind::InfixOperator##Name, Lex::Name##TokenIndex>;
  818. #define CARBON_PARSE_NODE_KIND_POSTFIX_OPERATOR(Name) \
  819. using PostfixOperator##Name = \
  820. PostfixOperator<NodeKind::PostfixOperator##Name, Lex::Name##TokenIndex>;
  821. #include "toolchain/parse/node_kind.def"
  822. using IntLiteral = LeafNode<NodeKind::IntLiteral, Lex::IntLiteralTokenIndex,
  823. NodeCategory::Expr | NodeCategory::IntConst>;
  824. // `extern` as a standalone modifier.
  825. using ExternModifier = LeafNode<NodeKind::ExternModifier, Lex::ExternTokenIndex,
  826. NodeCategory::Modifier>;
  827. // `extern library <owning_library>` modifiers.
  828. struct ExternModifierWithLibrary {
  829. static constexpr auto Kind = NodeKind::ExternModifierWithLibrary.Define(
  830. {.category = NodeCategory::Modifier, .child_count = 1});
  831. Lex::ExternTokenIndex token;
  832. LibrarySpecifierId library;
  833. };
  834. // The first operand of a short-circuiting infix operator: `a and` or `a or`.
  835. // The complete operator expression will be an InfixOperator with this as the
  836. // `lhs`.
  837. // TODO: Make this be a template if we ever need to write generic code to cover
  838. // both cases at once, say in check.
  839. struct ShortCircuitOperandAnd {
  840. static constexpr auto Kind =
  841. NodeKind::ShortCircuitOperandAnd.Define({.child_count = 1});
  842. AnyExprId operand;
  843. // This is a virtual token. The `and` token is owned by the
  844. // ShortCircuitOperatorAnd node.
  845. Lex::AndTokenIndex token;
  846. };
  847. struct ShortCircuitOperandOr {
  848. static constexpr auto Kind =
  849. NodeKind::ShortCircuitOperandOr.Define({.child_count = 1});
  850. AnyExprId operand;
  851. // This is a virtual token. The `or` token is owned by the
  852. // ShortCircuitOperatorOr node.
  853. Lex::OrTokenIndex token;
  854. };
  855. struct ShortCircuitOperatorAnd {
  856. static constexpr auto Kind = NodeKind::ShortCircuitOperatorAnd.Define(
  857. {.category = NodeCategory::Expr,
  858. .bracketed_by = ShortCircuitOperandAnd::Kind,
  859. .child_count = 2});
  860. ShortCircuitOperandAndId lhs;
  861. Lex::AndTokenIndex token;
  862. AnyExprId rhs;
  863. };
  864. struct ShortCircuitOperatorOr {
  865. static constexpr auto Kind = NodeKind::ShortCircuitOperatorOr.Define(
  866. {.category = NodeCategory::Expr,
  867. .bracketed_by = ShortCircuitOperandOr::Kind,
  868. .child_count = 2});
  869. ShortCircuitOperandOrId lhs;
  870. Lex::OrTokenIndex token;
  871. AnyExprId rhs;
  872. };
  873. // The `if` portion of an `if` expression: `if expr`.
  874. struct IfExprIf {
  875. static constexpr auto Kind = NodeKind::IfExprIf.Define({.child_count = 1});
  876. Lex::IfTokenIndex token;
  877. AnyExprId condition;
  878. };
  879. // The `then` portion of an `if` expression: `then expr`.
  880. struct IfExprThen {
  881. static constexpr auto Kind = NodeKind::IfExprThen.Define({.child_count = 1});
  882. Lex::ThenTokenIndex token;
  883. AnyExprId result;
  884. };
  885. // A full `if` expression: `if expr then expr else expr`.
  886. struct IfExprElse {
  887. static constexpr auto Kind =
  888. NodeKind::IfExprElse.Define({.category = NodeCategory::Expr,
  889. .bracketed_by = IfExprIf::Kind,
  890. .child_count = 3});
  891. IfExprIfId start;
  892. IfExprThenId then;
  893. Lex::ElseTokenIndex token;
  894. AnyExprId else_result;
  895. };
  896. // A `where` expression (TODO: `require` and `observe` declarations)
  897. // The `Self` in a context where it is treated as a name rather than an
  898. // expression, such as `.Self`.
  899. using SelfTypeName =
  900. LeafNode<NodeKind::SelfTypeName, Lex::SelfTypeIdentifierTokenIndex>;
  901. // `.Member` or `.Self` in an expression context, used in `where` and `require`
  902. // clauses.
  903. // TODO: Do we want to support `.1`, a designator for accessing a tuple member?
  904. struct DesignatorExpr {
  905. static constexpr auto Kind = NodeKind::DesignatorExpr.Define(
  906. {.category = NodeCategory::Expr, .child_count = 1});
  907. Lex::PeriodTokenIndex token;
  908. NodeIdOneOf<IdentifierNameNotBeforeParams, SelfTypeName> name;
  909. };
  910. struct RequirementEqual {
  911. static constexpr auto Kind = NodeKind::RequirementEqual.Define(
  912. {.category = NodeCategory::Requirement, .child_count = 2});
  913. DesignatorExprId lhs;
  914. Lex::EqualTokenIndex token;
  915. AnyExprId rhs;
  916. };
  917. struct RequirementEqualEqual {
  918. static constexpr auto Kind = NodeKind::RequirementEqualEqual.Define(
  919. {.category = NodeCategory::Requirement, .child_count = 2});
  920. AnyExprId lhs;
  921. Lex::EqualEqualTokenIndex token;
  922. AnyExprId rhs;
  923. };
  924. struct RequirementImpls {
  925. static constexpr auto Kind = NodeKind::RequirementImpls.Define(
  926. {.category = NodeCategory::Requirement, .child_count = 2});
  927. AnyExprId lhs;
  928. Lex::ImplsTokenIndex token;
  929. AnyExprId rhs;
  930. };
  931. // An `and` token separating requirements in a `where` expression.
  932. using RequirementAnd = LeafNode<NodeKind::RequirementAnd, Lex::AndTokenIndex>;
  933. struct WhereOperand {
  934. static constexpr auto Kind =
  935. NodeKind::WhereOperand.Define({.child_count = 1});
  936. AnyExprId type;
  937. // This is a virtual token. The `where` token is owned by the
  938. // WhereExpr node.
  939. Lex::WhereTokenIndex token;
  940. };
  941. struct WhereExpr {
  942. static constexpr auto Kind = NodeKind::WhereExpr.Define(
  943. {.category = NodeCategory::Expr, .bracketed_by = WhereOperand::Kind});
  944. WhereOperandId introducer;
  945. Lex::WhereTokenIndex token;
  946. CommaSeparatedList<AnyRequirementId, RequirementAndId> requirements;
  947. };
  948. // Choice nodes
  949. // ------------
  950. using ChoiceIntroducer =
  951. LeafNode<NodeKind::ChoiceIntroducer, Lex::ChoiceTokenIndex>;
  952. struct ChoiceSignature {
  953. static constexpr auto Kind = NodeKind::ChoiceDefinitionStart.Define(
  954. {.category = NodeCategory::None, .bracketed_by = ChoiceIntroducer::Kind});
  955. ChoiceIntroducerId introducer;
  956. llvm::SmallVector<AnyModifierId> modifiers;
  957. DeclName name;
  958. Lex::OpenCurlyBraceTokenIndex token;
  959. };
  960. using ChoiceDefinitionStart = ChoiceSignature;
  961. using ChoiceAlternativeListComma =
  962. LeafNode<NodeKind::ChoiceAlternativeListComma, Lex::CommaTokenIndex>;
  963. struct ChoiceDefinition {
  964. static constexpr auto Kind = NodeKind::ChoiceDefinition.Define(
  965. {.category = NodeCategory::Decl,
  966. .bracketed_by = ChoiceDefinitionStart::Kind});
  967. ChoiceDefinitionStartId signature;
  968. struct Alternative {
  969. AnyNonExprNameId name;
  970. std::optional<ExplicitParamListId> parameters;
  971. };
  972. CommaSeparatedList<Alternative, ChoiceAlternativeListCommaId> alternatives;
  973. Lex::CloseCurlyBraceTokenIndex token;
  974. };
  975. // Struct type and value literals
  976. // ----------------------------------------
  977. // `{`
  978. using StructLiteralStart =
  979. LeafNode<NodeKind::StructLiteralStart, Lex::OpenCurlyBraceTokenIndex>;
  980. using StructTypeLiteralStart =
  981. LeafNode<NodeKind::StructTypeLiteralStart, Lex::OpenCurlyBraceTokenIndex>;
  982. // `,`
  983. using StructLiteralComma =
  984. LeafNode<NodeKind::StructLiteralComma, Lex::CommaTokenIndex>;
  985. using StructTypeLiteralComma =
  986. LeafNode<NodeKind::StructTypeLiteralComma, Lex::CommaTokenIndex>;
  987. // `.a`
  988. // This is shared for struct literals and type literals in order to reduce
  989. // lookahead for parse (the `=` versus `:` would require lookahead of 2).
  990. struct StructFieldDesignator {
  991. static constexpr auto Kind =
  992. NodeKind::StructFieldDesignator.Define({.child_count = 1});
  993. Lex::PeriodTokenIndex token;
  994. NodeIdOneOf<IdentifierNameNotBeforeParams, BaseName> name;
  995. };
  996. // `.a = 0`
  997. struct StructLiteralField {
  998. static constexpr auto Kind = NodeKind::StructLiteralField.Define(
  999. {.bracketed_by = StructFieldDesignator::Kind, .child_count = 2});
  1000. StructFieldDesignatorId designator;
  1001. Lex::EqualTokenIndex token;
  1002. AnyExprId expr;
  1003. };
  1004. // `.a: i32`
  1005. struct StructTypeLiteralField {
  1006. static constexpr auto Kind = NodeKind::StructTypeLiteralField.Define(
  1007. {.bracketed_by = StructFieldDesignator::Kind, .child_count = 2});
  1008. StructFieldDesignatorId designator;
  1009. Lex::ColonTokenIndex token;
  1010. AnyExprId type_expr;
  1011. };
  1012. // Struct literals, such as `{.a = 0}`.
  1013. struct StructLiteral {
  1014. static constexpr auto Kind = NodeKind::StructLiteral.Define(
  1015. {.category = NodeCategory::Expr,
  1016. .bracketed_by = StructLiteralStart::Kind});
  1017. StructLiteralStartId start;
  1018. CommaSeparatedList<StructLiteralFieldId, StructLiteralCommaId> fields;
  1019. Lex::CloseCurlyBraceTokenIndex token;
  1020. };
  1021. // Struct type literals, such as `{.a: i32}`.
  1022. struct StructTypeLiteral {
  1023. static constexpr auto Kind = NodeKind::StructTypeLiteral.Define(
  1024. {.category = NodeCategory::Expr,
  1025. .bracketed_by = StructTypeLiteralStart::Kind});
  1026. StructTypeLiteralStartId start;
  1027. CommaSeparatedList<StructTypeLiteralFieldId, StructTypeLiteralCommaId> fields;
  1028. Lex::CloseCurlyBraceTokenIndex token;
  1029. };
  1030. // `class` declarations and definitions
  1031. // ------------------------------------
  1032. // `class`
  1033. using ClassIntroducer =
  1034. LeafNode<NodeKind::ClassIntroducer, Lex::ClassTokenIndex>;
  1035. // A class signature `class C`
  1036. template <const NodeKind& KindT, typename TokenKind,
  1037. NodeCategory::RawEnumType Category>
  1038. struct ClassSignature {
  1039. static constexpr auto Kind = KindT.Define(
  1040. {.category = Category, .bracketed_by = ClassIntroducer::Kind});
  1041. ClassIntroducerId introducer;
  1042. llvm::SmallVector<AnyModifierId> modifiers;
  1043. DeclName name;
  1044. TokenKind token;
  1045. };
  1046. // `class C;`
  1047. using ClassDecl = ClassSignature<NodeKind::ClassDecl, Lex::SemiTokenIndex,
  1048. NodeCategory::Decl>;
  1049. // `class C {`
  1050. using ClassDefinitionStart =
  1051. ClassSignature<NodeKind::ClassDefinitionStart,
  1052. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  1053. // `class C { ... }`
  1054. struct ClassDefinition {
  1055. static constexpr auto Kind = NodeKind::ClassDefinition.Define(
  1056. {.category = NodeCategory::Decl,
  1057. .bracketed_by = ClassDefinitionStart::Kind});
  1058. ClassDefinitionStartId signature;
  1059. llvm::SmallVector<AnyDeclId> members;
  1060. Lex::CloseCurlyBraceTokenIndex token;
  1061. };
  1062. // Adapter declaration
  1063. // -------------------
  1064. // `adapt`
  1065. using AdaptIntroducer =
  1066. LeafNode<NodeKind::AdaptIntroducer, Lex::AdaptTokenIndex>;
  1067. // `adapt SomeType;`
  1068. struct AdaptDecl {
  1069. static constexpr auto Kind = NodeKind::AdaptDecl.Define(
  1070. {.category = NodeCategory::Decl, .bracketed_by = AdaptIntroducer::Kind});
  1071. AdaptIntroducerId introducer;
  1072. llvm::SmallVector<AnyModifierId> modifiers;
  1073. AnyExprId adapted_type;
  1074. Lex::SemiTokenIndex token;
  1075. };
  1076. // Base class declaration
  1077. // ----------------------
  1078. // `base`
  1079. using BaseIntroducer = LeafNode<NodeKind::BaseIntroducer, Lex::BaseTokenIndex>;
  1080. using BaseColon = LeafNode<NodeKind::BaseColon, Lex::ColonTokenIndex>;
  1081. // `extend base: BaseClass;`
  1082. struct BaseDecl {
  1083. static constexpr auto Kind = NodeKind::BaseDecl.Define(
  1084. {.category = NodeCategory::Decl, .bracketed_by = BaseIntroducer::Kind});
  1085. BaseIntroducerId introducer;
  1086. llvm::SmallVector<AnyModifierId> modifiers;
  1087. BaseColonId colon;
  1088. AnyExprId base_class;
  1089. Lex::SemiTokenIndex token;
  1090. };
  1091. // Interface declarations and definitions
  1092. // --------------------------------------
  1093. // `interface`
  1094. using InterfaceIntroducer =
  1095. LeafNode<NodeKind::InterfaceIntroducer, Lex::InterfaceTokenIndex>;
  1096. // `interface I`
  1097. template <const NodeKind& KindT, typename TokenKind,
  1098. NodeCategory::RawEnumType Category>
  1099. struct InterfaceSignature {
  1100. static constexpr auto Kind = KindT.Define(
  1101. {.category = Category, .bracketed_by = InterfaceIntroducer::Kind});
  1102. InterfaceIntroducerId introducer;
  1103. llvm::SmallVector<AnyModifierId> modifiers;
  1104. DeclName name;
  1105. TokenKind token;
  1106. };
  1107. // `interface I;`
  1108. using InterfaceDecl =
  1109. InterfaceSignature<NodeKind::InterfaceDecl, Lex::SemiTokenIndex,
  1110. NodeCategory::Decl>;
  1111. // `interface I {`
  1112. using InterfaceDefinitionStart =
  1113. InterfaceSignature<NodeKind::InterfaceDefinitionStart,
  1114. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  1115. // `interface I { ... }`
  1116. struct InterfaceDefinition {
  1117. static constexpr auto Kind = NodeKind::InterfaceDefinition.Define(
  1118. {.category = NodeCategory::Decl,
  1119. .bracketed_by = InterfaceDefinitionStart::Kind});
  1120. InterfaceDefinitionStartId signature;
  1121. llvm::SmallVector<AnyDeclId> members;
  1122. Lex::CloseCurlyBraceTokenIndex token;
  1123. };
  1124. // `impl`...`as` declarations and definitions
  1125. // ------------------------------------------
  1126. // `impl`
  1127. using ImplIntroducer = LeafNode<NodeKind::ImplIntroducer, Lex::ImplTokenIndex>;
  1128. // `forall`
  1129. using Forall = LeafNode<NodeKind::Forall, Lex::ForallTokenIndex>;
  1130. // `forall [...]`
  1131. struct ImplForall {
  1132. ForallId forall;
  1133. ImplicitParamListId params;
  1134. };
  1135. // `as` with no type before it
  1136. using DefaultSelfImplAs = LeafNode<NodeKind::DefaultSelfImplAs,
  1137. Lex::AsTokenIndex, NodeCategory::ImplAs>;
  1138. // `<type> as`
  1139. struct TypeImplAs {
  1140. static constexpr auto Kind = NodeKind::TypeImplAs.Define(
  1141. {.category = NodeCategory::ImplAs, .child_count = 1});
  1142. AnyExprId type_expr;
  1143. Lex::AsTokenIndex token;
  1144. };
  1145. // `impl T as I`
  1146. template <const NodeKind& KindT, typename TokenKind,
  1147. NodeCategory::RawEnumType Category>
  1148. struct ImplSignature {
  1149. static constexpr auto Kind = KindT.Define(
  1150. {.category = Category, .bracketed_by = ImplIntroducer::Kind});
  1151. ImplIntroducerId introducer;
  1152. llvm::SmallVector<AnyModifierId> modifiers;
  1153. std::optional<ImplForall> forall;
  1154. AnyImplAsId as;
  1155. AnyExprId interface;
  1156. TokenKind token;
  1157. };
  1158. // `impl T as I;`
  1159. using ImplDecl =
  1160. ImplSignature<NodeKind::ImplDecl, Lex::SemiTokenIndex, NodeCategory::Decl>;
  1161. // `impl T as I {`
  1162. using ImplDefinitionStart =
  1163. ImplSignature<NodeKind::ImplDefinitionStart, Lex::OpenCurlyBraceTokenIndex,
  1164. NodeCategory::None>;
  1165. // `impl T as I { ... }`
  1166. struct ImplDefinition {
  1167. static constexpr auto Kind = NodeKind::ImplDefinition.Define(
  1168. {.category = NodeCategory::Decl,
  1169. .bracketed_by = ImplDefinitionStart::Kind});
  1170. ImplDefinitionStartId signature;
  1171. llvm::SmallVector<AnyDeclId> members;
  1172. Lex::CloseCurlyBraceTokenIndex token;
  1173. };
  1174. // Named constraint declarations and definitions
  1175. // ---------------------------------------------
  1176. // `constraint`
  1177. using NamedConstraintIntroducer =
  1178. LeafNode<NodeKind::NamedConstraintIntroducer, Lex::ConstraintTokenIndex>;
  1179. // `constraint NC`
  1180. template <const NodeKind& KindT, typename TokenKind,
  1181. NodeCategory::RawEnumType Category>
  1182. struct NamedConstraintSignature {
  1183. static constexpr auto Kind = KindT.Define(
  1184. {.category = Category, .bracketed_by = NamedConstraintIntroducer::Kind});
  1185. NamedConstraintIntroducerId introducer;
  1186. llvm::SmallVector<AnyModifierId> modifiers;
  1187. DeclName name;
  1188. TokenKind token;
  1189. };
  1190. // `constraint NC;`
  1191. using NamedConstraintDecl =
  1192. NamedConstraintSignature<NodeKind::NamedConstraintDecl, Lex::SemiTokenIndex,
  1193. NodeCategory::Decl>;
  1194. // `constraint NC {`
  1195. using NamedConstraintDefinitionStart =
  1196. NamedConstraintSignature<NodeKind::NamedConstraintDefinitionStart,
  1197. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  1198. // `constraint NC { ... }`
  1199. struct NamedConstraintDefinition {
  1200. static constexpr auto Kind = NodeKind::NamedConstraintDefinition.Define(
  1201. {.category = NodeCategory::Decl,
  1202. .bracketed_by = NamedConstraintDefinitionStart::Kind});
  1203. NamedConstraintDefinitionStartId signature;
  1204. llvm::SmallVector<AnyDeclId> members;
  1205. Lex::CloseCurlyBraceTokenIndex token;
  1206. };
  1207. // ---------------------------------------------------------------------------
  1208. // A complete source file. Note that there is no corresponding parse node for
  1209. // the file. The file is instead the complete contents of the parse tree.
  1210. struct File {
  1211. FileStartId start;
  1212. llvm::SmallVector<AnyDeclId> decls;
  1213. FileEndId end;
  1214. };
  1215. // Define `Foo` as the node type for the ID type `FooId`.
  1216. #define CARBON_PARSE_NODE_KIND(KindName) \
  1217. template <> \
  1218. struct NodeForId<KindName##Id> { \
  1219. using TypedNode = KindName; \
  1220. };
  1221. #include "toolchain/parse/node_kind.def"
  1222. } // namespace Carbon::Parse
  1223. #endif // CARBON_TOOLCHAIN_PARSE_TYPED_NODES_H_