handle_expr.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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/lex/token_kind.h"
  5. #include "toolchain/parse/context.h"
  6. namespace Carbon::Parse {
  7. static auto DiagnoseStatementOperatorAsSubExpr(Context& context) -> void {
  8. CARBON_DIAGNOSTIC(StatementOperatorAsSubExpr, Error,
  9. "Operator `{0}` can only be used as a complete statement.",
  10. Lex::TokenKind);
  11. context.emitter().Emit(*context.position(), StatementOperatorAsSubExpr,
  12. context.PositionKind());
  13. }
  14. auto HandleExpr(Context& context) -> void {
  15. auto state = context.PopState();
  16. // Check for a prefix operator.
  17. if (auto operator_precedence =
  18. PrecedenceGroup::ForLeading(context.PositionKind())) {
  19. if (PrecedenceGroup::GetPriority(state.ambient_precedence,
  20. *operator_precedence) !=
  21. OperatorPriority::RightFirst) {
  22. // The precedence rules don't permit this prefix operator in this
  23. // context. Diagnose this, but carry on and parse it anyway.
  24. if (PrecedenceGroup::GetPriority(PrecedenceGroup::ForTopLevelExpr(),
  25. *operator_precedence) ==
  26. OperatorPriority::RightFirst) {
  27. CARBON_DIAGNOSTIC(
  28. UnaryOperatorRequiresParentheses, Error,
  29. "Parentheses are required around this unary `{0}` operator.",
  30. Lex::TokenKind);
  31. context.emitter().Emit(*context.position(),
  32. UnaryOperatorRequiresParentheses,
  33. context.PositionKind());
  34. } else {
  35. // This operator wouldn't be allowed even if parenthesized.
  36. DiagnoseStatementOperatorAsSubExpr(context);
  37. }
  38. } else {
  39. // Check that this operator follows the proper whitespace rules.
  40. context.DiagnoseOperatorFixity(Context::OperatorFixity::Prefix);
  41. }
  42. if (context.PositionIs(Lex::TokenKind::If)) {
  43. context.PushState(State::IfExprFinish);
  44. context.PushState(State::IfExprFinishCondition);
  45. } else {
  46. context.PushStateForExprLoop(State::ExprLoopForPrefixOperator,
  47. state.ambient_precedence,
  48. *operator_precedence);
  49. }
  50. context.ConsumeAndDiscard();
  51. context.PushStateForExpr(*operator_precedence);
  52. } else {
  53. context.PushStateForExprLoop(State::ExprLoop, state.ambient_precedence,
  54. PrecedenceGroup::ForPostfixExpr());
  55. context.PushState(State::ExprInPostfix);
  56. }
  57. }
  58. auto HandleExprInPostfix(Context& context) -> void {
  59. auto state = context.PopState();
  60. // Continue to the loop state.
  61. state.state = State::ExprInPostfixLoop;
  62. // Parses a primary expression, which is either a terminal portion of an
  63. // expression tree, such as an identifier or literal, or a parenthesized
  64. // expression.
  65. switch (context.PositionKind()) {
  66. case Lex::TokenKind::Identifier: {
  67. context.AddLeafNode(NodeKind::IdentifierNameExpr, context.Consume());
  68. context.PushState(state);
  69. break;
  70. }
  71. case Lex::TokenKind::False: {
  72. context.AddLeafNode(NodeKind::BoolLiteralFalse, context.Consume());
  73. context.PushState(state);
  74. break;
  75. }
  76. case Lex::TokenKind::True: {
  77. context.AddLeafNode(NodeKind::BoolLiteralTrue, context.Consume());
  78. context.PushState(state);
  79. break;
  80. }
  81. case Lex::TokenKind::IntLiteral: {
  82. context.AddLeafNode(NodeKind::IntLiteral, context.Consume());
  83. context.PushState(state);
  84. break;
  85. }
  86. case Lex::TokenKind::RealLiteral: {
  87. context.AddLeafNode(NodeKind::RealLiteral, context.Consume());
  88. context.PushState(state);
  89. break;
  90. }
  91. case Lex::TokenKind::StringLiteral: {
  92. context.AddLeafNode(NodeKind::StringLiteral, context.Consume());
  93. context.PushState(state);
  94. break;
  95. }
  96. case Lex::TokenKind::Bool: {
  97. context.AddLeafNode(NodeKind::BoolTypeLiteral, context.Consume());
  98. context.PushState(state);
  99. break;
  100. }
  101. case Lex::TokenKind::IntTypeLiteral: {
  102. context.AddLeafNode(NodeKind::IntTypeLiteral, context.Consume());
  103. context.PushState(state);
  104. break;
  105. }
  106. case Lex::TokenKind::UnsignedIntTypeLiteral: {
  107. context.AddLeafNode(NodeKind::UnsignedIntTypeLiteral, context.Consume());
  108. context.PushState(state);
  109. break;
  110. }
  111. case Lex::TokenKind::FloatTypeLiteral: {
  112. context.AddLeafNode(NodeKind::FloatTypeLiteral, context.Consume());
  113. context.PushState(state);
  114. break;
  115. }
  116. case Lex::TokenKind::StringTypeLiteral: {
  117. context.AddLeafNode(NodeKind::StringTypeLiteral, context.Consume());
  118. context.PushState(state);
  119. break;
  120. }
  121. case Lex::TokenKind::Type: {
  122. context.AddLeafNode(NodeKind::TypeTypeLiteral, context.Consume());
  123. context.PushState(state);
  124. break;
  125. }
  126. case Lex::TokenKind::OpenCurlyBrace: {
  127. context.PushState(state);
  128. context.PushState(State::BraceExpr);
  129. break;
  130. }
  131. case Lex::TokenKind::OpenParen: {
  132. context.PushState(state);
  133. context.PushState(State::ParenExpr);
  134. break;
  135. }
  136. case Lex::TokenKind::OpenSquareBracket: {
  137. context.PushState(state);
  138. context.PushState(State::ArrayExpr);
  139. break;
  140. }
  141. case Lex::TokenKind::Package: {
  142. context.AddLeafNode(NodeKind::PackageExpr, context.Consume());
  143. context.PushState(state);
  144. break;
  145. }
  146. case Lex::TokenKind::SelfValueIdentifier: {
  147. context.AddLeafNode(NodeKind::SelfValueNameExpr, context.Consume());
  148. context.PushState(state);
  149. break;
  150. }
  151. case Lex::TokenKind::SelfTypeIdentifier: {
  152. context.AddLeafNode(NodeKind::SelfTypeNameExpr, context.Consume());
  153. context.PushState(state);
  154. break;
  155. }
  156. default: {
  157. // Add a node to keep the parse tree balanced.
  158. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  159. /*has_error=*/true);
  160. CARBON_DIAGNOSTIC(ExpectedExpr, Error, "Expected expression.");
  161. context.emitter().Emit(*context.position(), ExpectedExpr);
  162. context.ReturnErrorOnState();
  163. break;
  164. }
  165. }
  166. }
  167. auto HandleExprInPostfixLoop(Context& context) -> void {
  168. // This is a cyclic state that repeats, so this state is typically pushed back
  169. // on.
  170. auto state = context.PopState();
  171. state.token = *context.position();
  172. switch (context.PositionKind()) {
  173. case Lex::TokenKind::Period: {
  174. context.PushState(state);
  175. context.PushState(state, State::PeriodAsExpr);
  176. break;
  177. }
  178. case Lex::TokenKind::MinusGreater: {
  179. context.PushState(state);
  180. context.PushState(state, State::ArrowExpr);
  181. break;
  182. }
  183. case Lex::TokenKind::OpenParen: {
  184. context.PushState(state);
  185. context.PushState(state, State::CallExpr);
  186. break;
  187. }
  188. case Lex::TokenKind::OpenSquareBracket: {
  189. context.PushState(state);
  190. context.PushState(state, State::IndexExpr);
  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. switch (operator_kind) {
  252. // For `and` and `or`, wrap the first operand in a virtual parse tree
  253. // node so that checking can insert control flow here.
  254. case Lex::TokenKind::And:
  255. context.AddNode(NodeKind::ShortCircuitOperandAnd, state.token,
  256. state.subtree_start, state.has_error);
  257. state.state = State::ExprLoopForShortCircuitOperatorAsAnd;
  258. break;
  259. case Lex::TokenKind::Or:
  260. context.AddNode(NodeKind::ShortCircuitOperandOr, state.token,
  261. state.subtree_start, state.has_error);
  262. state.state = State::ExprLoopForShortCircuitOperatorAsOr;
  263. break;
  264. default:
  265. state.state = State::ExprLoopForInfixOperator;
  266. break;
  267. }
  268. context.PushState(state);
  269. context.PushStateForExpr(operator_precedence);
  270. } else {
  271. NodeKind node_kind;
  272. switch (operator_kind) {
  273. #define CARBON_PARSE_NODE_KIND(...)
  274. #define CARBON_PARSE_NODE_KIND_POSTFIX_OPERATOR(Name, ...) \
  275. case Lex::TokenKind::Name: \
  276. node_kind = NodeKind::PostfixOperator##Name; \
  277. break;
  278. #include "toolchain/parse/node_kind.def"
  279. default:
  280. CARBON_FATAL() << "Unexpected token kind for postfix operator: "
  281. << operator_kind;
  282. }
  283. context.AddNode(node_kind, state.token, state.subtree_start,
  284. state.has_error);
  285. state.has_error = false;
  286. context.PushState(state);
  287. }
  288. }
  289. // Adds the operator node and returns the the main expression loop.
  290. static auto HandleExprLoopForOperator(Context& context,
  291. Context::StateStackEntry state,
  292. NodeKind node_kind) -> void {
  293. context.AddNode(node_kind, state.token, state.subtree_start, state.has_error);
  294. state.has_error = false;
  295. context.PushState(state, State::ExprLoop);
  296. }
  297. auto HandleExprLoopForInfixOperator(Context& context) -> void {
  298. auto state = context.PopState();
  299. switch (auto token_kind = context.tokens().GetKind(state.token)) {
  300. #define CARBON_PARSE_NODE_KIND(...)
  301. #define CARBON_PARSE_NODE_KIND_INFIX_OPERATOR(Name, ...) \
  302. case Lex::TokenKind::Name: \
  303. HandleExprLoopForOperator(context, state, NodeKind::InfixOperator##Name); \
  304. break;
  305. #include "toolchain/parse/node_kind.def"
  306. default:
  307. CARBON_FATAL() << "Unexpected token kind for infix operator: "
  308. << token_kind;
  309. }
  310. }
  311. auto HandleExprLoopForPrefixOperator(Context& context) -> void {
  312. auto state = context.PopState();
  313. switch (auto token_kind = context.tokens().GetKind(state.token)) {
  314. #define CARBON_PARSE_NODE_KIND(...)
  315. #define CARBON_PARSE_NODE_KIND_PREFIX_OPERATOR(Name, ...) \
  316. case Lex::TokenKind::Name: \
  317. HandleExprLoopForOperator(context, state, NodeKind::PrefixOperator##Name); \
  318. break;
  319. #include "toolchain/parse/node_kind.def"
  320. default:
  321. CARBON_FATAL() << "Unexpected token kind for prefix operator: "
  322. << token_kind;
  323. }
  324. }
  325. auto HandleExprLoopForShortCircuitOperatorAsAnd(Context& context) -> void {
  326. auto state = context.PopState();
  327. HandleExprLoopForOperator(context, state, NodeKind::ShortCircuitOperatorAnd);
  328. }
  329. auto HandleExprLoopForShortCircuitOperatorAsOr(Context& context) -> void {
  330. auto state = context.PopState();
  331. HandleExprLoopForOperator(context, state, NodeKind::ShortCircuitOperatorOr);
  332. }
  333. auto HandleIfExprFinishCondition(Context& context) -> void {
  334. auto state = context.PopState();
  335. context.AddNode(NodeKind::IfExprIf, state.token, state.subtree_start,
  336. state.has_error);
  337. if (context.PositionIs(Lex::TokenKind::Then)) {
  338. context.PushState(State::IfExprFinishThen);
  339. context.ConsumeChecked(Lex::TokenKind::Then);
  340. context.PushStateForExpr(*PrecedenceGroup::ForLeading(Lex::TokenKind::If));
  341. } else {
  342. // TODO: Include the location of the `if` token.
  343. CARBON_DIAGNOSTIC(ExpectedThenAfterIf, Error,
  344. "Expected `then` after `if` condition.");
  345. if (!state.has_error) {
  346. context.emitter().Emit(*context.position(), ExpectedThenAfterIf);
  347. }
  348. // Add placeholders for `IfExprThen` and final `Expr`.
  349. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  350. /*has_error=*/true);
  351. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  352. /*has_error=*/true);
  353. context.ReturnErrorOnState();
  354. }
  355. }
  356. auto HandleIfExprFinishThen(Context& context) -> void {
  357. auto state = context.PopState();
  358. context.AddNode(NodeKind::IfExprThen, state.token, state.subtree_start,
  359. state.has_error);
  360. if (context.PositionIs(Lex::TokenKind::Else)) {
  361. context.PushState(State::IfExprFinishElse);
  362. context.ConsumeChecked(Lex::TokenKind::Else);
  363. context.PushStateForExpr(*PrecedenceGroup::ForLeading(Lex::TokenKind::If));
  364. } else {
  365. // TODO: Include the location of the `if` token.
  366. CARBON_DIAGNOSTIC(ExpectedElseAfterIf, Error,
  367. "Expected `else` after `if ... then ...`.");
  368. if (!state.has_error) {
  369. context.emitter().Emit(*context.position(), ExpectedElseAfterIf);
  370. }
  371. // Add placeholder for the final `Expr`.
  372. context.AddLeafNode(NodeKind::InvalidParse, *context.position(),
  373. /*has_error=*/true);
  374. context.ReturnErrorOnState();
  375. }
  376. }
  377. auto HandleIfExprFinishElse(Context& context) -> void {
  378. auto else_state = context.PopState();
  379. // Propagate the location of `else`.
  380. auto if_state = context.PopState();
  381. if_state.token = else_state.token;
  382. if_state.has_error |= else_state.has_error;
  383. context.PushState(if_state);
  384. }
  385. auto HandleIfExprFinish(Context& context) -> void {
  386. auto state = context.PopState();
  387. context.AddNode(NodeKind::IfExprElse, state.token, state.subtree_start,
  388. state.has_error);
  389. }
  390. auto HandleExprStatementFinish(Context& context) -> void {
  391. auto state = context.PopState();
  392. if (auto semi = context.ConsumeIf(Lex::TokenKind::Semi)) {
  393. context.AddNode(NodeKind::ExprStatement, *semi, state.subtree_start,
  394. state.has_error);
  395. return;
  396. }
  397. if (!state.has_error) {
  398. CARBON_DIAGNOSTIC(ExpectedExprSemi, Error,
  399. "Expected `;` after expression statement.");
  400. context.emitter().Emit(*context.position(), ExpectedExprSemi);
  401. }
  402. context.AddNode(NodeKind::ExprStatement,
  403. context.SkipPastLikelyEnd(state.token), state.subtree_start,
  404. /*has_error=*/true);
  405. }
  406. } // namespace Carbon::Parse