handle_expr.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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/parse/context.h"
  5. namespace Carbon::Parse {
  6. static auto DiagnoseStatementOperatorAsSubExpr(Context& context) -> void {
  7. CARBON_DIAGNOSTIC(StatementOperatorAsSubExpr, Error,
  8. "Operator `{0}` can only be used as a complete statement.",
  9. Lex::TokenKind);
  10. context.emitter().Emit(*context.position(), StatementOperatorAsSubExpr,
  11. context.PositionKind());
  12. }
  13. auto HandleExpr(Context& context) -> void {
  14. auto state = context.PopState();
  15. // Check for a prefix operator.
  16. if (auto operator_precedence =
  17. PrecedenceGroup::ForLeading(context.PositionKind())) {
  18. if (PrecedenceGroup::GetPriority(state.ambient_precedence,
  19. *operator_precedence) !=
  20. OperatorPriority::RightFirst) {
  21. // The precedence rules don't permit this prefix operator in this
  22. // context. Diagnose this, but carry on and parse it anyway.
  23. if (PrecedenceGroup::GetPriority(PrecedenceGroup::ForTopLevelExpr(),
  24. *operator_precedence) ==
  25. OperatorPriority::RightFirst) {
  26. CARBON_DIAGNOSTIC(
  27. UnaryOperatorRequiresParentheses, Error,
  28. "Parentheses are required around this unary `{0}` operator.",
  29. Lex::TokenKind);
  30. context.emitter().Emit(*context.position(),
  31. UnaryOperatorRequiresParentheses,
  32. context.PositionKind());
  33. } else {
  34. // This operator wouldn't be allowed even if parenthesized.
  35. DiagnoseStatementOperatorAsSubExpr(context);
  36. }
  37. } else {
  38. // Check that this operator follows the proper whitespace rules.
  39. context.DiagnoseOperatorFixity(Context::OperatorFixity::Prefix);
  40. }
  41. if (context.PositionIs(Lex::TokenKind::If)) {
  42. context.PushState(State::IfExprFinish);
  43. context.PushState(State::IfExprFinishCondition);
  44. } else {
  45. context.PushStateForExprLoop(State::ExprLoopForPrefix,
  46. state.ambient_precedence,
  47. *operator_precedence);
  48. }
  49. context.ConsumeAndDiscard();
  50. context.PushStateForExpr(*operator_precedence);
  51. } else {
  52. context.PushStateForExprLoop(State::ExprLoop, state.ambient_precedence,
  53. PrecedenceGroup::ForPostfixExpr());
  54. context.PushState(State::ExprInPostfix);
  55. }
  56. }
  57. auto HandleExprInPostfix(Context& context) -> void {
  58. auto state = context.PopState();
  59. // Continue to the loop state.
  60. state.state = State::ExprInPostfixLoop;
  61. // Parses a primary expression, which is either a terminal portion of an
  62. // expression tree, such as an identifier or literal, or a parenthesized
  63. // expression.
  64. switch (context.PositionKind()) {
  65. case Lex::TokenKind::Identifier: {
  66. context.AddLeafNode(NodeKind::NameExpr, context.Consume());
  67. context.PushState(state);
  68. break;
  69. }
  70. case Lex::TokenKind::False: {
  71. context.AddLeafNode(NodeKind::BoolLiteralFalse, context.Consume());
  72. context.PushState(state);
  73. break;
  74. }
  75. case Lex::TokenKind::True: {
  76. context.AddLeafNode(NodeKind::BoolLiteralTrue, context.Consume());
  77. context.PushState(state);
  78. break;
  79. }
  80. case Lex::TokenKind::IntegerLiteral: {
  81. context.AddLeafNode(NodeKind::IntegerLiteral, context.Consume());
  82. context.PushState(state);
  83. break;
  84. }
  85. case Lex::TokenKind::RealLiteral: {
  86. context.AddLeafNode(NodeKind::FloatingPointLiteral, context.Consume());
  87. context.PushState(state);
  88. break;
  89. }
  90. case Lex::TokenKind::StringLiteral: {
  91. context.AddLeafNode(NodeKind::StringLiteral, context.Consume());
  92. context.PushState(state);
  93. break;
  94. }
  95. case Lex::TokenKind::Bool: {
  96. context.AddLeafNode(NodeKind::BoolTypeLiteral, context.Consume());
  97. context.PushState(state);
  98. break;
  99. }
  100. case Lex::TokenKind::IntegerTypeLiteral: {
  101. context.AddLeafNode(NodeKind::IntegerTypeLiteral, context.Consume());
  102. context.PushState(state);
  103. break;
  104. }
  105. case Lex::TokenKind::UnsignedIntegerTypeLiteral: {
  106. context.AddLeafNode(NodeKind::UnsignedIntegerTypeLiteral,
  107. context.Consume());
  108. context.PushState(state);
  109. break;
  110. }
  111. case Lex::TokenKind::FloatingPointTypeLiteral: {
  112. context.AddLeafNode(NodeKind::FloatingPointTypeLiteral,
  113. context.Consume());
  114. context.PushState(state);
  115. break;
  116. }
  117. case Lex::TokenKind::StringTypeLiteral: {
  118. context.AddLeafNode(NodeKind::StringTypeLiteral, context.Consume());
  119. context.PushState(state);
  120. break;
  121. }
  122. case Lex::TokenKind::Type: {
  123. context.AddLeafNode(NodeKind::TypeTypeLiteral, context.Consume());
  124. context.PushState(state);
  125. break;
  126. }
  127. case Lex::TokenKind::OpenCurlyBrace: {
  128. context.PushState(state);
  129. context.PushState(State::BraceExpr);
  130. break;
  131. }
  132. case Lex::TokenKind::OpenParen: {
  133. context.PushState(state);
  134. context.PushState(State::ParenExpr);
  135. break;
  136. }
  137. case Lex::TokenKind::OpenSquareBracket: {
  138. context.PushState(state);
  139. context.PushState(State::ArrayExpr);
  140. break;
  141. }
  142. case Lex::TokenKind::SelfValueIdentifier: {
  143. context.AddLeafNode(NodeKind::SelfValueNameExpr, context.Consume());
  144. context.PushState(state);
  145. break;
  146. }
  147. case Lex::TokenKind::SelfTypeIdentifier: {
  148. context.AddLeafNode(NodeKind::SelfTypeNameExpr, context.Consume());
  149. context.PushState(state);
  150. break;
  151. }
  152. default: {
  153. // Add a node to keep the parse tree balanced.
  154. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  155. /*has_error=*/true);
  156. CARBON_DIAGNOSTIC(ExpectedExpr, Error, "Expected expression.");
  157. context.emitter().Emit(*context.position(), ExpectedExpr);
  158. context.ReturnErrorOnState();
  159. break;
  160. }
  161. }
  162. }
  163. auto HandleExprInPostfixLoop(Context& context) -> void {
  164. // This is a cyclic state that repeats, so this state is typically pushed back
  165. // on.
  166. auto state = context.PopState();
  167. state.token = *context.position();
  168. switch (context.PositionKind()) {
  169. case Lex::TokenKind::Period: {
  170. context.PushState(state);
  171. state.state = State::PeriodAsExpr;
  172. context.PushState(state);
  173. break;
  174. }
  175. case Lex::TokenKind::MinusGreater: {
  176. context.PushState(state);
  177. state.state = State::ArrowExpr;
  178. context.PushState(state);
  179. break;
  180. }
  181. case Lex::TokenKind::OpenParen: {
  182. context.PushState(state);
  183. state.state = State::CallExpr;
  184. context.PushState(state);
  185. break;
  186. }
  187. case Lex::TokenKind::OpenSquareBracket: {
  188. context.PushState(state);
  189. state.state = State::IndexExpr;
  190. context.PushState(state);
  191. break;
  192. }
  193. default: {
  194. if (state.has_error) {
  195. context.ReturnErrorOnState();
  196. }
  197. break;
  198. }
  199. }
  200. }
  201. auto HandleExprLoop(Context& context) -> void {
  202. auto state = context.PopState();
  203. auto operator_kind = context.PositionKind();
  204. auto trailing_operator = PrecedenceGroup::ForTrailing(
  205. operator_kind, context.IsTrailingOperatorInfix());
  206. if (!trailing_operator) {
  207. if (state.has_error) {
  208. context.ReturnErrorOnState();
  209. }
  210. return;
  211. }
  212. auto [operator_precedence, is_binary] = *trailing_operator;
  213. // TODO: If this operator is ambiguous with either the ambient precedence
  214. // or the LHS precedence, and there's a variant with a different fixity
  215. // that would work, use that one instead for error recovery.
  216. if (PrecedenceGroup::GetPriority(state.ambient_precedence,
  217. operator_precedence) !=
  218. OperatorPriority::RightFirst) {
  219. // The precedence rules don't permit this operator in this context. Try
  220. // again in the enclosing expression context.
  221. if (state.has_error) {
  222. context.ReturnErrorOnState();
  223. }
  224. return;
  225. }
  226. if (PrecedenceGroup::GetPriority(state.lhs_precedence, operator_precedence) !=
  227. OperatorPriority::LeftFirst) {
  228. // Either the LHS operator and this operator are ambiguous, or the
  229. // LHS operator is a unary operator that can't be nested within
  230. // this operator. Either way, parentheses are required.
  231. if (PrecedenceGroup::GetPriority(PrecedenceGroup::ForTopLevelExpr(),
  232. operator_precedence) ==
  233. OperatorPriority::RightFirst) {
  234. CARBON_DIAGNOSTIC(
  235. OperatorRequiresParentheses, Error,
  236. "Parentheses are required to disambiguate operator precedence.");
  237. context.emitter().Emit(*context.position(), OperatorRequiresParentheses);
  238. } else {
  239. // This operator wouldn't be allowed even if parenthesized.
  240. DiagnoseStatementOperatorAsSubExpr(context);
  241. }
  242. state.has_error = true;
  243. } else {
  244. context.DiagnoseOperatorFixity(is_binary
  245. ? Context::OperatorFixity::Infix
  246. : Context::OperatorFixity::Postfix);
  247. }
  248. state.token = context.Consume();
  249. state.lhs_precedence = operator_precedence;
  250. if (is_binary) {
  251. if (operator_kind == Lex::TokenKind::And ||
  252. operator_kind == Lex::TokenKind::Or) {
  253. // For `and` and `or`, wrap the first operand in a virtual parse tree
  254. // node so that semantics can insert control flow here.
  255. context.AddNode(NodeKind::ShortCircuitOperand, state.token,
  256. state.subtree_start, state.has_error);
  257. }
  258. state.state = State::ExprLoopForBinary;
  259. context.PushState(state);
  260. context.PushStateForExpr(operator_precedence);
  261. } else {
  262. context.AddNode(NodeKind::PostfixOperator, state.token, state.subtree_start,
  263. state.has_error);
  264. state.has_error = false;
  265. context.PushState(state);
  266. }
  267. }
  268. auto HandleExprLoopForBinary(Context& context) -> void {
  269. auto state = context.PopState();
  270. context.AddNode(NodeKind::InfixOperator, state.token, state.subtree_start,
  271. state.has_error);
  272. state.state = State::ExprLoop;
  273. state.has_error = false;
  274. context.PushState(state);
  275. }
  276. auto HandleExprLoopForPrefix(Context& context) -> void {
  277. auto state = context.PopState();
  278. context.AddNode(NodeKind::PrefixOperator, state.token, state.subtree_start,
  279. state.has_error);
  280. state.state = State::ExprLoop;
  281. state.has_error = false;
  282. context.PushState(state);
  283. }
  284. auto HandleIfExprFinishCondition(Context& context) -> void {
  285. auto state = context.PopState();
  286. context.AddNode(NodeKind::IfExprIf, state.token, state.subtree_start,
  287. state.has_error);
  288. if (context.PositionIs(Lex::TokenKind::Then)) {
  289. context.PushState(State::IfExprFinishThen);
  290. context.ConsumeChecked(Lex::TokenKind::Then);
  291. context.PushStateForExpr(*PrecedenceGroup::ForLeading(Lex::TokenKind::If));
  292. } else {
  293. // TODO: Include the location of the `if` token.
  294. CARBON_DIAGNOSTIC(ExpectedThenAfterIf, Error,
  295. "Expected `then` after `if` condition.");
  296. if (!state.has_error) {
  297. context.emitter().Emit(*context.position(), ExpectedThenAfterIf);
  298. }
  299. // Add placeholders for `IfExprThen` and final `Expr`.
  300. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  301. /*has_error=*/true);
  302. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  303. /*has_error=*/true);
  304. context.ReturnErrorOnState();
  305. }
  306. }
  307. auto HandleIfExprFinishThen(Context& context) -> void {
  308. auto state = context.PopState();
  309. context.AddNode(NodeKind::IfExprThen, state.token, state.subtree_start,
  310. state.has_error);
  311. if (context.PositionIs(Lex::TokenKind::Else)) {
  312. context.PushState(State::IfExprFinishElse);
  313. context.ConsumeChecked(Lex::TokenKind::Else);
  314. context.PushStateForExpr(*PrecedenceGroup::ForLeading(Lex::TokenKind::If));
  315. } else {
  316. // TODO: Include the location of the `if` token.
  317. CARBON_DIAGNOSTIC(ExpectedElseAfterIf, Error,
  318. "Expected `else` after `if ... then ...`.");
  319. if (!state.has_error) {
  320. context.emitter().Emit(*context.position(), ExpectedElseAfterIf);
  321. }
  322. // Add placeholder for the final `Expr`.
  323. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  324. /*has_error=*/true);
  325. context.ReturnErrorOnState();
  326. }
  327. }
  328. auto HandleIfExprFinishElse(Context& context) -> void {
  329. auto else_state = context.PopState();
  330. // Propagate the location of `else`.
  331. auto if_state = context.PopState();
  332. if_state.token = else_state.token;
  333. if_state.has_error |= else_state.has_error;
  334. context.PushState(if_state);
  335. }
  336. auto HandleIfExprFinish(Context& context) -> void {
  337. auto state = context.PopState();
  338. context.AddNode(NodeKind::IfExprElse, state.token, state.subtree_start,
  339. state.has_error);
  340. }
  341. auto HandleExprStatementFinish(Context& context) -> void {
  342. auto state = context.PopState();
  343. if (auto semi = context.ConsumeIf(Lex::TokenKind::Semi)) {
  344. context.AddNode(NodeKind::ExprStatement, *semi, state.subtree_start,
  345. state.has_error);
  346. return;
  347. }
  348. if (!state.has_error) {
  349. CARBON_DIAGNOSTIC(ExpectedExprSemi, Error,
  350. "Expected `;` after expression statement.");
  351. context.emitter().Emit(*context.position(), ExpectedExprSemi);
  352. }
  353. if (auto semi_token = context.SkipPastLikelyEnd(state.token)) {
  354. context.AddNode(NodeKind::ExprStatement, *semi_token, state.subtree_start,
  355. /*has_error=*/true);
  356. return;
  357. }
  358. // Found junk not even followed by a `;`, no node to add.
  359. context.ReturnErrorOnState();
  360. }
  361. } // namespace Carbon::Parse