parser_handle_expression.cpp 11 KB

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