typed_nodes.h 52 KB

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