typed_nodes.h 52 KB

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