parser.ypp 28 KB

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