typed_nodes.h 52 KB

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