parser.ypp 30 KB

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