handle_function.cpp 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. auto HandleFunctionIntroducer(Context& context) -> void {
  7. auto state = context.PopState();
  8. state.state = State::FunctionAfterParams;
  9. context.PushState(state);
  10. context.PushState(State::DeclNameAndParamsAsRequired, state.token);
  11. }
  12. auto HandleFunctionAfterParams(Context& context) -> void {
  13. auto state = context.PopState();
  14. // Regardless of whether there's a return type, we'll finish the signature.
  15. state.state = State::FunctionSignatureFinish;
  16. context.PushState(state);
  17. // If there is a return type, parse the expression before adding the return
  18. // type node.
  19. if (context.PositionIs(Lex::TokenKind::MinusGreater)) {
  20. context.PushState(State::FunctionReturnTypeFinish);
  21. context.ConsumeAndDiscard();
  22. context.PushStateForExpr(PrecedenceGroup::ForType());
  23. }
  24. }
  25. auto HandleFunctionReturnTypeFinish(Context& context) -> void {
  26. auto state = context.PopState();
  27. context.AddNode(NodeKind::ReturnType, state.token, state.subtree_start,
  28. state.has_error);
  29. }
  30. auto HandleFunctionSignatureFinish(Context& context) -> void {
  31. auto state = context.PopState();
  32. switch (context.PositionKind()) {
  33. case Lex::TokenKind::Semi: {
  34. context.AddNode(NodeKind::FunctionDecl, context.Consume(),
  35. state.subtree_start, state.has_error);
  36. break;
  37. }
  38. case Lex::TokenKind::OpenCurlyBrace: {
  39. context.AddNode(NodeKind::FunctionDefinitionStart, context.Consume(),
  40. state.subtree_start, state.has_error);
  41. // Any error is recorded on the FunctionDefinitionStart.
  42. state.has_error = false;
  43. state.state = State::FunctionDefinitionFinish;
  44. context.PushState(state);
  45. context.PushState(State::StatementScopeLoop);
  46. break;
  47. }
  48. default: {
  49. if (!state.has_error) {
  50. context.EmitExpectedDeclSemiOrDefinition(Lex::TokenKind::Fn);
  51. }
  52. // Only need to skip if we've not already found a new line.
  53. bool skip_past_likely_end =
  54. context.tokens().GetLine(*context.position()) ==
  55. context.tokens().GetLine(state.token);
  56. context.RecoverFromDeclError(state, NodeKind::FunctionDecl,
  57. skip_past_likely_end);
  58. break;
  59. }
  60. }
  61. }
  62. auto HandleFunctionDefinitionFinish(Context& context) -> void {
  63. auto state = context.PopState();
  64. context.AddNode(NodeKind::FunctionDefinition, context.Consume(),
  65. state.subtree_start, state.has_error);
  66. }
  67. } // namespace Carbon::Parse