handle_expr.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. #include "toolchain/parse/handle.h"
  7. namespace Carbon::Parse {
  8. static auto DiagnoseStatementOperatorAsSubExpr(Context& context) -> void {
  9. CARBON_DIAGNOSTIC(StatementOperatorAsSubExpr, Error,
  10. "operator `{0}` can only be used as a complete statement",
  11. Lex::TokenKind);
  12. context.emitter().Emit(*context.position(), StatementOperatorAsSubExpr,
  13. context.PositionKind());
  14. }
  15. auto HandleExpr(Context& context) -> void {
  16. auto state = context.PopState();
  17. // Check for a prefix operator.
  18. if (auto operator_precedence =
  19. PrecedenceGroup::ForLeading(context.PositionKind())) {
  20. if (PrecedenceGroup::GetPriority(state.ambient_precedence,
  21. *operator_precedence) !=
  22. OperatorPriority::RightFirst) {
  23. // The precedence rules don't permit this prefix operator in this
  24. // context. Diagnose this, but carry on and parse it anyway.
  25. if (PrecedenceGroup::GetPriority(PrecedenceGroup::ForTopLevelExpr(),
  26. *operator_precedence) ==
  27. OperatorPriority::RightFirst) {
  28. CARBON_DIAGNOSTIC(
  29. UnaryOperatorRequiresParentheses, Error,
  30. "parentheses are required around this unary `{0}` operator",
  31. Lex::TokenKind);
  32. context.emitter().Emit(*context.position(),
  33. UnaryOperatorRequiresParentheses,
  34. context.PositionKind());
  35. } else {
  36. // This operator wouldn't be allowed even if parenthesized.
  37. DiagnoseStatementOperatorAsSubExpr(context);
  38. }
  39. } else {
  40. // Check that this operator follows the proper whitespace rules.
  41. context.DiagnoseOperatorFixity(Context::OperatorFixity::Prefix);
  42. }
  43. if (context.PositionIs(Lex::TokenKind::If)) {
  44. context.PushState(State::IfExprFinish);
  45. context.PushState(State::IfExprFinishCondition);
  46. } else {
  47. context.PushStateForExprLoop(State::ExprLoopForPrefixOperator,
  48. state.ambient_precedence,
  49. *operator_precedence);
  50. }
  51. context.ConsumeAndDiscard();
  52. context.PushStateForExpr(*operator_precedence);
  53. } else {
  54. context.PushStateForExprLoop(State::ExprLoop, state.ambient_precedence,
  55. PrecedenceGroup::ForPostfixExpr());
  56. context.PushState(State::ExprInPostfix);
  57. }
  58. }
  59. auto HandleExprInPostfix(Context& context) -> void {
  60. auto state = context.PopState();
  61. // Continue to the loop state.
  62. state.state = State::ExprInPostfixLoop;
  63. // Parses a primary expression, which is either a terminal portion of an
  64. // expression tree, such as an identifier or literal, or a parenthesized
  65. // expression.
  66. switch (auto token_kind = context.PositionKind()) {
  67. case Lex::TokenKind::Identifier: {
  68. context.AddLeafNode(NodeKind::IdentifierNameExpr, context.Consume());
  69. context.PushState(state);
  70. break;
  71. }
  72. case Lex::TokenKind::False: {
  73. context.AddLeafNode(NodeKind::BoolLiteralFalse, context.Consume());
  74. context.PushState(state);
  75. break;
  76. }
  77. case Lex::TokenKind::True: {
  78. context.AddLeafNode(NodeKind::BoolLiteralTrue, context.Consume());
  79. context.PushState(state);
  80. break;
  81. }
  82. case Lex::TokenKind::IntLiteral: {
  83. context.AddLeafNode(NodeKind::IntLiteral, context.Consume());
  84. context.PushState(state);
  85. break;
  86. }
  87. case Lex::TokenKind::RealLiteral: {
  88. context.AddLeafNode(NodeKind::RealLiteral, context.Consume());
  89. context.PushState(state);
  90. break;
  91. }
  92. case Lex::TokenKind::StringLiteral: {
  93. context.AddLeafNode(NodeKind::StringLiteral, context.Consume());
  94. context.PushState(state);
  95. break;
  96. }
  97. case Lex::TokenKind::Bool: {
  98. context.AddLeafNode(NodeKind::BoolTypeLiteral, context.Consume());
  99. context.PushState(state);
  100. break;
  101. }
  102. case Lex::TokenKind::IntTypeLiteral: {
  103. context.AddLeafNode(NodeKind::IntTypeLiteral, context.Consume());
  104. context.PushState(state);
  105. break;
  106. }
  107. case Lex::TokenKind::UnsignedIntTypeLiteral: {
  108. context.AddLeafNode(NodeKind::UnsignedIntTypeLiteral, context.Consume());
  109. context.PushState(state);
  110. break;
  111. }
  112. case Lex::TokenKind::FloatTypeLiteral: {
  113. context.AddLeafNode(NodeKind::FloatTypeLiteral, 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::Auto: {
  128. context.AddLeafNode(NodeKind::AutoTypeLiteral, context.Consume());
  129. context.PushState(state);
  130. break;
  131. }
  132. case Lex::TokenKind::OpenCurlyBrace: {
  133. context.PushState(state);
  134. context.PushState(State::BraceExpr);
  135. break;
  136. }
  137. case Lex::TokenKind::OpenParen: {
  138. context.PushState(state);
  139. context.PushState(State::ParenExpr);
  140. break;
  141. }
  142. case Lex::TokenKind::OpenSquareBracket: {
  143. context.PushState(state);
  144. context.PushState(State::ArrayExpr);
  145. break;
  146. }
  147. case Lex::TokenKind::Package: {
  148. context.AddLeafNode(NodeKind::PackageExpr, context.Consume());
  149. context.PushState(state);
  150. break;
  151. }
  152. case Lex::TokenKind::SelfValueIdentifier: {
  153. context.AddLeafNode(NodeKind::SelfValueNameExpr, context.Consume());
  154. context.PushState(state);
  155. break;
  156. }
  157. case Lex::TokenKind::SelfTypeIdentifier: {
  158. context.AddLeafNode(NodeKind::SelfTypeNameExpr, context.Consume());
  159. context.PushState(state);
  160. break;
  161. }
  162. case Lex::TokenKind::Period: {
  163. // For periods, we look at the next token to form a designator like
  164. // `.Member` or `.Self`.
  165. auto period = context.Consume();
  166. if (context.ConsumeAndAddLeafNodeIf(Lex::TokenKind::Identifier,
  167. NodeKind::IdentifierName)) {
  168. // OK, `.` identifier.
  169. } else if (context.ConsumeAndAddLeafNodeIf(
  170. Lex::TokenKind::SelfTypeIdentifier,
  171. NodeKind::SelfTypeName)) {
  172. // OK, `.Self`.
  173. } else {
  174. CARBON_DIAGNOSTIC(ExpectedIdentifierOrSelfAfterPeriod, Error,
  175. "expected identifier or `Self` after `.`");
  176. context.emitter().Emit(*context.position(),
  177. ExpectedIdentifierOrSelfAfterPeriod);
  178. // Only consume if it is a number or word.
  179. if (context.PositionKind().is_keyword()) {
  180. context.AddLeafNode(NodeKind::IdentifierName, context.Consume(),
  181. /*has_error=*/true);
  182. } else if (context.PositionIs(Lex::TokenKind::IntLiteral)) {
  183. context.AddInvalidParse(context.Consume());
  184. } else {
  185. context.AddInvalidParse(*context.position());
  186. // Indicate the error to the parent state so that it can avoid
  187. // producing more errors. We only do this on this path where we don't
  188. // consume the token after the period, where we expect further errors
  189. // since we likely haven't recovered.
  190. context.ReturnErrorOnState();
  191. }
  192. state.has_error = true;
  193. }
  194. context.AddNode(NodeKind::DesignatorExpr, period, state.has_error);
  195. context.PushState(state);
  196. break;
  197. }
  198. default: {
  199. // If not already diagnosed in the lexer, diagnose it here.
  200. if (token_kind != Lex::TokenKind::Error) {
  201. CARBON_DIAGNOSTIC(ExpectedExpr, Error, "expected expression");
  202. context.emitter().Emit(*context.position(), ExpectedExpr);
  203. }
  204. // Add a node to keep the parse tree balanced.
  205. context.AddInvalidParse(*context.position());
  206. context.ReturnErrorOnState();
  207. break;
  208. }
  209. }
  210. }
  211. auto HandleExprInPostfixLoop(Context& context) -> void {
  212. // This is a cyclic state that repeats, so this state is typically pushed back
  213. // on.
  214. auto state = context.PopState();
  215. state.token = *context.position();
  216. switch (context.PositionKind()) {
  217. case Lex::TokenKind::Period: {
  218. context.PushState(state);
  219. context.PushState(state, State::PeriodAsExpr);
  220. break;
  221. }
  222. case Lex::TokenKind::MinusGreater: {
  223. context.PushState(state);
  224. context.PushState(state, State::ArrowExpr);
  225. break;
  226. }
  227. case Lex::TokenKind::OpenParen: {
  228. context.PushState(state);
  229. context.PushState(state, State::CallExpr);
  230. break;
  231. }
  232. case Lex::TokenKind::OpenSquareBracket: {
  233. context.PushState(state);
  234. context.PushState(state, State::IndexExpr);
  235. break;
  236. }
  237. default: {
  238. if (state.has_error) {
  239. context.ReturnErrorOnState();
  240. }
  241. break;
  242. }
  243. }
  244. }
  245. auto HandleExprLoop(Context& context) -> void {
  246. auto state = context.PopState();
  247. auto operator_kind = context.PositionKind();
  248. auto trailing_operator = PrecedenceGroup::ForTrailing(
  249. operator_kind, context.IsTrailingOperatorInfix());
  250. if (!trailing_operator) {
  251. if (state.has_error) {
  252. context.ReturnErrorOnState();
  253. }
  254. return;
  255. }
  256. auto [operator_precedence, is_binary] = *trailing_operator;
  257. // TODO: If this operator is ambiguous with either the ambient precedence
  258. // or the LHS precedence, and there's a variant with a different fixity
  259. // that would work, use that one instead for error recovery.
  260. if (PrecedenceGroup::GetPriority(state.ambient_precedence,
  261. operator_precedence) !=
  262. OperatorPriority::RightFirst) {
  263. // The precedence rules don't permit this operator in this context. Try
  264. // again in the enclosing expression context.
  265. if (state.has_error) {
  266. context.ReturnErrorOnState();
  267. }
  268. return;
  269. }
  270. if (PrecedenceGroup::GetPriority(state.lhs_precedence, operator_precedence) !=
  271. OperatorPriority::LeftFirst) {
  272. // Either the LHS operator and this operator are ambiguous, or the
  273. // LHS operator is a unary operator that can't be nested within
  274. // this operator. Either way, parentheses are required.
  275. if (PrecedenceGroup::GetPriority(PrecedenceGroup::ForTopLevelExpr(),
  276. operator_precedence) ==
  277. OperatorPriority::RightFirst) {
  278. CARBON_DIAGNOSTIC(
  279. OperatorRequiresParentheses, Error,
  280. "parentheses are required to disambiguate operator precedence");
  281. context.emitter().Emit(*context.position(), OperatorRequiresParentheses);
  282. } else {
  283. // This operator wouldn't be allowed even if parenthesized.
  284. DiagnoseStatementOperatorAsSubExpr(context);
  285. }
  286. state.has_error = true;
  287. } else {
  288. context.DiagnoseOperatorFixity(is_binary
  289. ? Context::OperatorFixity::Infix
  290. : Context::OperatorFixity::Postfix);
  291. }
  292. state.token = context.Consume();
  293. state.lhs_precedence = operator_precedence;
  294. if (is_binary) {
  295. switch (operator_kind) {
  296. // For `and` and `or`, wrap the first operand in a virtual parse tree
  297. // node so that checking can insert control flow here.
  298. case Lex::TokenKind::And:
  299. context.AddNode(NodeKind::ShortCircuitOperandAnd, state.token,
  300. state.has_error);
  301. state.state = State::ExprLoopForShortCircuitOperatorAsAnd;
  302. break;
  303. case Lex::TokenKind::Or:
  304. context.AddNode(NodeKind::ShortCircuitOperandOr, state.token,
  305. state.has_error);
  306. state.state = State::ExprLoopForShortCircuitOperatorAsOr;
  307. break;
  308. // `where` also needs a virtual parse tree node, and parses its right
  309. // argument in a mode where it can handle requirement operators like
  310. // `impls` and `=`.
  311. case Lex::TokenKind::Where:
  312. context.AddNode(NodeKind::WhereOperand, state.token, state.has_error);
  313. context.PushState(state, State::WhereFinish);
  314. context.PushState(State::RequirementBegin);
  315. return;
  316. default:
  317. state.state = State::ExprLoopForInfixOperator;
  318. break;
  319. }
  320. context.PushState(state);
  321. context.PushStateForExpr(operator_precedence);
  322. } else {
  323. NodeKind node_kind;
  324. switch (operator_kind) {
  325. #define CARBON_PARSE_NODE_KIND(...)
  326. #define CARBON_PARSE_NODE_KIND_POSTFIX_OPERATOR(Name, ...) \
  327. case Lex::TokenKind::Name: \
  328. node_kind = NodeKind::PostfixOperator##Name; \
  329. break;
  330. #include "toolchain/parse/node_kind.def"
  331. default:
  332. CARBON_FATAL("Unexpected token kind for postfix operator: {0}",
  333. operator_kind);
  334. }
  335. context.AddNode(node_kind, state.token, state.has_error);
  336. state.has_error = false;
  337. context.PushState(state);
  338. }
  339. }
  340. // Adds the operator node and returns the main expression loop.
  341. static auto HandleExprLoopForOperator(Context& context,
  342. Context::StateStackEntry state,
  343. NodeKind node_kind) -> void {
  344. context.AddNode(node_kind, state.token, state.has_error);
  345. state.has_error = false;
  346. context.PushState(state, State::ExprLoop);
  347. }
  348. auto HandleExprLoopForInfixOperator(Context& context) -> void {
  349. auto state = context.PopState();
  350. switch (auto token_kind = context.tokens().GetKind(state.token)) {
  351. #define CARBON_PARSE_NODE_KIND(...)
  352. #define CARBON_PARSE_NODE_KIND_INFIX_OPERATOR(Name, ...) \
  353. case Lex::TokenKind::Name: \
  354. HandleExprLoopForOperator(context, state, NodeKind::InfixOperator##Name); \
  355. break;
  356. #include "toolchain/parse/node_kind.def"
  357. default:
  358. CARBON_FATAL("Unexpected token kind for infix operator: {0}", token_kind);
  359. }
  360. }
  361. auto HandleExprLoopForPrefixOperator(Context& context) -> void {
  362. auto state = context.PopState();
  363. switch (auto token_kind = context.tokens().GetKind(state.token)) {
  364. #define CARBON_PARSE_NODE_KIND(...)
  365. #define CARBON_PARSE_NODE_KIND_PREFIX_OPERATOR(Name, ...) \
  366. case Lex::TokenKind::Name: \
  367. HandleExprLoopForOperator(context, state, NodeKind::PrefixOperator##Name); \
  368. break;
  369. #include "toolchain/parse/node_kind.def"
  370. default:
  371. CARBON_FATAL("Unexpected token kind for prefix operator: {0}",
  372. token_kind);
  373. }
  374. }
  375. auto HandleExprLoopForShortCircuitOperatorAsAnd(Context& context) -> void {
  376. auto state = context.PopState();
  377. HandleExprLoopForOperator(context, state, NodeKind::ShortCircuitOperatorAnd);
  378. }
  379. auto HandleExprLoopForShortCircuitOperatorAsOr(Context& context) -> void {
  380. auto state = context.PopState();
  381. HandleExprLoopForOperator(context, state, NodeKind::ShortCircuitOperatorOr);
  382. }
  383. auto HandleExprStatementFinish(Context& context) -> void {
  384. auto state = context.PopState();
  385. if (auto semi = context.ConsumeIf(Lex::TokenKind::Semi)) {
  386. context.AddNode(NodeKind::ExprStatement, *semi, state.has_error);
  387. return;
  388. }
  389. if (!state.has_error) {
  390. CARBON_DIAGNOSTIC(ExpectedExprSemi, Error,
  391. "expected `;` after expression statement");
  392. context.emitter().Emit(*context.position(), ExpectedExprSemi);
  393. }
  394. context.AddNode(NodeKind::ExprStatement,
  395. context.SkipPastLikelyEnd(state.token), /*has_error=*/true);
  396. }
  397. } // namespace Carbon::Parse