parser_handle_expression.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. #include "toolchain/parser/parser_context.h"
  5. namespace Carbon {
  6. CARBON_DIAGNOSTIC(
  7. OperatorRequiresParentheses, Error,
  8. "Parentheses are required to disambiguate operator precedence.");
  9. auto ParserHandleExpression(ParserContext& context) -> void {
  10. auto state = context.PopState();
  11. // Check for a prefix operator.
  12. if (auto operator_precedence =
  13. PrecedenceGroup::ForLeading(context.PositionKind())) {
  14. if (PrecedenceGroup::GetPriority(state.ambient_precedence,
  15. *operator_precedence) !=
  16. OperatorPriority::RightFirst) {
  17. // The precedence rules don't permit this prefix operator in this
  18. // context. Diagnose this, but carry on and parse it anyway.
  19. context.emitter().Emit(*context.position(), OperatorRequiresParentheses);
  20. } else {
  21. // Check that this operator follows the proper whitespace rules.
  22. context.DiagnoseOperatorFixity(ParserContext::OperatorFixity::Prefix);
  23. }
  24. if (context.PositionIs(TokenKind::If)) {
  25. context.PushState(ParserState::IfExpressionFinish);
  26. context.PushState(ParserState::IfExpressionFinishCondition);
  27. } else {
  28. context.PushStateForExpressionLoop(ParserState::ExpressionLoopForPrefix,
  29. state.ambient_precedence,
  30. *operator_precedence);
  31. }
  32. ++context.position();
  33. context.PushStateForExpression(*operator_precedence);
  34. } else {
  35. context.PushStateForExpressionLoop(ParserState::ExpressionLoop,
  36. state.ambient_precedence,
  37. PrecedenceGroup::ForPostfixExpression());
  38. context.PushState(ParserState::ExpressionInPostfix);
  39. }
  40. }
  41. auto ParserHandleExpressionInPostfix(ParserContext& context) -> void {
  42. auto state = context.PopState();
  43. // Continue to the loop state.
  44. state.state = ParserState::ExpressionInPostfixLoop;
  45. // Parses a primary expression, which is either a terminal portion of an
  46. // expression tree, such as an identifier or literal, or a parenthesized
  47. // expression.
  48. switch (context.PositionKind()) {
  49. case TokenKind::Identifier: {
  50. context.AddLeafNode(ParseNodeKind::NameReference, context.Consume());
  51. context.PushState(state);
  52. break;
  53. }
  54. case TokenKind::False:
  55. case TokenKind::True:
  56. case TokenKind::IntegerLiteral:
  57. case TokenKind::RealLiteral:
  58. case TokenKind::StringLiteral:
  59. case TokenKind::Bool:
  60. case TokenKind::IntegerTypeLiteral:
  61. case TokenKind::UnsignedIntegerTypeLiteral:
  62. case TokenKind::FloatingPointTypeLiteral:
  63. case TokenKind::StringTypeLiteral: {
  64. context.AddLeafNode(ParseNodeKind::Literal, context.Consume());
  65. context.PushState(state);
  66. break;
  67. }
  68. case TokenKind::OpenCurlyBrace: {
  69. context.PushState(state);
  70. context.PushState(ParserState::BraceExpression);
  71. break;
  72. }
  73. case TokenKind::OpenParen: {
  74. context.PushState(state);
  75. context.PushState(ParserState::ParenExpression);
  76. break;
  77. }
  78. case TokenKind::SelfValueIdentifier: {
  79. context.AddLeafNode(ParseNodeKind::SelfValueIdentifier,
  80. context.Consume());
  81. context.PushState(state);
  82. break;
  83. }
  84. case TokenKind::SelfTypeIdentifier: {
  85. context.AddLeafNode(ParseNodeKind::SelfTypeIdentifier, context.Consume());
  86. context.PushState(state);
  87. break;
  88. }
  89. default: {
  90. // Add a node to keep the parse tree balanced.
  91. context.AddLeafNode(ParseNodeKind::InvalidParse, *context.position(),
  92. /*has_error=*/true);
  93. CARBON_DIAGNOSTIC(ExpectedExpression, Error, "Expected expression.");
  94. context.emitter().Emit(*context.position(), ExpectedExpression);
  95. context.ReturnErrorOnState();
  96. break;
  97. }
  98. }
  99. }
  100. auto ParserHandleExpressionInPostfixLoop(ParserContext& context) -> void {
  101. // This is a cyclic state that repeats, so this state is typically pushed back
  102. // on.
  103. auto state = context.PopState();
  104. state.token = *context.position();
  105. switch (context.PositionKind()) {
  106. case TokenKind::Period: {
  107. context.PushState(state);
  108. state.state = ParserState::DesignatorAsExpression;
  109. context.PushState(state);
  110. break;
  111. }
  112. case TokenKind::OpenParen: {
  113. context.PushState(state);
  114. state.state = ParserState::CallExpression;
  115. context.PushState(state);
  116. break;
  117. }
  118. default: {
  119. if (state.has_error) {
  120. context.ReturnErrorOnState();
  121. }
  122. break;
  123. }
  124. }
  125. }
  126. auto ParserHandleExpressionLoop(ParserContext& context) -> void {
  127. auto state = context.PopState();
  128. auto trailing_operator = PrecedenceGroup::ForTrailing(
  129. context.PositionKind(), context.IsTrailingOperatorInfix());
  130. if (!trailing_operator) {
  131. if (state.has_error) {
  132. context.ReturnErrorOnState();
  133. }
  134. return;
  135. }
  136. auto [operator_precedence, is_binary] = *trailing_operator;
  137. // TODO: If this operator is ambiguous with either the ambient precedence
  138. // or the LHS precedence, and there's a variant with a different fixity
  139. // that would work, use that one instead for error recovery.
  140. if (PrecedenceGroup::GetPriority(state.ambient_precedence,
  141. operator_precedence) !=
  142. OperatorPriority::RightFirst) {
  143. // The precedence rules don't permit this operator in this context. Try
  144. // again in the enclosing expression context.
  145. if (state.has_error) {
  146. context.ReturnErrorOnState();
  147. }
  148. return;
  149. }
  150. if (PrecedenceGroup::GetPriority(state.lhs_precedence, operator_precedence) !=
  151. OperatorPriority::LeftFirst) {
  152. // Either the LHS operator and this operator are ambiguous, or the
  153. // LHS operator is a unary operator that can't be nested within
  154. // this operator. Either way, parentheses are required.
  155. context.emitter().Emit(*context.position(), OperatorRequiresParentheses);
  156. state.has_error = true;
  157. } else {
  158. context.DiagnoseOperatorFixity(
  159. is_binary ? ParserContext::OperatorFixity::Infix
  160. : ParserContext::OperatorFixity::Postfix);
  161. }
  162. state.token = context.Consume();
  163. state.lhs_precedence = operator_precedence;
  164. if (is_binary) {
  165. state.state = ParserState::ExpressionLoopForBinary;
  166. context.PushState(state);
  167. context.PushStateForExpression(operator_precedence);
  168. } else {
  169. context.AddNode(ParseNodeKind::PostfixOperator, state.token,
  170. state.subtree_start, state.has_error);
  171. state.has_error = false;
  172. context.PushState(state);
  173. }
  174. }
  175. auto ParserHandleExpressionLoopForBinary(ParserContext& context) -> void {
  176. auto state = context.PopState();
  177. context.AddNode(ParseNodeKind::InfixOperator, state.token,
  178. state.subtree_start, state.has_error);
  179. state.state = ParserState::ExpressionLoop;
  180. state.has_error = false;
  181. context.PushState(state);
  182. }
  183. auto ParserHandleExpressionLoopForPrefix(ParserContext& context) -> void {
  184. auto state = context.PopState();
  185. context.AddNode(ParseNodeKind::PrefixOperator, state.token,
  186. state.subtree_start, state.has_error);
  187. state.state = ParserState::ExpressionLoop;
  188. state.has_error = false;
  189. context.PushState(state);
  190. }
  191. auto ParserHandleIfExpressionFinishCondition(ParserContext& context) -> void {
  192. auto state = context.PopState();
  193. context.AddNode(ParseNodeKind::IfExpressionIf, state.token,
  194. state.subtree_start, state.has_error);
  195. if (context.PositionIs(TokenKind::Then)) {
  196. context.PushState(ParserState::IfExpressionFinishThen);
  197. context.ConsumeChecked(TokenKind::Then);
  198. context.PushStateForExpression(*PrecedenceGroup::ForLeading(TokenKind::If));
  199. } else {
  200. // TODO: Include the location of the `if` token.
  201. CARBON_DIAGNOSTIC(ExpectedThenAfterIf, Error,
  202. "Expected `then` after `if` condition.");
  203. if (!state.has_error) {
  204. context.emitter().Emit(*context.position(), ExpectedThenAfterIf);
  205. }
  206. // Add placeholders for `IfExpressionThen` and final `Expression`.
  207. context.AddLeafNode(ParseNodeKind::InvalidParse, *context.position(),
  208. /*has_error=*/true);
  209. context.AddLeafNode(ParseNodeKind::InvalidParse, *context.position(),
  210. /*has_error=*/true);
  211. context.ReturnErrorOnState();
  212. }
  213. }
  214. auto ParserHandleIfExpressionFinishThen(ParserContext& context) -> void {
  215. auto state = context.PopState();
  216. context.AddNode(ParseNodeKind::IfExpressionThen, state.token,
  217. state.subtree_start, state.has_error);
  218. if (context.PositionIs(TokenKind::Else)) {
  219. context.PushState(ParserState::IfExpressionFinishElse);
  220. context.ConsumeChecked(TokenKind::Else);
  221. context.PushStateForExpression(*PrecedenceGroup::ForLeading(TokenKind::If));
  222. } else {
  223. // TODO: Include the location of the `if` token.
  224. CARBON_DIAGNOSTIC(ExpectedElseAfterIf, Error,
  225. "Expected `else` after `if ... then ...`.");
  226. if (!state.has_error) {
  227. context.emitter().Emit(*context.position(), ExpectedElseAfterIf);
  228. }
  229. // Add placeholder for the final `Expression`.
  230. context.AddLeafNode(ParseNodeKind::InvalidParse, *context.position(),
  231. /*has_error=*/true);
  232. context.ReturnErrorOnState();
  233. }
  234. }
  235. auto ParserHandleIfExpressionFinishElse(ParserContext& context) -> void {
  236. auto else_state = context.PopState();
  237. // Propagate the location of `else`.
  238. auto if_state = context.PopState();
  239. if_state.token = else_state.token;
  240. if_state.has_error |= else_state.has_error;
  241. context.PushState(if_state);
  242. }
  243. auto ParserHandleIfExpressionFinish(ParserContext& context) -> void {
  244. auto state = context.PopState();
  245. context.AddNode(ParseNodeKind::IfExpressionElse, state.token,
  246. state.subtree_start, state.has_error);
  247. }
  248. auto ParserHandleExpressionStatementFinish(ParserContext& context) -> void {
  249. auto state = context.PopState();
  250. if (auto semi = context.ConsumeIf(TokenKind::Semi)) {
  251. context.AddNode(ParseNodeKind::ExpressionStatement, *semi,
  252. state.subtree_start, state.has_error);
  253. return;
  254. }
  255. if (!state.has_error) {
  256. CARBON_DIAGNOSTIC(ExpectedSemiAfterExpression, Error,
  257. "Expected `;` after expression.");
  258. context.emitter().Emit(*context.position(), ExpectedSemiAfterExpression);
  259. }
  260. if (auto semi_token = context.SkipPastLikelyEnd(state.token)) {
  261. context.AddNode(ParseNodeKind::ExpressionStatement, *semi_token,
  262. state.subtree_start,
  263. /*has_error=*/true);
  264. return;
  265. }
  266. // Found junk not even followed by a `;`, no node to add.
  267. context.ReturnErrorOnState();
  268. }
  269. } // namespace Carbon