typed_nodes.h 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562
  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. // `var` nodes
  460. // -----------
  461. using VariableIntroducer =
  462. LeafNode<NodeKind::VariableIntroducer, Lex::VarTokenIndex>;
  463. using ReturnedModifier =
  464. LeafNode<NodeKind::ReturnedModifier, Lex::ReturnedTokenIndex,
  465. NodeCategory::Modifier>;
  466. using VariableInitializer =
  467. LeafNode<NodeKind::VariableInitializer, Lex::EqualTokenIndex>;
  468. // A `var` declaration: `var a: i32;` or `var a: i32 = 5;`.
  469. struct VariableDecl {
  470. static constexpr auto Kind =
  471. NodeKind::VariableDecl.Define({.category = NodeCategory::Decl,
  472. .bracketed_by = VariableIntroducer::Kind});
  473. VariableIntroducerId introducer;
  474. llvm::SmallVector<AnyModifierId> modifiers;
  475. std::optional<ReturnedModifierId> returned;
  476. VariablePatternId pattern;
  477. struct Initializer {
  478. VariableInitializerId equals;
  479. AnyExprId value;
  480. };
  481. std::optional<Initializer> initializer;
  482. Lex::SemiTokenIndex token;
  483. };
  484. using FieldIntroducer = LeafNode<NodeKind::FieldIntroducer, Lex::VarTokenIndex>;
  485. using FieldInitializer =
  486. LeafNode<NodeKind::FieldInitializer, Lex::EqualTokenIndex>;
  487. struct FieldNameAndType {
  488. static constexpr auto Kind =
  489. NodeKind::FieldNameAndType.Define({.child_count = 2});
  490. IdentifierNameNotBeforeParamsId name;
  491. Lex::ColonTokenIndex token;
  492. AnyExprId type;
  493. };
  494. struct FieldDecl {
  495. static constexpr auto Kind = NodeKind::FieldDecl.Define(
  496. {.category = NodeCategory::Decl, .bracketed_by = FieldIntroducer::Kind});
  497. FieldIntroducerId introducer;
  498. llvm::SmallVector<AnyModifierId> modifiers;
  499. FieldNameAndTypeId name_and_type;
  500. struct Initializer {
  501. FieldInitializerId equals;
  502. AnyExprId value;
  503. };
  504. std::optional<Initializer> initializer;
  505. Lex::SemiTokenIndex token;
  506. };
  507. // A `var` pattern.
  508. struct VariablePattern {
  509. static constexpr auto Kind = NodeKind::VariablePattern.Define(
  510. {.category = NodeCategory::Pattern, .child_count = 1});
  511. Lex::VarTokenIndex token;
  512. AnyPatternId inner;
  513. };
  514. // Statement nodes
  515. // ---------------
  516. using CodeBlockStart =
  517. LeafNode<NodeKind::CodeBlockStart, Lex::OpenCurlyBraceTokenIndex>;
  518. // A code block: `{ statement; statement; ... }`.
  519. struct CodeBlock {
  520. static constexpr auto Kind =
  521. NodeKind::CodeBlock.Define({.bracketed_by = CodeBlockStart::Kind});
  522. CodeBlockStartId left_brace;
  523. llvm::SmallVector<AnyStatementId> statements;
  524. Lex::CloseCurlyBraceTokenIndex token;
  525. };
  526. // An expression statement: `F(x);`.
  527. struct ExprStatement {
  528. static constexpr auto Kind = NodeKind::ExprStatement.Define(
  529. {.category = NodeCategory::Statement, .child_count = 1});
  530. AnyExprId expr;
  531. Lex::SemiTokenIndex token;
  532. };
  533. using BreakStatementStart =
  534. LeafNode<NodeKind::BreakStatementStart, Lex::BreakTokenIndex>;
  535. // A break statement: `break;`.
  536. struct BreakStatement {
  537. static constexpr auto Kind = NodeKind::BreakStatement.Define(
  538. {.category = NodeCategory::Statement,
  539. .bracketed_by = BreakStatementStart::Kind,
  540. .child_count = 1});
  541. BreakStatementStartId introducer;
  542. Lex::SemiTokenIndex token;
  543. };
  544. using ContinueStatementStart =
  545. LeafNode<NodeKind::ContinueStatementStart, Lex::ContinueTokenIndex>;
  546. // A continue statement: `continue;`.
  547. struct ContinueStatement {
  548. static constexpr auto Kind = NodeKind::ContinueStatement.Define(
  549. {.category = NodeCategory::Statement,
  550. .bracketed_by = ContinueStatementStart::Kind,
  551. .child_count = 1});
  552. ContinueStatementStartId introducer;
  553. Lex::SemiTokenIndex token;
  554. };
  555. using ReturnStatementStart =
  556. LeafNode<NodeKind::ReturnStatementStart, Lex::ReturnTokenIndex>;
  557. using ReturnVarModifier = LeafNode<NodeKind::ReturnVarModifier,
  558. Lex::VarTokenIndex, NodeCategory::Modifier>;
  559. // A return statement: `return;` or `return expr;` or `return var;`.
  560. struct ReturnStatement {
  561. static constexpr auto Kind = NodeKind::ReturnStatement.Define(
  562. {.category = NodeCategory::Statement,
  563. .bracketed_by = ReturnStatementStart::Kind});
  564. ReturnStatementStartId introducer;
  565. // TODO: This should be optional<OneOf<AnyExprId, ReturnVarModifierId>>,
  566. // but we don't have support for OneOf between a node kind and a category.
  567. std::optional<AnyExprId> expr;
  568. std::optional<ReturnVarModifierId> var;
  569. Lex::SemiTokenIndex token;
  570. };
  571. using ForHeaderStart =
  572. LeafNode<NodeKind::ForHeaderStart, Lex::OpenParenTokenIndex>;
  573. // The `... in` portion of a `for` statement.
  574. struct ForIn {
  575. static constexpr auto Kind = NodeKind::ForIn.Define({.child_count = 1});
  576. AnyPatternId pattern;
  577. Lex::InTokenIndex token;
  578. };
  579. // The `(... in ...)` portion of a `for` statement.
  580. struct ForHeader {
  581. static constexpr auto Kind =
  582. NodeKind::ForHeader.Define({.bracketed_by = ForHeaderStart::Kind});
  583. ForHeaderStartId introducer;
  584. ForInId var;
  585. AnyExprId range;
  586. Lex::CloseParenTokenIndex token;
  587. };
  588. // A complete `for (...) { ... }` statement.
  589. struct ForStatement {
  590. static constexpr auto Kind =
  591. NodeKind::ForStatement.Define({.category = NodeCategory::Statement,
  592. .bracketed_by = ForHeader::Kind,
  593. .child_count = 2});
  594. Lex::ForTokenIndex token;
  595. ForHeaderId header;
  596. CodeBlockId body;
  597. };
  598. using IfConditionStart =
  599. LeafNode<NodeKind::IfConditionStart, Lex::OpenParenTokenIndex>;
  600. // The condition portion of an `if` statement: `(expr)`.
  601. struct IfCondition {
  602. static constexpr auto Kind = NodeKind::IfCondition.Define(
  603. {.bracketed_by = IfConditionStart::Kind, .child_count = 2});
  604. IfConditionStartId left_paren;
  605. AnyExprId condition;
  606. Lex::CloseParenTokenIndex token;
  607. };
  608. using IfStatementElse =
  609. LeafNode<NodeKind::IfStatementElse, Lex::ElseTokenIndex>;
  610. // An `if` statement: `if (expr) { ... } else { ... }`.
  611. struct IfStatement {
  612. static constexpr auto Kind = NodeKind::IfStatement.Define(
  613. {.category = NodeCategory::Statement, .bracketed_by = IfCondition::Kind});
  614. Lex::IfTokenIndex token;
  615. IfConditionId head;
  616. CodeBlockId then;
  617. struct Else {
  618. IfStatementElseId else_token;
  619. NodeIdOneOf<CodeBlock, IfStatement> body;
  620. };
  621. std::optional<Else> else_clause;
  622. };
  623. using WhileConditionStart =
  624. LeafNode<NodeKind::WhileConditionStart, Lex::OpenParenTokenIndex>;
  625. // The condition portion of a `while` statement: `(expr)`.
  626. struct WhileCondition {
  627. static constexpr auto Kind = NodeKind::WhileCondition.Define(
  628. {.bracketed_by = WhileConditionStart::Kind, .child_count = 2});
  629. WhileConditionStartId left_paren;
  630. AnyExprId condition;
  631. Lex::CloseParenTokenIndex token;
  632. };
  633. // A `while` statement: `while (expr) { ... }`.
  634. struct WhileStatement {
  635. static constexpr auto Kind =
  636. NodeKind::WhileStatement.Define({.category = NodeCategory::Statement,
  637. .bracketed_by = WhileCondition::Kind,
  638. .child_count = 2});
  639. Lex::WhileTokenIndex token;
  640. WhileConditionId head;
  641. CodeBlockId body;
  642. };
  643. using MatchConditionStart =
  644. LeafNode<NodeKind::MatchConditionStart, Lex::OpenParenTokenIndex>;
  645. struct MatchCondition {
  646. static constexpr auto Kind = NodeKind::MatchCondition.Define(
  647. {.bracketed_by = MatchConditionStart::Kind, .child_count = 2});
  648. MatchConditionStartId left_paren;
  649. AnyExprId condition;
  650. Lex::CloseParenTokenIndex token;
  651. };
  652. using MatchIntroducer =
  653. LeafNode<NodeKind::MatchIntroducer, Lex::MatchTokenIndex>;
  654. struct MatchStatementStart {
  655. static constexpr auto Kind = NodeKind::MatchStatementStart.Define(
  656. {.bracketed_by = MatchIntroducer::Kind, .child_count = 2});
  657. MatchIntroducerId introducer;
  658. MatchConditionId condition;
  659. Lex::OpenCurlyBraceTokenIndex token;
  660. };
  661. using MatchCaseIntroducer =
  662. LeafNode<NodeKind::MatchCaseIntroducer, Lex::CaseTokenIndex>;
  663. using MatchCaseGuardIntroducer =
  664. LeafNode<NodeKind::MatchCaseGuardIntroducer, Lex::IfTokenIndex>;
  665. using MatchCaseGuardStart =
  666. LeafNode<NodeKind::MatchCaseGuardStart, Lex::OpenParenTokenIndex>;
  667. struct MatchCaseGuard {
  668. static constexpr auto Kind = NodeKind::MatchCaseGuard.Define(
  669. {.bracketed_by = MatchCaseGuardIntroducer::Kind, .child_count = 3});
  670. MatchCaseGuardIntroducerId introducer;
  671. MatchCaseGuardStartId left_paren;
  672. AnyExprId condition;
  673. Lex::CloseParenTokenIndex token;
  674. };
  675. using MatchCaseEqualGreater =
  676. LeafNode<NodeKind::MatchCaseEqualGreater, Lex::EqualGreaterTokenIndex>;
  677. struct MatchCaseStart {
  678. static constexpr auto Kind = NodeKind::MatchCaseStart.Define(
  679. {.bracketed_by = MatchCaseIntroducer::Kind});
  680. MatchCaseIntroducerId introducer;
  681. AnyPatternId pattern;
  682. std::optional<MatchCaseGuardId> guard;
  683. MatchCaseEqualGreaterId equal_greater_token;
  684. Lex::OpenCurlyBraceTokenIndex token;
  685. };
  686. struct MatchCase {
  687. static constexpr auto Kind =
  688. NodeKind::MatchCase.Define({.bracketed_by = MatchCaseStart::Kind});
  689. MatchCaseStartId head;
  690. llvm::SmallVector<AnyStatementId> statements;
  691. Lex::CloseCurlyBraceTokenIndex token;
  692. };
  693. using MatchDefaultIntroducer =
  694. LeafNode<NodeKind::MatchDefaultIntroducer, Lex::DefaultTokenIndex>;
  695. using MatchDefaultEqualGreater =
  696. LeafNode<NodeKind::MatchDefaultEqualGreater, Lex::EqualGreaterTokenIndex>;
  697. struct MatchDefaultStart {
  698. static constexpr auto Kind = NodeKind::MatchDefaultStart.Define(
  699. {.bracketed_by = MatchDefaultIntroducer::Kind, .child_count = 2});
  700. MatchDefaultIntroducerId introducer;
  701. MatchDefaultEqualGreaterId equal_greater_token;
  702. Lex::OpenCurlyBraceTokenIndex token;
  703. };
  704. struct MatchDefault {
  705. static constexpr auto Kind =
  706. NodeKind::MatchDefault.Define({.bracketed_by = MatchDefaultStart::Kind});
  707. MatchDefaultStartId introducer;
  708. llvm::SmallVector<AnyStatementId> statements;
  709. Lex::CloseCurlyBraceTokenIndex token;
  710. };
  711. // A `match` statement: `match (expr) { case (...) => {...} default => {...}}`.
  712. struct MatchStatement {
  713. static constexpr auto Kind = NodeKind::MatchStatement.Define(
  714. {.category = NodeCategory::Statement,
  715. .bracketed_by = MatchStatementStart::Kind});
  716. MatchStatementStartId head;
  717. llvm::SmallVector<MatchCaseId> cases;
  718. std::optional<MatchDefaultId> default_case;
  719. Lex::CloseCurlyBraceTokenIndex token;
  720. };
  721. // Expression nodes
  722. // ----------------
  723. using ArrayExprKeyword =
  724. LeafNode<NodeKind::ArrayExprKeyword, Lex::ArrayTokenIndex>;
  725. using ArrayExprOpenParen =
  726. LeafNode<NodeKind::ArrayExprOpenParen, Lex::OpenParenTokenIndex>;
  727. using ArrayExprComma = LeafNode<NodeKind::ArrayExprComma, Lex::CommaTokenIndex>;
  728. // An array type, `array(T, N)`.
  729. struct ArrayExpr {
  730. static constexpr auto Kind = NodeKind::ArrayExpr.Define(
  731. {.category = NodeCategory::Expr, .child_count = 5});
  732. ArrayExprKeywordId keyword;
  733. ArrayExprOpenParenId start;
  734. AnyExprId type;
  735. ArrayExprCommaId comma;
  736. AnyExprId bound;
  737. Lex::CloseParenTokenIndex token;
  738. };
  739. // The opening portion of an indexing expression: `a[`.
  740. //
  741. // TODO: Consider flattening this into `IndexExpr`.
  742. struct IndexExprStart {
  743. static constexpr auto Kind =
  744. NodeKind::IndexExprStart.Define({.child_count = 1});
  745. AnyExprId sequence;
  746. Lex::OpenSquareBracketTokenIndex token;
  747. };
  748. // An indexing expression, such as `a[1]`.
  749. struct IndexExpr {
  750. static constexpr auto Kind =
  751. NodeKind::IndexExpr.Define({.category = NodeCategory::Expr,
  752. .bracketed_by = IndexExprStart::Kind,
  753. .child_count = 2});
  754. IndexExprStartId start;
  755. AnyExprId index;
  756. Lex::CloseSquareBracketTokenIndex token;
  757. };
  758. using ParenExprStart =
  759. LeafNode<NodeKind::ParenExprStart, Lex::OpenParenTokenIndex>;
  760. // A parenthesized expression: `(a)`.
  761. struct ParenExpr {
  762. static constexpr auto Kind = NodeKind::ParenExpr.Define(
  763. {.category = NodeCategory::Expr | NodeCategory::MemberExpr,
  764. .bracketed_by = ParenExprStart::Kind,
  765. .child_count = 2});
  766. ParenExprStartId start;
  767. AnyExprId expr;
  768. Lex::CloseParenTokenIndex token;
  769. };
  770. using TupleLiteralStart =
  771. LeafNode<NodeKind::TupleLiteralStart, Lex::OpenParenTokenIndex>;
  772. using TupleLiteralComma =
  773. LeafNode<NodeKind::TupleLiteralComma, Lex::CommaTokenIndex>;
  774. // A tuple literal: `()`, `(a, b, c)`, or `(a,)`.
  775. struct TupleLiteral {
  776. static constexpr auto Kind =
  777. NodeKind::TupleLiteral.Define({.category = NodeCategory::Expr,
  778. .bracketed_by = TupleLiteralStart::Kind});
  779. TupleLiteralStartId start;
  780. CommaSeparatedList<AnyExprId, TupleLiteralCommaId> elements;
  781. Lex::CloseParenTokenIndex token;
  782. };
  783. // The opening portion of a call expression: `F(`.
  784. //
  785. // TODO: Consider flattening this into `CallExpr`.
  786. struct CallExprStart {
  787. static constexpr auto Kind =
  788. NodeKind::CallExprStart.Define({.child_count = 1});
  789. AnyExprId callee;
  790. Lex::OpenParenTokenIndex token;
  791. };
  792. using CallExprComma = LeafNode<NodeKind::CallExprComma, Lex::CommaTokenIndex>;
  793. // A call expression: `F(a, b, c)`.
  794. struct CallExpr {
  795. static constexpr auto Kind = NodeKind::CallExpr.Define(
  796. {.category = NodeCategory::Expr, .bracketed_by = CallExprStart::Kind});
  797. CallExprStartId start;
  798. CommaSeparatedList<AnyExprId, CallExprCommaId> arguments;
  799. Lex::CloseParenTokenIndex token;
  800. };
  801. // A member access expression: `a.b` or `a.(b)`.
  802. struct MemberAccessExpr {
  803. static constexpr auto Kind = NodeKind::MemberAccessExpr.Define(
  804. {.category = NodeCategory::Expr, .child_count = 2});
  805. AnyExprId lhs;
  806. Lex::PeriodTokenIndex token;
  807. AnyMemberAccessId rhs;
  808. };
  809. // An indirect member access expression: `a->b` or `a->(b)`.
  810. struct PointerMemberAccessExpr {
  811. static constexpr auto Kind = NodeKind::PointerMemberAccessExpr.Define(
  812. {.category = NodeCategory::Expr, .child_count = 2});
  813. AnyExprId lhs;
  814. Lex::MinusGreaterTokenIndex token;
  815. AnyMemberAccessId rhs;
  816. };
  817. // A prefix operator expression.
  818. template <const NodeKind& KindT, typename TokenKind>
  819. struct PrefixOperator {
  820. static constexpr auto Kind =
  821. KindT.Define({.category = NodeCategory::Expr, .child_count = 1});
  822. TokenKind token;
  823. AnyExprId operand;
  824. };
  825. // An infix operator expression.
  826. template <const NodeKind& KindT, typename TokenKind>
  827. struct InfixOperator {
  828. static constexpr auto Kind =
  829. KindT.Define({.category = NodeCategory::Expr, .child_count = 2});
  830. AnyExprId lhs;
  831. TokenKind token;
  832. AnyExprId rhs;
  833. };
  834. // A postfix operator expression.
  835. template <const NodeKind& KindT, typename TokenKind>
  836. struct PostfixOperator {
  837. static constexpr auto Kind =
  838. KindT.Define({.category = NodeCategory::Expr, .child_count = 1});
  839. AnyExprId operand;
  840. TokenKind token;
  841. };
  842. // An `unsafe` modifier: `a unsafe <operator> b`. This is modeled in the parse
  843. // tree as a postfix operator applied to `a`.
  844. struct UnsafeModifier {
  845. static constexpr auto Kind = NodeKind::UnsafeModifier.Define(
  846. {.category = NodeCategory::Expr, .child_count = 1});
  847. AnyExprId operand;
  848. Lex::UnsafeTokenIndex token;
  849. };
  850. // Literals, operators, and modifiers
  851. #define CARBON_PARSE_NODE_KIND(Name)
  852. #define CARBON_PARSE_NODE_KIND_TOKEN_LITERAL(Name, LexTokenKind) \
  853. using Name = LeafNode<NodeKind::Name, Lex::LexTokenKind##TokenIndex, \
  854. NodeCategory::Expr>;
  855. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name) \
  856. using Name##Modifier = \
  857. LeafNode<NodeKind::Name##Modifier, Lex::Name##TokenIndex, \
  858. NodeCategory::Modifier>;
  859. #define CARBON_PARSE_NODE_KIND_PREFIX_OPERATOR(Name) \
  860. using PrefixOperator##Name = \
  861. PrefixOperator<NodeKind::PrefixOperator##Name, Lex::Name##TokenIndex>;
  862. #define CARBON_PARSE_NODE_KIND_INFIX_OPERATOR(Name) \
  863. using InfixOperator##Name = \
  864. InfixOperator<NodeKind::InfixOperator##Name, Lex::Name##TokenIndex>;
  865. #define CARBON_PARSE_NODE_KIND_POSTFIX_OPERATOR(Name) \
  866. using PostfixOperator##Name = \
  867. PostfixOperator<NodeKind::PostfixOperator##Name, Lex::Name##TokenIndex>;
  868. #include "toolchain/parse/node_kind.def"
  869. using IntLiteral = LeafNode<NodeKind::IntLiteral, Lex::IntLiteralTokenIndex,
  870. NodeCategory::Expr | NodeCategory::IntConst>;
  871. // `extern` as a standalone modifier.
  872. using ExternModifier = LeafNode<NodeKind::ExternModifier, Lex::ExternTokenIndex,
  873. NodeCategory::Modifier>;
  874. // `extern library <owning_library>` modifiers.
  875. struct ExternModifierWithLibrary {
  876. static constexpr auto Kind = NodeKind::ExternModifierWithLibrary.Define(
  877. {.category = NodeCategory::Modifier, .child_count = 1});
  878. Lex::ExternTokenIndex token;
  879. LibrarySpecifierId library;
  880. };
  881. // The first operand of a short-circuiting infix operator: `a and` or `a or`.
  882. // The complete operator expression will be an InfixOperator with this as the
  883. // `lhs`.
  884. // TODO: Make this be a template if we ever need to write generic code to cover
  885. // both cases at once, say in check.
  886. struct ShortCircuitOperandAnd {
  887. static constexpr auto Kind =
  888. NodeKind::ShortCircuitOperandAnd.Define({.child_count = 1});
  889. AnyExprId operand;
  890. // This is a virtual token. The `and` token is owned by the
  891. // ShortCircuitOperatorAnd node.
  892. Lex::AndTokenIndex token;
  893. };
  894. struct ShortCircuitOperandOr {
  895. static constexpr auto Kind =
  896. NodeKind::ShortCircuitOperandOr.Define({.child_count = 1});
  897. AnyExprId operand;
  898. // This is a virtual token. The `or` token is owned by the
  899. // ShortCircuitOperatorOr node.
  900. Lex::OrTokenIndex token;
  901. };
  902. struct ShortCircuitOperatorAnd {
  903. static constexpr auto Kind = NodeKind::ShortCircuitOperatorAnd.Define(
  904. {.category = NodeCategory::Expr,
  905. .bracketed_by = ShortCircuitOperandAnd::Kind,
  906. .child_count = 2});
  907. ShortCircuitOperandAndId lhs;
  908. Lex::AndTokenIndex token;
  909. AnyExprId rhs;
  910. };
  911. struct ShortCircuitOperatorOr {
  912. static constexpr auto Kind = NodeKind::ShortCircuitOperatorOr.Define(
  913. {.category = NodeCategory::Expr,
  914. .bracketed_by = ShortCircuitOperandOr::Kind,
  915. .child_count = 2});
  916. ShortCircuitOperandOrId lhs;
  917. Lex::OrTokenIndex token;
  918. AnyExprId rhs;
  919. };
  920. // The `if` portion of an `if` expression: `if expr`.
  921. struct IfExprIf {
  922. static constexpr auto Kind = NodeKind::IfExprIf.Define({.child_count = 1});
  923. Lex::IfTokenIndex token;
  924. AnyExprId condition;
  925. };
  926. // The `then` portion of an `if` expression: `then expr`.
  927. struct IfExprThen {
  928. static constexpr auto Kind = NodeKind::IfExprThen.Define({.child_count = 1});
  929. Lex::ThenTokenIndex token;
  930. AnyExprId result;
  931. };
  932. // A full `if` expression: `if expr then expr else expr`.
  933. struct IfExprElse {
  934. static constexpr auto Kind =
  935. NodeKind::IfExprElse.Define({.category = NodeCategory::Expr,
  936. .bracketed_by = IfExprIf::Kind,
  937. .child_count = 3});
  938. IfExprIfId start;
  939. IfExprThenId then;
  940. Lex::ElseTokenIndex token;
  941. AnyExprId else_result;
  942. };
  943. // A `where` expression (TODO: `require` and `observe` declarations)
  944. // The `Self` in a context where it is treated as a name rather than an
  945. // expression, such as `.Self`.
  946. using SelfTypeName =
  947. LeafNode<NodeKind::SelfTypeName, Lex::SelfTypeIdentifierTokenIndex>;
  948. // `.Member` or `.Self` in an expression context, used in `where` and `require`
  949. // clauses.
  950. // TODO: Do we want to support `.1`, a designator for accessing a tuple member?
  951. struct DesignatorExpr {
  952. static constexpr auto Kind = NodeKind::DesignatorExpr.Define(
  953. {.category = NodeCategory::Expr, .child_count = 1});
  954. Lex::PeriodTokenIndex token;
  955. NodeIdOneOf<IdentifierNameNotBeforeParams, SelfTypeName> name;
  956. };
  957. struct RequirementEqual {
  958. static constexpr auto Kind = NodeKind::RequirementEqual.Define(
  959. {.category = NodeCategory::Requirement, .child_count = 2});
  960. DesignatorExprId lhs;
  961. Lex::EqualTokenIndex token;
  962. AnyExprId rhs;
  963. };
  964. struct RequirementEqualEqual {
  965. static constexpr auto Kind = NodeKind::RequirementEqualEqual.Define(
  966. {.category = NodeCategory::Requirement, .child_count = 2});
  967. AnyExprId lhs;
  968. Lex::EqualEqualTokenIndex token;
  969. AnyExprId rhs;
  970. };
  971. struct RequirementImpls {
  972. static constexpr auto Kind = NodeKind::RequirementImpls.Define(
  973. {.category = NodeCategory::Requirement, .child_count = 2});
  974. AnyExprId lhs;
  975. Lex::ImplsTokenIndex token;
  976. AnyExprId rhs;
  977. };
  978. // An `and` token separating requirements in a `where` expression.
  979. using RequirementAnd = LeafNode<NodeKind::RequirementAnd, Lex::AndTokenIndex>;
  980. struct WhereOperand {
  981. static constexpr auto Kind =
  982. NodeKind::WhereOperand.Define({.child_count = 1});
  983. AnyExprId type;
  984. // This is a virtual token. The `where` token is owned by the
  985. // WhereExpr node.
  986. Lex::WhereTokenIndex token;
  987. };
  988. struct WhereExpr {
  989. static constexpr auto Kind = NodeKind::WhereExpr.Define(
  990. {.category = NodeCategory::Expr, .bracketed_by = WhereOperand::Kind});
  991. WhereOperandId introducer;
  992. Lex::WhereTokenIndex token;
  993. CommaSeparatedList<AnyRequirementId, RequirementAndId> requirements;
  994. };
  995. // Choice nodes
  996. // ------------
  997. using ChoiceIntroducer =
  998. LeafNode<NodeKind::ChoiceIntroducer, Lex::ChoiceTokenIndex>;
  999. struct ChoiceSignature {
  1000. static constexpr auto Kind = NodeKind::ChoiceDefinitionStart.Define(
  1001. {.category = NodeCategory::None, .bracketed_by = ChoiceIntroducer::Kind});
  1002. ChoiceIntroducerId introducer;
  1003. llvm::SmallVector<AnyModifierId> modifiers;
  1004. DeclName name;
  1005. Lex::OpenCurlyBraceTokenIndex token;
  1006. };
  1007. using ChoiceDefinitionStart = ChoiceSignature;
  1008. using ChoiceAlternativeListComma =
  1009. LeafNode<NodeKind::ChoiceAlternativeListComma, Lex::CommaTokenIndex>;
  1010. struct ChoiceDefinition {
  1011. static constexpr auto Kind = NodeKind::ChoiceDefinition.Define(
  1012. {.category = NodeCategory::Decl,
  1013. .bracketed_by = ChoiceDefinitionStart::Kind});
  1014. ChoiceDefinitionStartId signature;
  1015. struct Alternative {
  1016. AnyNonExprNameId name;
  1017. std::optional<ExplicitParamListId> parameters;
  1018. };
  1019. CommaSeparatedList<Alternative, ChoiceAlternativeListCommaId> alternatives;
  1020. Lex::CloseCurlyBraceTokenIndex token;
  1021. };
  1022. // Struct type and value literals
  1023. // ----------------------------------------
  1024. // `{`
  1025. using StructLiteralStart =
  1026. LeafNode<NodeKind::StructLiteralStart, Lex::OpenCurlyBraceTokenIndex>;
  1027. using StructTypeLiteralStart =
  1028. LeafNode<NodeKind::StructTypeLiteralStart, Lex::OpenCurlyBraceTokenIndex>;
  1029. // `,`
  1030. using StructLiteralComma =
  1031. LeafNode<NodeKind::StructLiteralComma, Lex::CommaTokenIndex>;
  1032. using StructTypeLiteralComma =
  1033. LeafNode<NodeKind::StructTypeLiteralComma, Lex::CommaTokenIndex>;
  1034. // `.a`
  1035. // This is shared for struct literals and type literals in order to reduce
  1036. // lookahead for parse (the `=` versus `:` would require lookahead of 2).
  1037. struct StructFieldDesignator {
  1038. static constexpr auto Kind =
  1039. NodeKind::StructFieldDesignator.Define({.child_count = 1});
  1040. Lex::PeriodTokenIndex token;
  1041. NodeIdOneOf<IdentifierNameNotBeforeParams, BaseName> name;
  1042. };
  1043. // `.a = 0`
  1044. struct StructLiteralField {
  1045. static constexpr auto Kind = NodeKind::StructLiteralField.Define(
  1046. {.bracketed_by = StructFieldDesignator::Kind, .child_count = 2});
  1047. StructFieldDesignatorId designator;
  1048. Lex::EqualTokenIndex token;
  1049. AnyExprId expr;
  1050. };
  1051. // `.a: i32`
  1052. struct StructTypeLiteralField {
  1053. static constexpr auto Kind = NodeKind::StructTypeLiteralField.Define(
  1054. {.bracketed_by = StructFieldDesignator::Kind, .child_count = 2});
  1055. StructFieldDesignatorId designator;
  1056. Lex::ColonTokenIndex token;
  1057. AnyExprId type_expr;
  1058. };
  1059. // Struct literals, such as `{.a = 0}`.
  1060. struct StructLiteral {
  1061. static constexpr auto Kind = NodeKind::StructLiteral.Define(
  1062. {.category = NodeCategory::Expr,
  1063. .bracketed_by = StructLiteralStart::Kind});
  1064. StructLiteralStartId start;
  1065. CommaSeparatedList<StructLiteralFieldId, StructLiteralCommaId> fields;
  1066. Lex::CloseCurlyBraceTokenIndex token;
  1067. };
  1068. // Struct type literals, such as `{.a: i32}`.
  1069. struct StructTypeLiteral {
  1070. static constexpr auto Kind = NodeKind::StructTypeLiteral.Define(
  1071. {.category = NodeCategory::Expr,
  1072. .bracketed_by = StructTypeLiteralStart::Kind});
  1073. StructTypeLiteralStartId start;
  1074. CommaSeparatedList<StructTypeLiteralFieldId, StructTypeLiteralCommaId> fields;
  1075. Lex::CloseCurlyBraceTokenIndex token;
  1076. };
  1077. // `class` declarations and definitions
  1078. // ------------------------------------
  1079. // `class`
  1080. using ClassIntroducer =
  1081. LeafNode<NodeKind::ClassIntroducer, Lex::ClassTokenIndex>;
  1082. // A class signature `class C`
  1083. template <const NodeKind& KindT, typename TokenKind,
  1084. NodeCategory::RawEnumType Category>
  1085. struct ClassSignature {
  1086. static constexpr auto Kind = KindT.Define(
  1087. {.category = Category, .bracketed_by = ClassIntroducer::Kind});
  1088. ClassIntroducerId introducer;
  1089. llvm::SmallVector<AnyModifierId> modifiers;
  1090. DeclName name;
  1091. TokenKind token;
  1092. };
  1093. // `class C;`
  1094. using ClassDecl = ClassSignature<NodeKind::ClassDecl, Lex::SemiTokenIndex,
  1095. NodeCategory::Decl>;
  1096. // `class C {`
  1097. using ClassDefinitionStart =
  1098. ClassSignature<NodeKind::ClassDefinitionStart,
  1099. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  1100. // `class C { ... }`
  1101. struct ClassDefinition {
  1102. static constexpr auto Kind = NodeKind::ClassDefinition.Define(
  1103. {.category = NodeCategory::Decl,
  1104. .bracketed_by = ClassDefinitionStart::Kind});
  1105. ClassDefinitionStartId signature;
  1106. llvm::SmallVector<AnyDeclId> members;
  1107. Lex::CloseCurlyBraceTokenIndex token;
  1108. };
  1109. // Adapter declaration
  1110. // -------------------
  1111. // `adapt`
  1112. using AdaptIntroducer =
  1113. LeafNode<NodeKind::AdaptIntroducer, Lex::AdaptTokenIndex>;
  1114. // `adapt SomeType;`
  1115. struct AdaptDecl {
  1116. static constexpr auto Kind = NodeKind::AdaptDecl.Define(
  1117. {.category = NodeCategory::Decl, .bracketed_by = AdaptIntroducer::Kind});
  1118. AdaptIntroducerId introducer;
  1119. llvm::SmallVector<AnyModifierId> modifiers;
  1120. AnyExprId adapted_type;
  1121. Lex::SemiTokenIndex token;
  1122. };
  1123. // Base class declaration
  1124. // ----------------------
  1125. // `base`
  1126. using BaseIntroducer = LeafNode<NodeKind::BaseIntroducer, Lex::BaseTokenIndex>;
  1127. using BaseColon = LeafNode<NodeKind::BaseColon, Lex::ColonTokenIndex>;
  1128. // `extend base: BaseClass;`
  1129. struct BaseDecl {
  1130. static constexpr auto Kind = NodeKind::BaseDecl.Define(
  1131. {.category = NodeCategory::Decl, .bracketed_by = BaseIntroducer::Kind});
  1132. BaseIntroducerId introducer;
  1133. llvm::SmallVector<AnyModifierId> modifiers;
  1134. BaseColonId colon;
  1135. AnyExprId base_class;
  1136. Lex::SemiTokenIndex token;
  1137. };
  1138. // Interface declarations and definitions
  1139. // --------------------------------------
  1140. // `interface`
  1141. using InterfaceIntroducer =
  1142. LeafNode<NodeKind::InterfaceIntroducer, Lex::InterfaceTokenIndex>;
  1143. // `interface I`
  1144. template <const NodeKind& KindT, typename TokenKind,
  1145. NodeCategory::RawEnumType Category>
  1146. struct InterfaceSignature {
  1147. static constexpr auto Kind = KindT.Define(
  1148. {.category = Category, .bracketed_by = InterfaceIntroducer::Kind});
  1149. InterfaceIntroducerId introducer;
  1150. llvm::SmallVector<AnyModifierId> modifiers;
  1151. DeclName name;
  1152. TokenKind token;
  1153. };
  1154. // `interface I;`
  1155. using InterfaceDecl =
  1156. InterfaceSignature<NodeKind::InterfaceDecl, Lex::SemiTokenIndex,
  1157. NodeCategory::Decl>;
  1158. // `interface I {`
  1159. using InterfaceDefinitionStart =
  1160. InterfaceSignature<NodeKind::InterfaceDefinitionStart,
  1161. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  1162. // `interface I { ... }`
  1163. struct InterfaceDefinition {
  1164. static constexpr auto Kind = NodeKind::InterfaceDefinition.Define(
  1165. {.category = NodeCategory::Decl,
  1166. .bracketed_by = InterfaceDefinitionStart::Kind});
  1167. InterfaceDefinitionStartId signature;
  1168. llvm::SmallVector<AnyDeclId> members;
  1169. Lex::CloseCurlyBraceTokenIndex token;
  1170. };
  1171. // `impl`...`as` declarations and definitions
  1172. // ------------------------------------------
  1173. // `impl`
  1174. using ImplIntroducer = LeafNode<NodeKind::ImplIntroducer, Lex::ImplTokenIndex>;
  1175. // `forall`
  1176. using Forall = LeafNode<NodeKind::Forall, Lex::ForallTokenIndex>;
  1177. // `forall [...]`
  1178. struct ImplForall {
  1179. ForallId forall;
  1180. ImplicitParamListId params;
  1181. };
  1182. // `as` with no type before it
  1183. using DefaultSelfImplAs = LeafNode<NodeKind::DefaultSelfImplAs,
  1184. Lex::AsTokenIndex, NodeCategory::ImplAs>;
  1185. // `<type> as`
  1186. struct TypeImplAs {
  1187. static constexpr auto Kind = NodeKind::TypeImplAs.Define(
  1188. {.category = NodeCategory::ImplAs, .child_count = 1});
  1189. AnyExprId type_expr;
  1190. Lex::AsTokenIndex token;
  1191. };
  1192. // `impl T as I`
  1193. template <const NodeKind& KindT, typename TokenKind,
  1194. NodeCategory::RawEnumType Category>
  1195. struct ImplSignature {
  1196. static constexpr auto Kind = KindT.Define(
  1197. {.category = Category, .bracketed_by = ImplIntroducer::Kind});
  1198. ImplIntroducerId introducer;
  1199. llvm::SmallVector<AnyModifierId> modifiers;
  1200. std::optional<ImplForall> forall;
  1201. AnyImplAsId as;
  1202. AnyExprId interface;
  1203. TokenKind token;
  1204. };
  1205. // `impl T as I;`
  1206. using ImplDecl =
  1207. ImplSignature<NodeKind::ImplDecl, Lex::SemiTokenIndex, NodeCategory::Decl>;
  1208. // `impl T as I {`
  1209. using ImplDefinitionStart =
  1210. ImplSignature<NodeKind::ImplDefinitionStart, Lex::OpenCurlyBraceTokenIndex,
  1211. NodeCategory::None>;
  1212. // `impl T as I { ... }`
  1213. struct ImplDefinition {
  1214. static constexpr auto Kind = NodeKind::ImplDefinition.Define(
  1215. {.category = NodeCategory::Decl,
  1216. .bracketed_by = ImplDefinitionStart::Kind});
  1217. ImplDefinitionStartId signature;
  1218. llvm::SmallVector<AnyDeclId> members;
  1219. Lex::CloseCurlyBraceTokenIndex token;
  1220. };
  1221. // Named constraint declarations and definitions
  1222. // ---------------------------------------------
  1223. // `constraint`
  1224. using NamedConstraintIntroducer =
  1225. LeafNode<NodeKind::NamedConstraintIntroducer, Lex::ConstraintTokenIndex>;
  1226. // `constraint NC`
  1227. template <const NodeKind& KindT, typename TokenKind,
  1228. NodeCategory::RawEnumType Category>
  1229. struct NamedConstraintSignature {
  1230. static constexpr auto Kind = KindT.Define(
  1231. {.category = Category, .bracketed_by = NamedConstraintIntroducer::Kind});
  1232. NamedConstraintIntroducerId introducer;
  1233. llvm::SmallVector<AnyModifierId> modifiers;
  1234. DeclName name;
  1235. TokenKind token;
  1236. };
  1237. // `constraint NC;`
  1238. using NamedConstraintDecl =
  1239. NamedConstraintSignature<NodeKind::NamedConstraintDecl, Lex::SemiTokenIndex,
  1240. NodeCategory::Decl>;
  1241. // `constraint NC {`
  1242. using NamedConstraintDefinitionStart =
  1243. NamedConstraintSignature<NodeKind::NamedConstraintDefinitionStart,
  1244. Lex::OpenCurlyBraceTokenIndex, NodeCategory::None>;
  1245. // `constraint NC { ... }`
  1246. struct NamedConstraintDefinition {
  1247. static constexpr auto Kind = NodeKind::NamedConstraintDefinition.Define(
  1248. {.category = NodeCategory::Decl,
  1249. .bracketed_by = NamedConstraintDefinitionStart::Kind});
  1250. NamedConstraintDefinitionStartId signature;
  1251. llvm::SmallVector<AnyDeclId> members;
  1252. Lex::CloseCurlyBraceTokenIndex token;
  1253. };
  1254. // ---------------------------------------------------------------------------
  1255. // A complete source file. Note that there is no corresponding parse node for
  1256. // the file. The file is instead the complete contents of the parse tree.
  1257. struct File {
  1258. FileStartId start;
  1259. llvm::SmallVector<AnyDeclId> decls;
  1260. FileEndId end;
  1261. };
  1262. // Define `Foo` as the node type for the ID type `FooId`.
  1263. #define CARBON_PARSE_NODE_KIND(KindName) \
  1264. template <> \
  1265. struct NodeForId<KindName##Id> { \
  1266. using TypedNode = KindName; \
  1267. };
  1268. #include "toolchain/parse/node_kind.def"
  1269. } // namespace Carbon::Parse
  1270. #endif // CARBON_TOOLCHAIN_PARSE_TYPED_NODES_H_