parser.ypp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  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. // -----------------------------------------------------------------------------
  5. // Bison Configuration
  6. // -----------------------------------------------------------------------------
  7. %require "3.2"
  8. %language "c++"
  9. // We don't need a separate header for Bison locations.
  10. %define api.location.file none
  11. // Use a type-safe C++ variant for semantic values
  12. %define api.value.type variant
  13. // Have Bison generate the functions ‘make_TEXT’ and ‘make_NUMBER’, but also
  14. // ‘make_YYEOF’, for the end of input.
  15. %define api.token.constructor
  16. // Generate the parser as `::Carbon::Parser`.
  17. %define api.namespace { Carbon }
  18. %define api.parser.class { Parser }
  19. // Make parse error messages more detailed
  20. %define parse.error verbose
  21. // Enable support for parser debugging
  22. %define parse.trace true
  23. // Generate location structs.
  24. %locations
  25. // Parameters to the parser and lexer.
  26. //
  27. // Parameters to the parser are stored therein as protected data members, and
  28. // thus available to its methods.
  29. // "inout" parameters passed to both the parser and the lexer.
  30. %param {Nonnull<Arena*> arena}
  31. %param {yyscan_t yyscanner}
  32. %param {ParseAndLexContext& context}
  33. // "out" parameter passed to the parser, where the AST is written.
  34. %parse-param {std::optional<AST>* ast}
  35. // No shift-reduce conflicts are expected.
  36. // See README.md#precedence-and-associativity for a description of how
  37. // operator precedence is expressed.
  38. %expect 0
  39. // -----------------------------------------------------------------------------
  40. %code top {
  41. #include <algorithm>
  42. #include <cstdarg>
  43. #include <cstdio>
  44. #include <cstdlib>
  45. #include <vector>
  46. #include "common/check.h"
  47. #include "explorer/syntax/parse_and_lex_context.h"
  48. #include "llvm/ADT/StringExtras.h"
  49. #include "llvm/Support/raw_ostream.h"
  50. } // %code top
  51. %code requires {
  52. #include <optional>
  53. #include "explorer/ast/ast.h"
  54. #include "explorer/ast/declaration.h"
  55. #include "explorer/ast/expression.h"
  56. #include "explorer/ast/paren_contents.h"
  57. #include "explorer/ast/pattern.h"
  58. #include "explorer/ast/value_category.h"
  59. #include "explorer/common/arena.h"
  60. #include "explorer/common/nonnull.h"
  61. #include "explorer/syntax/bison_wrap.h"
  62. namespace Carbon {
  63. class ParseAndLexContext;
  64. } // namespace Carbon
  65. typedef void* yyscan_t;
  66. } // %code requires
  67. %code {
  68. void Carbon::Parser::error(const location_type&, const std::string& message) {
  69. context.RecordSyntaxError(message);
  70. }
  71. } // %code
  72. %token <int> integer_literal
  73. %token <std::string> identifier
  74. %token <IntrinsicExpression::Intrinsic> intrinsic_identifier
  75. %token <std::string> sized_type_literal
  76. %token <std::string> string_literal
  77. %type <std::string> designator
  78. %type <ImplKind> impl_kind
  79. %type <Nonnull<Expression*>> impl_type
  80. %type <std::pair<LibraryName, bool>> package_directive
  81. %type <LibraryName> import_directive
  82. %type <std::vector<LibraryName>> import_directives
  83. %type <std::string> optional_library_path
  84. %type <bool> api_or_impl
  85. %type <Nonnull<Declaration*>> declaration
  86. %type <Nonnull<FunctionDeclaration*>> function_declaration
  87. %type <Nonnull<AliasDeclaration*>> alias_declaration
  88. %type <std::vector<Nonnull<Declaration*>>> declaration_list
  89. %type <Nonnull<Statement*>> statement
  90. %type <Nonnull<If*>> if_statement
  91. %type <std::optional<Nonnull<Block*>>> optional_else
  92. %type <std::pair<Nonnull<Expression*>, bool>> return_expression
  93. %type <Nonnull<Block*>> nonempty_block
  94. %type <Nonnull<Block*>> block
  95. %type <std::vector<Nonnull<Statement*>>> statement_list
  96. %type <Nonnull<Expression*>> primary_expression
  97. %type <Nonnull<Expression*>> postfix_expression
  98. %type <Nonnull<Expression*>> ref_deref_expression
  99. %type <Nonnull<Expression*>> type_expression
  100. %type <Nonnull<Expression*>> fn_type_expression
  101. %type <Nonnull<Expression*>> minus_expression
  102. %type <Nonnull<Expression*>> multiplicative_operand
  103. %type <Nonnull<Expression*>> multiplicative_lhs
  104. %type <Nonnull<Expression*>> multiplicative_expression
  105. %type <Nonnull<Expression*>> additive_operand
  106. %type <Nonnull<Expression*>> additive_lhs
  107. %type <Nonnull<Expression*>> additive_expression
  108. %type <Nonnull<Expression*>> unimpl_expression
  109. %type <Nonnull<Expression*>> value_expression
  110. %type <Nonnull<Expression*>> comparison_operand
  111. %type <Nonnull<Expression*>> comparison_expression
  112. %type <Nonnull<Expression*>> not_expression
  113. %type <Nonnull<Expression*>> predicate_expression
  114. %type <Nonnull<Expression*>> and_or_operand
  115. %type <Nonnull<Expression*>> and_lhs
  116. %type <Nonnull<Expression*>> and_expression
  117. %type <Nonnull<Expression*>> or_lhs
  118. %type <Nonnull<Expression*>> or_expression
  119. %type <Nonnull<Expression*>> statement_expression
  120. %type <Nonnull<Expression*>> if_expression
  121. %type <Nonnull<Expression*>> expression
  122. %type <Nonnull<GenericBinding*>> generic_binding
  123. %type <std::vector<Nonnull<AstNode*>>> deduced_params
  124. %type <std::vector<Nonnull<AstNode*>>> impl_deduced_params
  125. %type <std::vector<Nonnull<AstNode*>>> deduced_param_list
  126. %type <Nonnull<Pattern*>> pattern
  127. %type <Nonnull<Pattern*>> non_expression_pattern
  128. %type <BisonWrap<ReturnTerm>> return_term
  129. %type <Nonnull<Expression*>> paren_expression
  130. %type <Nonnull<StructLiteral*>> struct_literal
  131. %type <std::vector<FieldInitializer>> struct_literal_contents
  132. %type <Nonnull<StructTypeLiteral*>> struct_type_literal
  133. %type <std::vector<FieldInitializer>> struct_type_literal_contents
  134. %type <Nonnull<TupleLiteral*>> tuple
  135. %type <std::string> binding_lhs
  136. %type <std::optional<Nonnull<BindingPattern*>>> receiver
  137. %type <Nonnull<BindingPattern*>> variable_declaration
  138. %type <ParenContents<Expression>> paren_expression_base
  139. %type <ParenContents<Expression>> paren_expression_contents
  140. %type <Nonnull<Pattern*>> paren_pattern
  141. %type <Nonnull<TuplePattern*>> tuple_pattern
  142. %type <Nonnull<TuplePattern*>> maybe_empty_tuple_pattern
  143. %type <std::optional<Nonnull<TuplePattern*>>> type_params
  144. %type <ParenContents<Pattern>> paren_pattern_base
  145. %type <ParenContents<Pattern>> paren_pattern_contents
  146. %type <Nonnull<AlternativeSignature*>> alternative
  147. %type <std::vector<Nonnull<AlternativeSignature*>>> alternative_list
  148. %type <std::vector<Nonnull<AlternativeSignature*>>> alternative_list_contents
  149. %type <BisonWrap<Match::Clause>> clause
  150. %type <std::vector<Match::Clause>> clause_list
  151. %token
  152. // Most tokens have their spelling defined in lexer.lpp.
  153. // table-begin
  154. ALIAS
  155. AMPERSAND
  156. AND
  157. API
  158. ARROW
  159. AS
  160. AUTO
  161. AWAIT
  162. BOOL
  163. BREAK
  164. CASE
  165. CHOICE
  166. CLASS
  167. COLON
  168. COLON_BANG
  169. COMMA
  170. CONTINUATION
  171. CONTINUATION_TYPE
  172. CONTINUE
  173. DEFAULT
  174. DOUBLE_ARROW
  175. ELSE
  176. EQUAL
  177. EQUAL_EQUAL
  178. EXTERNAL
  179. FALSE
  180. FN
  181. FN_TYPE
  182. FORALL
  183. IF
  184. IMPL
  185. IMPORT
  186. INTERFACE
  187. LEFT_CURLY_BRACE
  188. LEFT_PARENTHESIS
  189. LEFT_SQUARE_BRACKET
  190. LET
  191. LIBRARY
  192. MATCH
  193. MINUS
  194. NOT
  195. OR
  196. PACKAGE
  197. PERIOD
  198. PLUS
  199. RETURN
  200. RIGHT_CURLY_BRACE
  201. RIGHT_PARENTHESIS
  202. RIGHT_SQUARE_BRACKET
  203. RUN
  204. SELF
  205. SEMICOLON
  206. SLASH
  207. STRING
  208. THEN
  209. TRUE
  210. TYPE
  211. UNDERSCORE
  212. UNIMPL_EXAMPLE
  213. VAR
  214. WHILE
  215. // table-end
  216. // Used to track EOF.
  217. END_OF_FILE 0
  218. // Only used for precedence.
  219. FNARROW "-> in return type"
  220. // The lexer determines the arity and fixity of each `*` based on whitespace
  221. // and adjacent tokens. UNARY_STAR indicates that the operator is unary but
  222. // could be either prefix or postfix.
  223. UNARY_STAR "unary *"
  224. PREFIX_STAR "prefix *"
  225. POSTFIX_STAR "postfix *"
  226. BINARY_STAR "binary *"
  227. ;
  228. %start input
  229. %%
  230. input: package_directive import_directives declaration_list
  231. {
  232. *ast = AST({.package = $1.first,
  233. .is_api = $1.second,
  234. .imports = std::move($2),
  235. .declarations = std::move($3)});
  236. }
  237. ;
  238. package_directive:
  239. PACKAGE identifier optional_library_path api_or_impl SEMICOLON
  240. { $$ = {LibraryName({.package = $2, .path = $3}), $4}; }
  241. ;
  242. import_directive:
  243. IMPORT identifier optional_library_path SEMICOLON
  244. { $$ = LibraryName({.package = $2, .path = $3}); }
  245. ;
  246. import_directives:
  247. // Empty
  248. { $$ = std::vector<LibraryName>(); }
  249. | import_directives import_directive
  250. {
  251. $$ = std::move($1);
  252. $$.push_back($2);
  253. }
  254. ;
  255. optional_library_path:
  256. // Empty
  257. { $$ = ""; }
  258. | LIBRARY string_literal
  259. { $$ = $2; }
  260. ;
  261. api_or_impl:
  262. API
  263. { $$ = true; }
  264. | IMPL
  265. { $$ = false; }
  266. ;
  267. primary_expression:
  268. identifier
  269. { $$ = arena->New<IdentifierExpression>(context.source_loc(), $1); }
  270. | integer_literal
  271. { $$ = arena->New<IntLiteral>(context.source_loc(), $1); }
  272. | string_literal
  273. { $$ = arena->New<StringLiteral>(context.source_loc(), $1); }
  274. | TRUE
  275. { $$ = arena->New<BoolLiteral>(context.source_loc(), true); }
  276. | FALSE
  277. { $$ = arena->New<BoolLiteral>(context.source_loc(), false); }
  278. | sized_type_literal
  279. {
  280. int val;
  281. CARBON_CHECK(llvm::to_integer(llvm::StringRef($1).substr(1), val));
  282. CARBON_CHECK($1[0] == 'i' && val == 32)
  283. << "Only i32 is supported for now: " << $1;
  284. $$ = arena->New<IntTypeLiteral>(context.source_loc());
  285. }
  286. | SELF
  287. // FIXME: Should we create a new TypeLiteral for `Self`?
  288. { $$ = arena->New<IdentifierExpression>(context.source_loc(), "Self"); }
  289. | STRING
  290. { $$ = arena->New<StringTypeLiteral>(context.source_loc()); }
  291. | BOOL
  292. { $$ = arena->New<BoolTypeLiteral>(context.source_loc()); }
  293. | TYPE
  294. { $$ = arena->New<TypeTypeLiteral>(context.source_loc()); }
  295. | CONTINUATION_TYPE
  296. { $$ = arena->New<ContinuationTypeLiteral>(context.source_loc()); }
  297. | paren_expression { $$ = $1; }
  298. | struct_literal { $$ = $1; }
  299. | struct_type_literal { $$ = $1; }
  300. | LEFT_SQUARE_BRACKET expression SEMICOLON expression RIGHT_SQUARE_BRACKET
  301. { $$ = arena->New<ArrayTypeLiteral>(context.source_loc(), $2, $4); }
  302. ;
  303. postfix_expression:
  304. primary_expression
  305. | postfix_expression designator
  306. { $$ = arena->New<FieldAccessExpression>(context.source_loc(), $1, $2); }
  307. | postfix_expression PERIOD LEFT_PARENTHESIS expression RIGHT_PARENTHESIS
  308. {
  309. $$ = arena->New<CompoundFieldAccessExpression>(context.source_loc(), $1,
  310. $4);
  311. }
  312. | postfix_expression LEFT_SQUARE_BRACKET expression RIGHT_SQUARE_BRACKET
  313. { $$ = arena->New<IndexExpression>(context.source_loc(), $1, $3); }
  314. | intrinsic_identifier tuple
  315. { $$ = arena->New<IntrinsicExpression>($1, $2, context.source_loc()); }
  316. | postfix_expression tuple
  317. { $$ = arena->New<CallExpression>(context.source_loc(), $1, $2); }
  318. | postfix_expression POSTFIX_STAR
  319. {
  320. $$ = arena->New<PrimitiveOperatorExpression>(
  321. context.source_loc(), Operator::Ptr,
  322. std::vector<Nonnull<Expression*>>({$1}));
  323. }
  324. | postfix_expression UNARY_STAR
  325. {
  326. $$ = arena->New<PrimitiveOperatorExpression>(
  327. context.source_loc(), Operator::Ptr,
  328. std::vector<Nonnull<Expression*>>({$1}));
  329. }
  330. ;
  331. ref_deref_expression:
  332. postfix_expression
  333. | PREFIX_STAR ref_deref_expression
  334. {
  335. $$ = arena->New<PrimitiveOperatorExpression>(
  336. context.source_loc(), Operator::Deref,
  337. std::vector<Nonnull<Expression*>>({$2}));
  338. }
  339. | UNARY_STAR ref_deref_expression
  340. {
  341. $$ = arena->New<PrimitiveOperatorExpression>(
  342. context.source_loc(), Operator::Deref,
  343. std::vector<Nonnull<Expression*>>({$2}));
  344. }
  345. | AMPERSAND ref_deref_expression
  346. {
  347. $$ = arena->New<PrimitiveOperatorExpression>(
  348. context.source_loc(), Operator::AddressOf,
  349. std::vector<Nonnull<Expression*>>({$2}));
  350. }
  351. ;
  352. fn_type_expression:
  353. FN_TYPE tuple ARROW type_expression
  354. { $$ = arena->New<FunctionTypeLiteral>(context.source_loc(), $2, $4); }
  355. ;
  356. type_expression:
  357. ref_deref_expression
  358. | fn_type_expression
  359. ;
  360. minus_expression:
  361. // ref_deref_expression excluded due to precedence diamond.
  362. MINUS ref_deref_expression
  363. {
  364. $$ = arena->New<PrimitiveOperatorExpression>(
  365. context.source_loc(), Operator::Neg,
  366. std::vector<Nonnull<Expression*>>({$2}));
  367. }
  368. ;
  369. multiplicative_operand:
  370. ref_deref_expression
  371. | minus_expression
  372. ;
  373. multiplicative_lhs:
  374. ref_deref_expression
  375. | multiplicative_expression
  376. ;
  377. multiplicative_expression:
  378. minus_expression
  379. | multiplicative_lhs BINARY_STAR multiplicative_operand
  380. {
  381. $$ = arena->New<PrimitiveOperatorExpression>(
  382. context.source_loc(), Operator::Mul,
  383. std::vector<Nonnull<Expression*>>({$1, $3}));
  384. }
  385. ;
  386. additive_operand:
  387. ref_deref_expression
  388. | multiplicative_expression
  389. ;
  390. additive_lhs:
  391. ref_deref_expression
  392. | additive_expression
  393. ;
  394. additive_expression:
  395. multiplicative_expression
  396. | additive_lhs PLUS additive_operand
  397. {
  398. $$ = arena->New<PrimitiveOperatorExpression>(
  399. context.source_loc(), Operator::Add,
  400. std::vector<Nonnull<Expression*>>({$1, $3}));
  401. }
  402. | additive_lhs MINUS additive_operand
  403. {
  404. $$ = arena->New<PrimitiveOperatorExpression>(
  405. context.source_loc(), Operator::Sub,
  406. std::vector<Nonnull<Expression*>>({$1, $3}));
  407. }
  408. ;
  409. unimpl_expression:
  410. // ref_deref_expression excluded due to precedence diamond.
  411. ref_deref_expression UNIMPL_EXAMPLE ref_deref_expression
  412. {
  413. $$ = arena->New<UnimplementedExpression>(context.source_loc(),
  414. "ExampleInfix", $1, $3);
  415. }
  416. ;
  417. value_expression:
  418. // ref_deref_expression excluded due to precedence diamond.
  419. additive_expression
  420. | fn_type_expression
  421. | unimpl_expression
  422. ;
  423. comparison_operand:
  424. ref_deref_expression
  425. | value_expression
  426. ;
  427. comparison_expression:
  428. value_expression
  429. | comparison_operand EQUAL_EQUAL comparison_operand
  430. {
  431. $$ = arena->New<PrimitiveOperatorExpression>(
  432. context.source_loc(), Operator::Eq,
  433. std::vector<Nonnull<Expression*>>({$1, $3}));
  434. }
  435. ;
  436. not_expression:
  437. NOT ref_deref_expression
  438. {
  439. $$ = arena->New<PrimitiveOperatorExpression>(
  440. context.source_loc(), Operator::Not,
  441. std::vector<Nonnull<Expression*>>({$2}));
  442. }
  443. ;
  444. predicate_expression:
  445. // ref_deref_expression excluded due to precedence diamond.
  446. not_expression
  447. | comparison_expression
  448. ;
  449. and_or_operand:
  450. ref_deref_expression
  451. | predicate_expression
  452. ;
  453. and_lhs:
  454. and_or_operand
  455. | and_expression
  456. ;
  457. and_expression:
  458. // predicate_expression excluded due to precedence diamond.
  459. and_lhs AND and_or_operand
  460. {
  461. $$ = arena->New<PrimitiveOperatorExpression>(
  462. context.source_loc(), Operator::And,
  463. std::vector<Nonnull<Expression*>>({$1, $3}));
  464. }
  465. ;
  466. or_lhs:
  467. and_or_operand
  468. | or_expression
  469. ;
  470. or_expression:
  471. // predicate_expression excluded due to precedence diamond.
  472. or_lhs OR and_or_operand
  473. {
  474. $$ = arena->New<PrimitiveOperatorExpression>(
  475. context.source_loc(), Operator::Or,
  476. std::vector<Nonnull<Expression*>>({$1, $3}));
  477. }
  478. ;
  479. statement_expression:
  480. ref_deref_expression
  481. | predicate_expression
  482. | and_expression
  483. | or_expression
  484. ;
  485. if_expression:
  486. statement_expression
  487. | IF expression THEN if_expression ELSE if_expression
  488. { $$ = arena->New<IfExpression>(context.source_loc(), $2, $4, $6); }
  489. ;
  490. expression:
  491. if_expression
  492. ;
  493. designator: PERIOD identifier { $$ = $2; }
  494. ;
  495. paren_expression: paren_expression_base
  496. { $$ = ExpressionFromParenContents(arena, context.source_loc(), $1); }
  497. ;
  498. tuple: paren_expression_base
  499. { $$ = TupleExpressionFromParenContents(arena, context.source_loc(), $1); }
  500. ;
  501. paren_expression_base:
  502. LEFT_PARENTHESIS RIGHT_PARENTHESIS
  503. { $$ = {.elements = {}, .has_trailing_comma = false}; }
  504. | LEFT_PARENTHESIS paren_expression_contents RIGHT_PARENTHESIS
  505. { $$ = $2; }
  506. | LEFT_PARENTHESIS paren_expression_contents COMMA RIGHT_PARENTHESIS
  507. {
  508. $$ = $2;
  509. $$.has_trailing_comma = true;
  510. }
  511. ;
  512. paren_expression_contents:
  513. expression
  514. { $$ = {.elements = {$1}, .has_trailing_comma = false}; }
  515. | paren_expression_contents COMMA expression
  516. {
  517. $$ = $1;
  518. $$.elements.push_back($3);
  519. }
  520. ;
  521. struct_literal:
  522. LEFT_CURLY_BRACE struct_literal_contents RIGHT_CURLY_BRACE
  523. { $$ = arena->New<StructLiteral>(context.source_loc(), $2); }
  524. | LEFT_CURLY_BRACE struct_literal_contents COMMA RIGHT_CURLY_BRACE
  525. { $$ = arena->New<StructLiteral>(context.source_loc(), $2); }
  526. ;
  527. struct_literal_contents:
  528. designator EQUAL expression
  529. { $$ = {FieldInitializer($1, $3)}; }
  530. | struct_literal_contents COMMA designator EQUAL expression
  531. {
  532. $$ = $1;
  533. $$.push_back(FieldInitializer($3, $5));
  534. }
  535. ;
  536. struct_type_literal:
  537. LEFT_CURLY_BRACE RIGHT_CURLY_BRACE
  538. { $$ = arena->New<StructTypeLiteral>(context.source_loc()); }
  539. | LEFT_CURLY_BRACE struct_type_literal_contents RIGHT_CURLY_BRACE
  540. { $$ = arena->New<StructTypeLiteral>(context.source_loc(), $2); }
  541. | LEFT_CURLY_BRACE struct_type_literal_contents COMMA RIGHT_CURLY_BRACE
  542. { $$ = arena->New<StructTypeLiteral>(context.source_loc(), $2); }
  543. ;
  544. struct_type_literal_contents:
  545. designator COLON expression
  546. { $$ = {FieldInitializer($1, $3)}; }
  547. | struct_type_literal_contents COMMA designator COLON expression
  548. {
  549. $$ = $1;
  550. $$.push_back(FieldInitializer($3, $5));
  551. }
  552. ;
  553. // In many cases, using `pattern` recursively will result in ambiguities.
  554. // When that happens, it's necessary to factor out two separate productions,
  555. // one for when the sub-pattern is an expression, and one for when it is not.
  556. // To facilitate this, non-terminals besides `pattern` whose names contain
  557. // `pattern` are structured to be disjoint from `expression`, unless otherwise
  558. // specified.
  559. pattern:
  560. non_expression_pattern
  561. { $$ = $1; }
  562. | expression
  563. { $$ = arena->New<ExpressionPattern>($1); }
  564. ;
  565. non_expression_pattern:
  566. AUTO
  567. { $$ = arena->New<AutoPattern>(context.source_loc()); }
  568. | binding_lhs COLON pattern
  569. {
  570. $$ = arena->New<BindingPattern>(context.source_loc(), $1, $3,
  571. std::nullopt);
  572. }
  573. | binding_lhs COLON_BANG expression
  574. { $$ = arena->New<GenericBinding>(context.source_loc(), $1, $3); }
  575. | paren_pattern
  576. { $$ = $1; }
  577. | postfix_expression tuple_pattern
  578. {
  579. ErrorOr<Nonnull<AlternativePattern*>> alternative_pattern =
  580. AlternativePattern::Create(arena, context.source_loc(), $1, $2);
  581. if (alternative_pattern.ok()) {
  582. $$ = *alternative_pattern;
  583. } else {
  584. context.RecordSyntaxError(alternative_pattern.error().message());
  585. YYERROR;
  586. }
  587. }
  588. | VAR non_expression_pattern
  589. { $$ = arena->New<VarPattern>(context.source_loc(), $2); }
  590. ;
  591. binding_lhs:
  592. identifier { $$ = $1; }
  593. | UNDERSCORE { $$ = AnonymousName; }
  594. ;
  595. paren_pattern: paren_pattern_base
  596. { $$ = PatternFromParenContents(arena, context.source_loc(), $1); }
  597. ;
  598. paren_pattern_base:
  599. LEFT_PARENTHESIS paren_pattern_contents RIGHT_PARENTHESIS
  600. { $$ = $2; }
  601. | LEFT_PARENTHESIS paren_pattern_contents COMMA RIGHT_PARENTHESIS
  602. {
  603. $$ = $2;
  604. $$.has_trailing_comma = true;
  605. }
  606. ;
  607. // paren_pattern is analogous to paren_expression, but in order to avoid
  608. // ambiguities, it must be disjoint from paren_expression, meaning it must
  609. // contain at least one non_expression_pattern. The structure of this rule
  610. // is very different from the corresponding expression rule because is has to
  611. // enforce that requirement.
  612. paren_pattern_contents:
  613. non_expression_pattern
  614. { $$ = {.elements = {$1}, .has_trailing_comma = false}; }
  615. | paren_expression_contents COMMA non_expression_pattern
  616. {
  617. $$ = ParenExpressionToParenPattern(arena, $1);
  618. $$.elements.push_back($3);
  619. }
  620. | paren_pattern_contents COMMA expression
  621. {
  622. $$ = $1;
  623. $$.elements.push_back(arena->New<ExpressionPattern>($3));
  624. }
  625. | paren_pattern_contents COMMA non_expression_pattern
  626. {
  627. $$ = $1;
  628. $$.elements.push_back($3);
  629. }
  630. ;
  631. tuple_pattern: paren_pattern_base
  632. { $$ = TuplePatternFromParenContents(arena, context.source_loc(), $1); }
  633. ;
  634. // Unlike most `pattern` nonterminals, this one overlaps with `expression`,
  635. // so it should be used only when prior context (such as an introducer)
  636. // rules out the possibility of an `expression` at this point.
  637. maybe_empty_tuple_pattern:
  638. LEFT_PARENTHESIS RIGHT_PARENTHESIS
  639. {
  640. $$ = arena->New<TuplePattern>(context.source_loc(),
  641. std::vector<Nonnull<Pattern*>>());
  642. }
  643. | tuple_pattern
  644. { $$ = $1; }
  645. ;
  646. clause:
  647. CASE pattern DOUBLE_ARROW statement
  648. { $$ = Match::Clause($2, $4); }
  649. | DEFAULT DOUBLE_ARROW statement
  650. {
  651. $$ = Match::Clause(arena->New<BindingPattern>(
  652. context.source_loc(), std::string(AnonymousName),
  653. arena->New<AutoPattern>(context.source_loc()),
  654. ValueCategory::Let),
  655. $3);
  656. }
  657. ;
  658. clause_list:
  659. // Empty
  660. { $$ = {}; }
  661. | clause_list clause
  662. {
  663. $$ = $1;
  664. $$.push_back($2);
  665. }
  666. ;
  667. statement:
  668. statement_expression EQUAL expression SEMICOLON
  669. { $$ = arena->New<Assign>(context.source_loc(), $1, $3); }
  670. | VAR pattern EQUAL expression SEMICOLON
  671. {
  672. $$ = arena->New<VariableDefinition>(context.source_loc(), $2, $4,
  673. ValueCategory::Var);
  674. }
  675. | LET pattern EQUAL expression SEMICOLON
  676. {
  677. $$ = arena->New<VariableDefinition>(context.source_loc(), $2, $4,
  678. ValueCategory::Let);
  679. }
  680. | statement_expression SEMICOLON
  681. { $$ = arena->New<ExpressionStatement>(context.source_loc(), $1); }
  682. | if_statement
  683. { $$ = $1; }
  684. | WHILE LEFT_PARENTHESIS expression RIGHT_PARENTHESIS block
  685. { $$ = arena->New<While>(context.source_loc(), $3, $5); }
  686. | BREAK SEMICOLON
  687. { $$ = arena->New<Break>(context.source_loc()); }
  688. | CONTINUE SEMICOLON
  689. { $$ = arena->New<Continue>(context.source_loc()); }
  690. | RETURN return_expression SEMICOLON
  691. {
  692. auto [return_exp, is_omitted_exp] = $2;
  693. $$ = arena->New<Return>(context.source_loc(), return_exp, is_omitted_exp);
  694. }
  695. // We disallow empty blocks in places where an arbitrary statement can occur
  696. // in order to avoid ambiguity with the empty struct literal `{}`. We can
  697. // allow non-empty blocks because a non-empty struct literal always starts with
  698. // a designator, and a block never does, so one token of lookahead suffices
  699. // to disambiguate. As of this writing, the "official" resolution of this
  700. // ambiguity is an open question (see
  701. // https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/classes.md#literals)
  702. | nonempty_block
  703. { $$ = $1; }
  704. | MATCH LEFT_PARENTHESIS expression RIGHT_PARENTHESIS LEFT_CURLY_BRACE
  705. clause_list RIGHT_CURLY_BRACE
  706. { $$ = arena->New<Match>(context.source_loc(), $3, $6); }
  707. | CONTINUATION identifier block
  708. { $$ = arena->New<Continuation>(context.source_loc(), $2, $3); }
  709. | RUN expression SEMICOLON
  710. { $$ = arena->New<Run>(context.source_loc(), $2); }
  711. | AWAIT SEMICOLON
  712. { $$ = arena->New<Await>(context.source_loc()); }
  713. ;
  714. if_statement:
  715. IF LEFT_PARENTHESIS expression RIGHT_PARENTHESIS block optional_else
  716. { $$ = arena->New<If>(context.source_loc(), $3, $5, $6); }
  717. ;
  718. optional_else:
  719. // Empty
  720. { $$ = std::nullopt; }
  721. | ELSE if_statement
  722. {
  723. $$ = arena->New<Block>(context.source_loc(),
  724. std::vector<Nonnull<Statement*>>({$2}));
  725. }
  726. | ELSE block
  727. { $$ = $2; }
  728. ;
  729. return_expression:
  730. // Empty
  731. { $$ = {arena->New<TupleLiteral>(context.source_loc()), true}; }
  732. | expression
  733. { $$ = {$1, false}; }
  734. ;
  735. statement_list:
  736. // Empty
  737. { $$ = {}; }
  738. | statement_list statement
  739. {
  740. $$ = std::move($1);
  741. $$.push_back($2);
  742. }
  743. ;
  744. block:
  745. LEFT_CURLY_BRACE statement_list RIGHT_CURLY_BRACE
  746. { $$ = arena->New<Block>(context.source_loc(), std::move($2)); }
  747. ;
  748. nonempty_block:
  749. LEFT_CURLY_BRACE statement_list statement RIGHT_CURLY_BRACE
  750. {
  751. $2.push_back($3);
  752. $$ = arena->New<Block>(context.source_loc(), std::move($2));
  753. }
  754. ;
  755. return_term:
  756. // Empty
  757. { $$ = ReturnTerm::Omitted(context.source_loc()); }
  758. | ARROW AUTO
  759. { $$ = ReturnTerm::Auto(context.source_loc()); }
  760. | ARROW expression
  761. { $$ = ReturnTerm::Explicit($2); }
  762. ;
  763. generic_binding:
  764. identifier COLON_BANG expression
  765. {
  766. $$ = arena->New<GenericBinding>(context.source_loc(), std::move($1), $3);
  767. }
  768. ;
  769. deduced_param_list:
  770. // Empty
  771. { $$ = std::vector<Nonnull<AstNode*>>(); }
  772. | generic_binding
  773. {
  774. $$ = std::vector<Nonnull<AstNode*>>();
  775. $$.push_back($1);
  776. }
  777. | deduced_param_list COMMA generic_binding
  778. {
  779. $$ = $1;
  780. $$.push_back($3);
  781. }
  782. | variable_declaration
  783. {
  784. $$ = std::vector<Nonnull<AstNode*>>();
  785. $$.push_back($1);
  786. }
  787. | deduced_param_list COMMA variable_declaration
  788. {
  789. $$ = $1;
  790. $$.push_back($3);
  791. }
  792. ;
  793. deduced_params:
  794. // Empty
  795. { $$ = std::vector<Nonnull<AstNode*>>(); }
  796. | LEFT_SQUARE_BRACKET deduced_param_list RIGHT_SQUARE_BRACKET
  797. { $$ = $2; }
  798. ;
  799. impl_deduced_params:
  800. // Empty
  801. { $$ = std::vector<Nonnull<AstNode*>>(); }
  802. | FORALL LEFT_SQUARE_BRACKET deduced_param_list RIGHT_SQUARE_BRACKET
  803. { $$ = $3; }
  804. ;
  805. receiver:
  806. // Empty
  807. { $$ = std::nullopt; }
  808. | LEFT_CURLY_BRACE variable_declaration RIGHT_CURLY_BRACE
  809. { $$ = $2; }
  810. ;
  811. function_declaration:
  812. FN identifier deduced_params receiver maybe_empty_tuple_pattern return_term block
  813. {
  814. ErrorOr<FunctionDeclaration*> fn = FunctionDeclaration::Create(
  815. arena, context.source_loc(), $2, $3, $4, $5, $6, $7);
  816. if (fn.ok()) {
  817. $$ = *fn;
  818. } else {
  819. context.RecordSyntaxError(fn.error().message());
  820. YYERROR;
  821. }
  822. }
  823. | FN identifier deduced_params receiver maybe_empty_tuple_pattern return_term SEMICOLON
  824. {
  825. ErrorOr<FunctionDeclaration*> fn = FunctionDeclaration::Create(
  826. arena, context.source_loc(), $2, $3, $4, $5, $6, std::nullopt);
  827. if (fn.ok()) {
  828. $$ = *fn;
  829. } else {
  830. context.RecordSyntaxError(fn.error().message());
  831. YYERROR;
  832. }
  833. }
  834. ;
  835. variable_declaration: identifier COLON pattern
  836. {
  837. $$ = arena->New<BindingPattern>(context.source_loc(), $1, $3,
  838. std::nullopt);
  839. }
  840. ;
  841. alias_declaration: ALIAS identifier EQUAL expression SEMICOLON
  842. { $$ = arena->New<AliasDeclaration>(context.source_loc(), $2, $4); }
  843. ;
  844. alternative:
  845. identifier tuple
  846. { $$ = arena->New<AlternativeSignature>(context.source_loc(), $1, $2); }
  847. | identifier
  848. {
  849. $$ = arena->New<AlternativeSignature>(
  850. context.source_loc(), $1,
  851. arena->New<TupleLiteral>(context.source_loc()));
  852. }
  853. ;
  854. alternative_list:
  855. // Empty
  856. { $$ = {}; }
  857. | alternative_list_contents
  858. { $$ = $1; }
  859. | alternative_list_contents COMMA
  860. { $$ = $1; }
  861. ;
  862. alternative_list_contents:
  863. alternative
  864. { $$ = {std::move($1)}; }
  865. | alternative_list_contents COMMA alternative
  866. {
  867. $$ = $1;
  868. $$.push_back(std::move($3));
  869. }
  870. ;
  871. type_params:
  872. // Empty
  873. { $$ = std::nullopt; }
  874. | tuple_pattern
  875. { $$ = $1; }
  876. ;
  877. declaration:
  878. function_declaration
  879. { $$ = $1; }
  880. | CLASS identifier type_params LEFT_CURLY_BRACE declaration_list RIGHT_CURLY_BRACE
  881. {
  882. $$ = arena->New<ClassDeclaration>(
  883. context.source_loc(), $2,
  884. arena->New<SelfDeclaration>(context.source_loc()), $3, $5);
  885. }
  886. | CHOICE identifier LEFT_CURLY_BRACE alternative_list RIGHT_CURLY_BRACE
  887. { $$ = arena->New<ChoiceDeclaration>(context.source_loc(), $2, $4); }
  888. | VAR variable_declaration SEMICOLON
  889. {
  890. $$ = arena->New<VariableDeclaration>(context.source_loc(), $2,
  891. std::nullopt, ValueCategory::Var);
  892. }
  893. | VAR variable_declaration EQUAL expression SEMICOLON
  894. {
  895. $$ = arena->New<VariableDeclaration>(context.source_loc(), $2, $4,
  896. ValueCategory::Var);
  897. }
  898. | LET variable_declaration EQUAL expression SEMICOLON
  899. {
  900. $$ = arena->New<VariableDeclaration>(context.source_loc(), $2, $4,
  901. ValueCategory::Let);
  902. }
  903. | INTERFACE identifier type_params LEFT_CURLY_BRACE declaration_list RIGHT_CURLY_BRACE
  904. {
  905. // TODO: Type of `Self` should be the interface being declared, not
  906. // `Type`.
  907. auto ty_ty = arena -> New<TypeTypeLiteral>(context.source_loc());
  908. // FIXME: Should this be switched to use a `SelfDeclaration` instead?
  909. auto self =
  910. arena -> New<GenericBinding>(context.source_loc(), "Self", ty_ty);
  911. $$ = arena->New<InterfaceDeclaration>(context.source_loc(), $2, $3, self,
  912. $5);
  913. }
  914. | impl_kind IMPL impl_deduced_params impl_type AS expression LEFT_CURLY_BRACE declaration_list RIGHT_CURLY_BRACE
  915. {
  916. ErrorOr<ImplDeclaration*> impl = ImplDeclaration::Create(
  917. arena, context.source_loc(), $1, $4, $6, $3, $8);
  918. if (impl.ok()) {
  919. $$ = *impl;
  920. } else {
  921. context.RecordSyntaxError(impl.error().message());
  922. YYERROR;
  923. }
  924. }
  925. | alias_declaration
  926. { $$ = $1; }
  927. ;
  928. impl_kind:
  929. // Internal
  930. { $$ = Carbon::ImplKind::InternalImpl; }
  931. | EXTERNAL
  932. { $$ = Carbon::ImplKind::ExternalImpl; }
  933. ;
  934. impl_type:
  935. // Self
  936. { $$ = arena->New<IdentifierExpression>(context.source_loc(), "Self"); }
  937. | expression
  938. ;
  939. declaration_list:
  940. // Empty
  941. { $$ = {}; }
  942. | declaration_list declaration
  943. {
  944. $$ = $1;
  945. $$.push_back(Nonnull<Declaration*>($2));
  946. }
  947. ;
  948. %%