typed_nodes.h 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  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/parse/node_ids.h"
  8. #include "toolchain/parse/node_kind.h"
  9. namespace Carbon::Parse {
  10. // Helpers for defining different kinds of parse nodes.
  11. // ----------------------------------------------------
  12. // A pair of a list item and its optional following comma.
  13. template <typename Element, typename Comma>
  14. struct ListItem {
  15. Element value;
  16. std::optional<Comma> comma;
  17. };
  18. // A list of items, parameterized by the kind of the elements and comma.
  19. template <typename Element, typename Comma>
  20. using CommaSeparatedList = llvm::SmallVector<ListItem<Element, Comma>>;
  21. // This class provides a shorthand for defining parse node kinds for leaf nodes.
  22. template <const NodeKind& KindT, NodeCategory Category = NodeCategory::None>
  23. struct LeafNode {
  24. static constexpr auto Kind = KindT.Define(Category);
  25. };
  26. // ----------------------------------------------------------------------------
  27. // Each node kind (in node_kind.def) should have a corresponding type defined
  28. // here which describes the expected child structure of that parse node.
  29. //
  30. // Each of these types should start with a `static constexpr Kind` member
  31. // initialized by calling `Define` on the corresponding `NodeKind`, and passing
  32. // in the `NodeCategory` of that kind. This will both associate the category
  33. // with the node kind and create the necessary kind object for the typed node.
  34. //
  35. // This should be followed by field declarations that describe the child nodes,
  36. // in order, that occur in the parse tree. The `Extract...` functions on the
  37. // parse tree use struct reflection on these fields to guide the extraction of
  38. // the child nodes from the tree into an object of this type with these fields
  39. // for convenient access.
  40. //
  41. // The types of these fields are special and describe the specific child node
  42. // structure of the parse node. Many of these types are defined in `node_ids.h`.
  43. //
  44. // Valid primitive types here are:
  45. // - `NodeId` to match any single child node
  46. // - `FooId` to require that child to have kind `NodeKind::Foo`
  47. // - `AnyCatId` to require that child to have a kind in category `Cat`
  48. // - `NodeIdOneOf<A, B>` to require the child to have kind `NodeKind::A` or
  49. // `NodeKind::B`
  50. // - `NodeIdNot<A>` to match any single child whose kind is not `NodeKind::A`
  51. //
  52. // There a few, restricted composite field types allowed that compose types in
  53. // various ways, where all of the `T`s and `U`s below are themselves valid field
  54. // types:
  55. // - `llvm::SmallVector<T>` to match any number of children matching `T`
  56. // - `std::optional<T>` to match 0 or 1 children matching `T`
  57. // - `std::tuple<T...>` to match children matching `T...`
  58. // - Any provided `Aggregate` type that is a simple aggregate type such as
  59. // `struct Aggregate { T x; U y; }`,
  60. // to match children with types `T` and `U`.
  61. // ----------------------------------------------------------------------------
  62. // Error nodes
  63. // -----------
  64. // An invalid parse. Used to balance the parse tree. This type is here only to
  65. // ensure we have a type for each parse node kind. This node kind always has an
  66. // error, so can never be extracted.
  67. using InvalidParse =
  68. LeafNode<NodeKind::InvalidParse, NodeCategory::Decl | NodeCategory::Expr>;
  69. // An invalid subtree. Always has an error so can never be extracted.
  70. using InvalidParseStart = LeafNode<NodeKind::InvalidParseStart>;
  71. struct InvalidParseSubtree {
  72. static constexpr auto Kind =
  73. NodeKind::InvalidParseSubtree.Define(NodeCategory::Decl);
  74. InvalidParseStartId start;
  75. llvm::SmallVector<NodeIdNot<InvalidParseStart>> extra;
  76. };
  77. // A placeholder node to be replaced; it will never exist in a valid parse tree.
  78. // Its token kind is not enforced even when valid.
  79. using Placeholder = LeafNode<NodeKind::Placeholder>;
  80. // File nodes
  81. // ----------
  82. // The start of the file.
  83. using FileStart = LeafNode<NodeKind::FileStart>;
  84. // The end of the file.
  85. using FileEnd = LeafNode<NodeKind::FileEnd>;
  86. // General-purpose nodes
  87. // ---------------------
  88. // An empty declaration, such as `;`.
  89. using EmptyDecl =
  90. LeafNode<NodeKind::EmptyDecl, NodeCategory::Decl | NodeCategory::Statement>;
  91. // A name in a non-expression context, such as a declaration.
  92. using IdentifierName =
  93. LeafNode<NodeKind::IdentifierName,
  94. NodeCategory::NameComponent | NodeCategory::MemberName>;
  95. // A name in an expression context.
  96. using IdentifierNameExpr =
  97. LeafNode<NodeKind::IdentifierNameExpr, NodeCategory::Expr>;
  98. // The `self` value and `Self` type identifier keywords. Typically of the form
  99. // `self: Self`.
  100. using SelfValueName = LeafNode<NodeKind::SelfValueName>;
  101. using SelfValueNameExpr =
  102. LeafNode<NodeKind::SelfValueNameExpr, NodeCategory::Expr>;
  103. using SelfTypeNameExpr =
  104. LeafNode<NodeKind::SelfTypeNameExpr, NodeCategory::Expr>;
  105. // The `base` value keyword, introduced by `base: B`. Typically referenced in
  106. // an expression, as in `x.base` or `{.base = ...}`, but can also be used as a
  107. // declared name, as in `{.base: partial B}`.
  108. using BaseName = LeafNode<NodeKind::BaseName, NodeCategory::MemberName>;
  109. // A qualified name: `A.B`.
  110. struct QualifiedName {
  111. static constexpr auto Kind =
  112. NodeKind::QualifiedName.Define(NodeCategory::NameComponent);
  113. // For now, this is either an IdentifierName or a QualifiedName.
  114. AnyNameComponentId lhs;
  115. // TODO: This will eventually need to support more general expressions, for
  116. // example `GenericType(type_args).ChildType(child_type_args).Name`.
  117. IdentifierNameId rhs;
  118. };
  119. // Library, package, import
  120. // ------------------------
  121. // The `package` keyword in an expression.
  122. using PackageExpr = LeafNode<NodeKind::PackageExpr, NodeCategory::Expr>;
  123. // The name of a package or library for `package`, `import`, and `library`.
  124. using PackageName = LeafNode<NodeKind::PackageName>;
  125. using LibraryName = LeafNode<NodeKind::LibraryName>;
  126. using DefaultLibrary = LeafNode<NodeKind::DefaultLibrary>;
  127. using PackageIntroducer = LeafNode<NodeKind::PackageIntroducer>;
  128. using PackageApi = LeafNode<NodeKind::PackageApi>;
  129. using PackageImpl = LeafNode<NodeKind::PackageImpl>;
  130. // `library` in `package` or `import`.
  131. struct LibrarySpecifier {
  132. static constexpr auto Kind = NodeKind::LibrarySpecifier.Define();
  133. NodeIdOneOf<LibraryName, DefaultLibrary> name;
  134. };
  135. // First line of the file, such as:
  136. // `package MyPackage library "MyLibrary" impl;`
  137. struct PackageDirective {
  138. static constexpr auto Kind =
  139. NodeKind::PackageDirective.Define(NodeCategory::Decl);
  140. PackageIntroducerId introducer;
  141. std::optional<PackageNameId> name;
  142. std::optional<LibrarySpecifierId> library;
  143. NodeIdOneOf<PackageApi, PackageImpl> api_or_impl;
  144. };
  145. // `import TheirPackage library "TheirLibrary";`
  146. using ImportIntroducer = LeafNode<NodeKind::ImportIntroducer>;
  147. struct ImportDirective {
  148. static constexpr auto Kind =
  149. NodeKind::ImportDirective.Define(NodeCategory::Decl);
  150. ImportIntroducerId introducer;
  151. std::optional<PackageNameId> name;
  152. std::optional<LibrarySpecifierId> library;
  153. };
  154. // `library` as directive.
  155. using LibraryIntroducer = LeafNode<NodeKind::LibraryIntroducer>;
  156. struct LibraryDirective {
  157. static constexpr auto Kind =
  158. NodeKind::LibraryDirective.Define(NodeCategory::Decl);
  159. LibraryIntroducerId introducer;
  160. NodeIdOneOf<LibraryName, DefaultLibrary> library_name;
  161. NodeIdOneOf<PackageApi, PackageImpl> api_or_impl;
  162. };
  163. // Namespace nodes
  164. // ---------------
  165. using NamespaceStart = LeafNode<NodeKind::NamespaceStart>;
  166. // A namespace: `namespace N;`.
  167. struct Namespace {
  168. static constexpr auto Kind = NodeKind::Namespace.Define(NodeCategory::Decl);
  169. NamespaceStartId introducer;
  170. llvm::SmallVector<AnyModifierId> modifiers;
  171. NodeIdOneOf<IdentifierName, QualifiedName> name;
  172. };
  173. // Pattern nodes
  174. // -------------
  175. // A pattern binding, such as `name: Type`.
  176. struct BindingPattern {
  177. static constexpr auto Kind =
  178. NodeKind::BindingPattern.Define(NodeCategory::Pattern);
  179. NodeIdOneOf<IdentifierName, SelfValueName> name;
  180. AnyExprId type;
  181. };
  182. // `name:! Type`
  183. struct CompileTimeBindingPattern {
  184. static constexpr auto Kind =
  185. NodeKind::CompileTimeBindingPattern.Define(NodeCategory::Pattern);
  186. NodeIdOneOf<IdentifierName, SelfValueName> name;
  187. AnyExprId type;
  188. };
  189. // An address-of binding: `addr self: Self*`.
  190. struct Addr {
  191. static constexpr auto Kind = NodeKind::Addr.Define(NodeCategory::Pattern);
  192. AnyPatternId inner;
  193. };
  194. // A template binding: `template T:! type`.
  195. struct Template {
  196. static constexpr auto Kind = NodeKind::Template.Define(NodeCategory::Pattern);
  197. // This is a CompileTimeBindingPatternId in any valid program.
  198. // TODO: Should the parser enforce that?
  199. AnyPatternId inner;
  200. };
  201. using TuplePatternStart = LeafNode<NodeKind::TuplePatternStart>;
  202. using PatternListComma = LeafNode<NodeKind::PatternListComma>;
  203. // A parameter list or tuple pattern: `(a: i32, b: i32)`.
  204. struct TuplePattern {
  205. static constexpr auto Kind =
  206. NodeKind::TuplePattern.Define(NodeCategory::Pattern);
  207. TuplePatternStartId left_paren;
  208. CommaSeparatedList<AnyPatternId, PatternListCommaId> params;
  209. };
  210. using ImplicitParamListStart = LeafNode<NodeKind::ImplicitParamListStart>;
  211. // An implicit parameter list: `[T:! type, self: Self]`.
  212. struct ImplicitParamList {
  213. static constexpr auto Kind = NodeKind::ImplicitParamList.Define();
  214. ImplicitParamListStartId left_square;
  215. CommaSeparatedList<AnyPatternId, PatternListCommaId> params;
  216. };
  217. // Function nodes
  218. // --------------
  219. using FunctionIntroducer = LeafNode<NodeKind::FunctionIntroducer>;
  220. // A return type: `-> i32`.
  221. struct ReturnType {
  222. static constexpr auto Kind = NodeKind::ReturnType.Define();
  223. AnyExprId type;
  224. };
  225. // A function signature: `fn F() -> i32`.
  226. template <const NodeKind& KindT, NodeCategory Category>
  227. struct FunctionSignature {
  228. static constexpr auto Kind = KindT.Define(Category);
  229. FunctionIntroducerId introducer;
  230. llvm::SmallVector<AnyModifierId> modifiers;
  231. // For now, this is either an IdentifierName or a QualifiedName.
  232. AnyNameComponentId name;
  233. std::optional<ImplicitParamListId> implicit_params;
  234. TuplePatternId params;
  235. std::optional<ReturnTypeId> return_type;
  236. };
  237. using FunctionDecl =
  238. FunctionSignature<NodeKind::FunctionDecl, NodeCategory::Decl>;
  239. using FunctionDefinitionStart =
  240. FunctionSignature<NodeKind::FunctionDefinitionStart, NodeCategory::None>;
  241. // A function definition: `fn F() -> i32 { ... }`.
  242. struct FunctionDefinition {
  243. static constexpr auto Kind =
  244. NodeKind::FunctionDefinition.Define(NodeCategory::Decl);
  245. FunctionDefinitionStartId signature;
  246. llvm::SmallVector<AnyStatementId> body;
  247. };
  248. using BuiltinFunctionDefinitionStart =
  249. FunctionSignature<NodeKind::BuiltinFunctionDefinitionStart,
  250. NodeCategory::None>;
  251. using BuiltinName = LeafNode<NodeKind::BuiltinName>;
  252. // A builtin function definition: `fn F() -> i32 = "builtin name";`
  253. struct BuiltinFunctionDefinition {
  254. static constexpr auto Kind =
  255. NodeKind::BuiltinFunctionDefinition.Define(NodeCategory::Decl);
  256. BuiltinFunctionDefinitionStartId signature;
  257. BuiltinNameId builtin_name;
  258. };
  259. // `alias` nodes
  260. // -------------
  261. using AliasIntroducer = LeafNode<NodeKind::AliasIntroducer>;
  262. using AliasInitializer = LeafNode<NodeKind::AliasInitializer>;
  263. // An `alias` declaration: `alias a = b;`.
  264. struct Alias {
  265. static constexpr auto Kind =
  266. NodeKind::Alias.Define(NodeCategory::Decl | NodeCategory::Statement);
  267. AliasIntroducerId introducer;
  268. llvm::SmallVector<AnyModifierId> modifiers;
  269. // For now, this is either an IdentifierName or a QualifiedName.
  270. AnyNameComponentId name;
  271. AliasInitializerId equals;
  272. AnyExprId initializer;
  273. };
  274. // `let` nodes
  275. // -----------
  276. using LetIntroducer = LeafNode<NodeKind::LetIntroducer>;
  277. using LetInitializer = LeafNode<NodeKind::LetInitializer>;
  278. // A `let` declaration: `let a: i32 = 5;`.
  279. struct LetDecl {
  280. static constexpr auto Kind =
  281. NodeKind::LetDecl.Define(NodeCategory::Decl | NodeCategory::Statement);
  282. LetIntroducerId introducer;
  283. llvm::SmallVector<AnyModifierId> modifiers;
  284. AnyPatternId pattern;
  285. struct Initializer {
  286. LetInitializerId equals;
  287. AnyExprId initializer;
  288. };
  289. std::optional<Initializer> initializer;
  290. };
  291. // `var` nodes
  292. // -----------
  293. using VariableIntroducer = LeafNode<NodeKind::VariableIntroducer>;
  294. using ReturnedModifier = LeafNode<NodeKind::ReturnedModifier>;
  295. using VariableInitializer = LeafNode<NodeKind::VariableInitializer>;
  296. // A `var` declaration: `var a: i32;` or `var a: i32 = 5;`.
  297. struct VariableDecl {
  298. static constexpr auto Kind = NodeKind::VariableDecl.Define(
  299. NodeCategory::Decl | NodeCategory::Statement);
  300. VariableIntroducerId introducer;
  301. llvm::SmallVector<AnyModifierId> modifiers;
  302. std::optional<ReturnedModifierId> returned;
  303. AnyPatternId pattern;
  304. struct Initializer {
  305. VariableInitializerId equals;
  306. AnyExprId value;
  307. };
  308. std::optional<Initializer> initializer;
  309. };
  310. // Statement nodes
  311. // ---------------
  312. using CodeBlockStart = LeafNode<NodeKind::CodeBlockStart>;
  313. // A code block: `{ statement; statement; ... }`.
  314. struct CodeBlock {
  315. static constexpr auto Kind = NodeKind::CodeBlock.Define();
  316. CodeBlockStartId left_brace;
  317. llvm::SmallVector<AnyStatementId> statements;
  318. };
  319. // An expression statement: `F(x);`.
  320. struct ExprStatement {
  321. static constexpr auto Kind =
  322. NodeKind::ExprStatement.Define(NodeCategory::Statement);
  323. AnyExprId expr;
  324. };
  325. using BreakStatementStart = LeafNode<NodeKind::BreakStatementStart>;
  326. // A break statement: `break;`.
  327. struct BreakStatement {
  328. static constexpr auto Kind =
  329. NodeKind::BreakStatement.Define(NodeCategory::Statement);
  330. BreakStatementStartId introducer;
  331. };
  332. using ContinueStatementStart = LeafNode<NodeKind::ContinueStatementStart>;
  333. // A continue statement: `continue;`.
  334. struct ContinueStatement {
  335. static constexpr auto Kind =
  336. NodeKind::ContinueStatement.Define(NodeCategory::Statement);
  337. ContinueStatementStartId introducer;
  338. };
  339. using ReturnStatementStart = LeafNode<NodeKind::ReturnStatementStart>;
  340. using ReturnVarModifier = LeafNode<NodeKind::ReturnVarModifier>;
  341. // A return statement: `return;` or `return expr;` or `return var;`.
  342. struct ReturnStatement {
  343. static constexpr auto Kind =
  344. NodeKind::ReturnStatement.Define(NodeCategory::Statement);
  345. ReturnStatementStartId introducer;
  346. std::optional<AnyExprId> expr;
  347. std::optional<ReturnVarModifierId> var;
  348. };
  349. using ForHeaderStart = LeafNode<NodeKind::ForHeaderStart>;
  350. // The `var ... in` portion of a `for` statement.
  351. struct ForIn {
  352. static constexpr auto Kind = NodeKind::ForIn.Define();
  353. VariableIntroducerId introducer;
  354. AnyPatternId pattern;
  355. };
  356. // The `for (var ... in ...)` portion of a `for` statement.
  357. struct ForHeader {
  358. static constexpr auto Kind = NodeKind::ForHeader.Define();
  359. ForHeaderStartId introducer;
  360. ForInId var;
  361. AnyExprId range;
  362. };
  363. // A complete `for (...) { ... }` statement.
  364. struct ForStatement {
  365. static constexpr auto Kind =
  366. NodeKind::ForStatement.Define(NodeCategory::Statement);
  367. ForHeaderId header;
  368. CodeBlockId body;
  369. };
  370. using IfConditionStart = LeafNode<NodeKind::IfConditionStart>;
  371. // The condition portion of an `if` statement: `(expr)`.
  372. struct IfCondition {
  373. static constexpr auto Kind = NodeKind::IfCondition.Define();
  374. IfConditionStartId left_paren;
  375. AnyExprId condition;
  376. };
  377. using IfStatementElse = LeafNode<NodeKind::IfStatementElse>;
  378. // An `if` statement: `if (expr) { ... } else { ... }`.
  379. struct IfStatement {
  380. static constexpr auto Kind =
  381. NodeKind::IfStatement.Define(NodeCategory::Statement);
  382. IfConditionId head;
  383. CodeBlockId then;
  384. struct Else {
  385. IfStatementElseId else_token;
  386. NodeIdOneOf<CodeBlock, IfStatement> body;
  387. };
  388. std::optional<Else> else_clause;
  389. };
  390. using WhileConditionStart = LeafNode<NodeKind::WhileConditionStart>;
  391. // The condition portion of a `while` statement: `(expr)`.
  392. struct WhileCondition {
  393. static constexpr auto Kind = NodeKind::WhileCondition.Define();
  394. WhileConditionStartId left_paren;
  395. AnyExprId condition;
  396. };
  397. // A `while` statement: `while (expr) { ... }`.
  398. struct WhileStatement {
  399. static constexpr auto Kind =
  400. NodeKind::WhileStatement.Define(NodeCategory::Statement);
  401. WhileConditionId head;
  402. CodeBlockId body;
  403. };
  404. using MatchConditionStart = LeafNode<NodeKind::MatchConditionStart>;
  405. struct MatchCondition {
  406. static constexpr auto Kind = NodeKind::MatchCondition.Define();
  407. MatchConditionStartId left_paren;
  408. AnyExprId condition;
  409. };
  410. using MatchIntroducer = LeafNode<NodeKind::MatchIntroducer>;
  411. struct MatchStatementStart {
  412. static constexpr auto Kind = NodeKind::MatchStatementStart.Define();
  413. MatchIntroducerId introducer;
  414. MatchConditionId left_brace;
  415. };
  416. using MatchCaseIntroducer = LeafNode<NodeKind::MatchCaseIntroducer>;
  417. using MatchCaseGuardIntroducer = LeafNode<NodeKind::MatchCaseGuardIntroducer>;
  418. using MatchCaseGuardStart = LeafNode<NodeKind::MatchCaseGuardStart>;
  419. struct MatchCaseGuard {
  420. static constexpr auto Kind = NodeKind::MatchCaseGuard.Define();
  421. MatchCaseGuardIntroducerId introducer;
  422. MatchCaseGuardStartId left_paren;
  423. AnyExprId condition;
  424. };
  425. using MatchCaseEqualGreater = LeafNode<NodeKind::MatchCaseEqualGreater>;
  426. struct MatchCaseStart {
  427. static constexpr auto Kind = NodeKind::MatchCaseStart.Define();
  428. MatchCaseIntroducerId introducer;
  429. AnyPatternId pattern;
  430. std::optional<MatchCaseGuardId> guard;
  431. MatchCaseEqualGreaterId equal_greater_token;
  432. };
  433. struct MatchCase {
  434. static constexpr auto Kind = NodeKind::MatchCase.Define();
  435. MatchCaseStartId head;
  436. llvm::SmallVector<AnyStatementId> statements;
  437. };
  438. using MatchDefaultIntroducer = LeafNode<NodeKind::MatchDefaultIntroducer>;
  439. using MatchDefaultEqualGreater = LeafNode<NodeKind::MatchDefaultEqualGreater>;
  440. struct MatchDefaultStart {
  441. static constexpr auto Kind = NodeKind::MatchDefaultStart.Define();
  442. MatchDefaultIntroducerId introducer;
  443. MatchDefaultEqualGreaterId equal_greater_token;
  444. };
  445. struct MatchDefault {
  446. static constexpr auto Kind = NodeKind::MatchDefault.Define();
  447. MatchDefaultStartId introducer;
  448. llvm::SmallVector<AnyStatementId> statements;
  449. };
  450. // A `match` statement: `match (expr) { case (...) => {...} default => {...}}`.
  451. struct MatchStatement {
  452. static constexpr auto Kind =
  453. NodeKind::MatchStatement.Define(NodeCategory::Statement);
  454. MatchStatementStartId head;
  455. llvm::SmallVector<MatchCaseId> cases;
  456. std::optional<MatchDefaultId> default_case;
  457. };
  458. // Expression nodes
  459. // ----------------
  460. using ArrayExprStart = LeafNode<NodeKind::ArrayExprStart>;
  461. // The start of an array type, `[i32;`.
  462. //
  463. // TODO: Consider flattening this into `ArrayExpr`.
  464. struct ArrayExprSemi {
  465. static constexpr auto Kind = NodeKind::ArrayExprSemi.Define();
  466. ArrayExprStartId left_square;
  467. AnyExprId type;
  468. };
  469. // An array type, such as `[i32; 3]` or `[i32;]`.
  470. struct ArrayExpr {
  471. static constexpr auto Kind = NodeKind::ArrayExpr.Define(NodeCategory::Expr);
  472. ArrayExprSemiId start;
  473. std::optional<AnyExprId> bound;
  474. };
  475. // The opening portion of an indexing expression: `a[`.
  476. //
  477. // TODO: Consider flattening this into `IndexExpr`.
  478. struct IndexExprStart {
  479. static constexpr auto Kind = NodeKind::IndexExprStart.Define();
  480. AnyExprId sequence;
  481. };
  482. // An indexing expression, such as `a[1]`.
  483. struct IndexExpr {
  484. static constexpr auto Kind = NodeKind::IndexExpr.Define(NodeCategory::Expr);
  485. IndexExprStartId start;
  486. AnyExprId index;
  487. };
  488. using ExprOpenParen = LeafNode<NodeKind::ExprOpenParen>;
  489. // A parenthesized expression: `(a)`.
  490. struct ParenExpr {
  491. static constexpr auto Kind =
  492. NodeKind::ParenExpr.Define(NodeCategory::Expr | NodeCategory::MemberExpr);
  493. ExprOpenParenId left_paren;
  494. AnyExprId expr;
  495. };
  496. using TupleLiteralComma = LeafNode<NodeKind::TupleLiteralComma>;
  497. // A tuple literal: `()`, `(a, b, c)`, or `(a,)`.
  498. struct TupleLiteral {
  499. static constexpr auto Kind =
  500. NodeKind::TupleLiteral.Define(NodeCategory::Expr);
  501. ExprOpenParenId left_paren;
  502. CommaSeparatedList<AnyExprId, TupleLiteralCommaId> elements;
  503. };
  504. // The opening portion of a call expression: `F(`.
  505. //
  506. // TODO: Consider flattening this into `CallExpr`.
  507. struct CallExprStart {
  508. static constexpr auto Kind = NodeKind::CallExprStart.Define();
  509. AnyExprId callee;
  510. };
  511. using CallExprComma = LeafNode<NodeKind::CallExprComma>;
  512. // A call expression: `F(a, b, c)`.
  513. struct CallExpr {
  514. static constexpr auto Kind = NodeKind::CallExpr.Define(NodeCategory::Expr);
  515. CallExprStartId start;
  516. CommaSeparatedList<AnyExprId, CallExprCommaId> arguments;
  517. };
  518. // A member access expression: `a.b` or `a.(b)`.
  519. struct MemberAccessExpr {
  520. static constexpr auto Kind =
  521. NodeKind::MemberAccessExpr.Define(NodeCategory::Expr);
  522. AnyExprId lhs;
  523. AnyMemberNameOrMemberExprId rhs;
  524. };
  525. // An indirect member access expression: `a->b` or `a->(b)`.
  526. struct PointerMemberAccessExpr {
  527. static constexpr auto Kind =
  528. NodeKind::PointerMemberAccessExpr.Define(NodeCategory::Expr);
  529. AnyExprId lhs;
  530. AnyMemberNameOrMemberExprId rhs;
  531. };
  532. // A prefix operator expression.
  533. template <const NodeKind& KindT>
  534. struct PrefixOperator {
  535. static constexpr auto Kind = KindT.Define(NodeCategory::Expr);
  536. AnyExprId operand;
  537. };
  538. // An infix operator expression.
  539. template <const NodeKind& KindT>
  540. struct InfixOperator {
  541. static constexpr auto Kind = KindT.Define(NodeCategory::Expr);
  542. AnyExprId lhs;
  543. AnyExprId rhs;
  544. };
  545. // A postfix operator expression.
  546. template <const NodeKind& KindT>
  547. struct PostfixOperator {
  548. static constexpr auto Kind = KindT.Define(NodeCategory::Expr);
  549. AnyExprId operand;
  550. };
  551. // Literals, operators, and modifiers
  552. #define CARBON_PARSE_NODE_KIND(...)
  553. #define CARBON_PARSE_NODE_KIND_TOKEN_LITERAL(Name, ...) \
  554. using Name = LeafNode<NodeKind::Name, NodeCategory::Expr>;
  555. #define CARBON_PARSE_NODE_KIND_TOKEN_MODIFIER(Name, ...) \
  556. using Name##Modifier = \
  557. LeafNode<NodeKind::Name##Modifier, NodeCategory::Modifier>;
  558. #define CARBON_PARSE_NODE_KIND_PREFIX_OPERATOR(Name, ...) \
  559. using PrefixOperator##Name = PrefixOperator<NodeKind::PrefixOperator##Name>;
  560. #define CARBON_PARSE_NODE_KIND_INFIX_OPERATOR(Name, ...) \
  561. using InfixOperator##Name = InfixOperator<NodeKind::InfixOperator##Name>;
  562. #define CARBON_PARSE_NODE_KIND_POSTFIX_OPERATOR(Name, ...) \
  563. using PostfixOperator##Name = \
  564. PostfixOperator<NodeKind::PostfixOperator##Name>;
  565. #include "toolchain/parse/node_kind.def"
  566. // The first operand of a short-circuiting infix operator: `a and` or `a or`.
  567. // The complete operator expression will be an InfixOperator with this as the
  568. // `lhs`.
  569. // TODO: Make this be a template if we ever need to write generic code to cover
  570. // both cases at once, say in check.
  571. struct ShortCircuitOperandAnd {
  572. static constexpr auto Kind = NodeKind::ShortCircuitOperandAnd.Define();
  573. AnyExprId operand;
  574. };
  575. struct ShortCircuitOperandOr {
  576. static constexpr auto Kind = NodeKind::ShortCircuitOperandOr.Define();
  577. AnyExprId operand;
  578. };
  579. struct ShortCircuitOperatorAnd {
  580. static constexpr auto Kind =
  581. NodeKind::ShortCircuitOperatorAnd.Define(NodeCategory::Expr);
  582. ShortCircuitOperandAndId lhs;
  583. AnyExprId rhs;
  584. };
  585. struct ShortCircuitOperatorOr {
  586. static constexpr auto Kind =
  587. NodeKind::ShortCircuitOperatorOr.Define(NodeCategory::Expr);
  588. ShortCircuitOperandOrId lhs;
  589. AnyExprId rhs;
  590. };
  591. // The `if` portion of an `if` expression: `if expr`.
  592. struct IfExprIf {
  593. static constexpr auto Kind = NodeKind::IfExprIf.Define();
  594. AnyExprId condition;
  595. };
  596. // The `then` portion of an `if` expression: `then expr`.
  597. struct IfExprThen {
  598. static constexpr auto Kind = NodeKind::IfExprThen.Define();
  599. AnyExprId result;
  600. };
  601. // A full `if` expression: `if expr then expr else expr`.
  602. struct IfExprElse {
  603. static constexpr auto Kind = NodeKind::IfExprElse.Define(NodeCategory::Expr);
  604. IfExprIfId start;
  605. IfExprThenId then;
  606. AnyExprId else_result;
  607. };
  608. // Choice nodes
  609. // ------------
  610. using ChoiceIntroducer = LeafNode<NodeKind::ChoiceIntroducer>;
  611. struct ChoiceSignature {
  612. static constexpr auto Kind =
  613. NodeKind::ChoiceDefinitionStart.Define(NodeCategory::None);
  614. ChoiceIntroducerId introducer;
  615. llvm::SmallVector<AnyModifierId> modifiers;
  616. AnyNameComponentId name;
  617. std::optional<ImplicitParamListId> implicit_params;
  618. std::optional<TuplePatternId> params;
  619. };
  620. using ChoiceDefinitionStart = ChoiceSignature;
  621. using ChoiceAlternativeListComma =
  622. LeafNode<NodeKind::ChoiceAlternativeListComma>;
  623. struct ChoiceDefinition {
  624. static constexpr auto Kind =
  625. NodeKind::ChoiceDefinition.Define(NodeCategory::Decl);
  626. ChoiceDefinitionStartId signature;
  627. struct Alternative {
  628. IdentifierNameId name;
  629. std::optional<TuplePatternId> parameters;
  630. };
  631. CommaSeparatedList<Alternative, ChoiceAlternativeListCommaId> alternatives;
  632. };
  633. // Struct literals and struct type literals
  634. // ----------------------------------------
  635. // `{`
  636. using StructLiteralOrStructTypeLiteralStart =
  637. LeafNode<NodeKind::StructLiteralOrStructTypeLiteralStart>;
  638. // `,`
  639. using StructComma = LeafNode<NodeKind::StructComma>;
  640. // `.a`
  641. struct StructFieldDesignator {
  642. static constexpr auto Kind = NodeKind::StructFieldDesignator.Define();
  643. NodeIdOneOf<IdentifierName, BaseName> name;
  644. };
  645. // `.a = 0`
  646. struct StructFieldValue {
  647. static constexpr auto Kind = NodeKind::StructFieldValue.Define();
  648. StructFieldDesignatorId designator;
  649. AnyExprId expr;
  650. };
  651. // `.a: i32`
  652. struct StructFieldType {
  653. static constexpr auto Kind = NodeKind::StructFieldType.Define();
  654. StructFieldDesignatorId designator;
  655. AnyExprId type_expr;
  656. };
  657. // Struct literals, such as `{.a = 0}`.
  658. struct StructLiteral {
  659. static constexpr auto Kind =
  660. NodeKind::StructLiteral.Define(NodeCategory::Expr);
  661. StructLiteralOrStructTypeLiteralStartId introducer;
  662. CommaSeparatedList<StructFieldValueId, StructCommaId> fields;
  663. };
  664. // Struct type literals, such as `{.a: i32}`.
  665. struct StructTypeLiteral {
  666. static constexpr auto Kind =
  667. NodeKind::StructTypeLiteral.Define(NodeCategory::Expr);
  668. StructLiteralOrStructTypeLiteralStartId introducer;
  669. CommaSeparatedList<StructFieldTypeId, StructCommaId> fields;
  670. };
  671. // `class` declarations and definitions
  672. // ------------------------------------
  673. // `class`
  674. using ClassIntroducer = LeafNode<NodeKind::ClassIntroducer>;
  675. // A class signature `class C`
  676. template <const NodeKind& KindT, NodeCategory Category>
  677. struct ClassSignature {
  678. static constexpr auto Kind = KindT.Define(Category);
  679. ClassIntroducerId introducer;
  680. llvm::SmallVector<AnyModifierId> modifiers;
  681. AnyNameComponentId name;
  682. std::optional<ImplicitParamListId> implicit_params;
  683. std::optional<TuplePatternId> params;
  684. };
  685. // `class C;`
  686. using ClassDecl = ClassSignature<NodeKind::ClassDecl, NodeCategory::Decl>;
  687. // `class C {`
  688. using ClassDefinitionStart =
  689. ClassSignature<NodeKind::ClassDefinitionStart, NodeCategory::None>;
  690. // `class C { ... }`
  691. struct ClassDefinition {
  692. static constexpr auto Kind =
  693. NodeKind::ClassDefinition.Define(NodeCategory::Decl);
  694. ClassDefinitionStartId signature;
  695. llvm::SmallVector<AnyDeclId> members;
  696. };
  697. // Base class declaration
  698. // ----------------------
  699. // `base`
  700. using BaseIntroducer = LeafNode<NodeKind::BaseIntroducer>;
  701. using BaseColon = LeafNode<NodeKind::BaseColon>;
  702. // `extend base: BaseClass;`
  703. struct BaseDecl {
  704. static constexpr auto Kind = NodeKind::BaseDecl.Define(NodeCategory::Decl);
  705. BaseIntroducerId introducer;
  706. llvm::SmallVector<AnyModifierId> modifiers;
  707. BaseColonId colon;
  708. AnyExprId base_class;
  709. };
  710. // Interface declarations and definitions
  711. // --------------------------------------
  712. // `interface`
  713. using InterfaceIntroducer = LeafNode<NodeKind::InterfaceIntroducer>;
  714. // `interface I`
  715. template <const NodeKind& KindT, NodeCategory Category>
  716. struct InterfaceSignature {
  717. static constexpr auto Kind = KindT.Define(Category);
  718. InterfaceIntroducerId introducer;
  719. llvm::SmallVector<AnyModifierId> modifiers;
  720. AnyNameComponentId name;
  721. std::optional<ImplicitParamListId> implicit_params;
  722. std::optional<TuplePatternId> params;
  723. };
  724. // `interface I;`
  725. using InterfaceDecl =
  726. InterfaceSignature<NodeKind::InterfaceDecl, NodeCategory::Decl>;
  727. // `interface I {`
  728. using InterfaceDefinitionStart =
  729. InterfaceSignature<NodeKind::InterfaceDefinitionStart, NodeCategory::None>;
  730. // `interface I { ... }`
  731. struct InterfaceDefinition {
  732. static constexpr auto Kind =
  733. NodeKind::InterfaceDefinition.Define(NodeCategory::Decl);
  734. InterfaceDefinitionStartId signature;
  735. llvm::SmallVector<AnyDeclId> members;
  736. };
  737. // `impl`...`as` declarations and definitions
  738. // ------------------------------------------
  739. // `impl`
  740. using ImplIntroducer = LeafNode<NodeKind::ImplIntroducer>;
  741. // `forall [...]`
  742. struct ImplForall {
  743. static constexpr auto Kind = NodeKind::ImplForall.Define();
  744. ImplicitParamListId params;
  745. };
  746. // `as` with no type before it
  747. using DefaultSelfImplAs =
  748. LeafNode<NodeKind::DefaultSelfImplAs, NodeCategory::ImplAs>;
  749. // `<type> as`
  750. struct TypeImplAs {
  751. static constexpr auto Kind =
  752. NodeKind::TypeImplAs.Define(NodeCategory::ImplAs);
  753. AnyExprId type_expr;
  754. };
  755. // `impl T as I`
  756. template <const NodeKind& KindT, NodeCategory Category>
  757. struct ImplSignature {
  758. static constexpr auto Kind = KindT.Define(Category);
  759. ImplIntroducerId introducer;
  760. llvm::SmallVector<AnyModifierId> modifiers;
  761. std::optional<ImplForallId> forall;
  762. AnyImplAsId as;
  763. AnyExprId interface;
  764. };
  765. // `impl T as I;`
  766. using ImplDecl = ImplSignature<NodeKind::ImplDecl, NodeCategory::Decl>;
  767. // `impl T as I {`
  768. using ImplDefinitionStart =
  769. ImplSignature<NodeKind::ImplDefinitionStart, NodeCategory::None>;
  770. // `impl T as I { ... }`
  771. struct ImplDefinition {
  772. static constexpr auto Kind =
  773. NodeKind::ImplDefinition.Define(NodeCategory::Decl);
  774. ImplDefinitionStartId signature;
  775. llvm::SmallVector<AnyDeclId> members;
  776. };
  777. // Named constraint declarations and definitions
  778. // ---------------------------------------------
  779. // `constraint`
  780. using NamedConstraintIntroducer = LeafNode<NodeKind::NamedConstraintIntroducer>;
  781. // `constraint NC`
  782. template <const NodeKind& KindT, NodeCategory Category>
  783. struct NamedConstraintSignature {
  784. static constexpr auto Kind = KindT.Define(Category);
  785. NamedConstraintIntroducerId introducer;
  786. llvm::SmallVector<AnyModifierId> modifiers;
  787. AnyNameComponentId name;
  788. std::optional<ImplicitParamListId> implicit_params;
  789. std::optional<TuplePatternId> params;
  790. };
  791. // `constraint NC;`
  792. using NamedConstraintDecl =
  793. NamedConstraintSignature<NodeKind::NamedConstraintDecl, NodeCategory::Decl>;
  794. // `constraint NC {`
  795. using NamedConstraintDefinitionStart =
  796. NamedConstraintSignature<NodeKind::NamedConstraintDefinitionStart,
  797. NodeCategory::None>;
  798. // `constraint NC { ... }`
  799. struct NamedConstraintDefinition {
  800. static constexpr auto Kind =
  801. NodeKind::NamedConstraintDefinition.Define(NodeCategory::Decl);
  802. NamedConstraintDefinitionStartId signature;
  803. llvm::SmallVector<AnyDeclId> members;
  804. };
  805. // ---------------------------------------------------------------------------
  806. // A complete source file. Note that there is no corresponding parse node for
  807. // the file. The file is instead the complete contents of the parse tree.
  808. struct File {
  809. FileStartId start;
  810. llvm::SmallVector<AnyDeclId> decls;
  811. FileEndId end;
  812. };
  813. // Define `Foo` as the node type for the ID type `FooId`.
  814. #define CARBON_PARSE_NODE_KIND(KindName) \
  815. template <> \
  816. struct NodeForId<KindName##Id> { \
  817. using TypedNode = KindName; \
  818. };
  819. #include "toolchain/parse/node_kind.def"
  820. } // namespace Carbon::Parse
  821. #endif // CARBON_TOOLCHAIN_PARSE_TYPED_NODES_H_