typed_nodes.h 48 KB

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