handle_decl_scope_loop.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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 OutputInvalidParseSubtree(Context& context, int32_t subtree_start)
  7. -> void {
  8. auto cursor = *context.position();
  9. // Consume to the next `;` or end of line. We ignore the return value since
  10. // we only care how much was consumed, not whether it ended with a `;`.
  11. // TODO: adjust the return of SkipPastLikelyEnd or create a new function
  12. // to avoid going through these hoops.
  13. context.SkipPastLikelyEnd(cursor);
  14. // Set `iter` to the last token consumed, one before the current position.
  15. auto iter = context.position();
  16. --iter;
  17. // Output an invalid parse subtree including everything up to the last token
  18. // consumed.
  19. context.ReplacePlaceholderNode(subtree_start, NodeKind::InvalidParseStart,
  20. cursor, /*has_error=*/true);
  21. context.AddNode(NodeKind::InvalidParseSubtree, *iter, subtree_start,
  22. /*has_error=*/true);
  23. }
  24. // Handles an unrecognized declaration.
  25. static auto HandleUnrecognizedDecl(Context& context, int32_t subtree_start)
  26. -> void {
  27. CARBON_DIAGNOSTIC(UnrecognizedDecl, Error,
  28. "Unrecognized declaration introducer.");
  29. context.emitter().Emit(*context.position(), UnrecognizedDecl);
  30. OutputInvalidParseSubtree(context, subtree_start);
  31. }
  32. static auto TokenIsModifierOrIntroducer(Lex::TokenKind token_kind) -> bool {
  33. switch (token_kind) {
  34. case Lex::TokenKind::Abstract:
  35. case Lex::TokenKind::Base:
  36. case Lex::TokenKind::Class:
  37. case Lex::TokenKind::Constraint:
  38. case Lex::TokenKind::Default:
  39. case Lex::TokenKind::Final:
  40. case Lex::TokenKind::Fn:
  41. case Lex::TokenKind::Impl:
  42. case Lex::TokenKind::Interface:
  43. case Lex::TokenKind::Let:
  44. case Lex::TokenKind::Private:
  45. case Lex::TokenKind::Protected:
  46. case Lex::TokenKind::Var:
  47. case Lex::TokenKind::Virtual:
  48. return true;
  49. default:
  50. return false;
  51. }
  52. }
  53. auto HandleDeclScopeLoop(Context& context) -> void {
  54. // This maintains the current state unless we're at the end of the scope.
  55. switch (context.PositionKind()) {
  56. case Lex::TokenKind::CloseCurlyBrace:
  57. case Lex::TokenKind::FileEnd: {
  58. // This is the end of the scope, so the loop state ends.
  59. context.PopAndDiscardState();
  60. return;
  61. }
  62. // `import`, `library`, and `package` manage their packaging state.
  63. case Lex::TokenKind::Import: {
  64. context.PushState(State::Import);
  65. return;
  66. }
  67. case Lex::TokenKind::Library: {
  68. context.PushState(State::Library);
  69. return;
  70. }
  71. case Lex::TokenKind::Package: {
  72. context.PushState(State::Package);
  73. return;
  74. }
  75. default: {
  76. break;
  77. }
  78. }
  79. // Because a non-packaging keyword was encountered, packaging is complete.
  80. // Misplaced packaging keywords may lead to this being re-triggered.
  81. if (context.packaging_state() !=
  82. Context::PackagingState::AfterNonPackagingDecl) {
  83. if (!context.first_non_packaging_token().is_valid()) {
  84. context.set_first_non_packaging_token(*context.position());
  85. }
  86. context.set_packaging_state(Context::PackagingState::AfterNonPackagingDecl);
  87. }
  88. // Remaining keywords are only valid after imports are complete, and so all
  89. // result in a `set_packaging_state` call. Note, this may not always be
  90. // necessary but is probably cheaper than validating.
  91. // Create a state with the correct starting position, with a dummy kind until
  92. // we see the declaration's introducer.
  93. context.PushState(State::DeclScopeLoop);
  94. auto state = context.PopState();
  95. // Add a placeholder node, to be replaced by the declaration introducer once
  96. // it is found.
  97. context.AddLeafNode(NodeKind::Placeholder, *context.position());
  98. auto introducer = [&](NodeKind node_kind, State next_state) {
  99. context.ReplacePlaceholderNode(state.subtree_start, node_kind,
  100. context.Consume());
  101. // Reuse state here to retain its `subtree_start`
  102. state.state = next_state;
  103. context.PushState(state);
  104. };
  105. bool saw_modifier = false;
  106. while (true) {
  107. switch (context.PositionKind()) {
  108. // If we see a access modifier keyword token, add it as a leaf node
  109. // and repeat with the next token.
  110. case Lex::TokenKind::Private:
  111. case Lex::TokenKind::Protected: {
  112. auto modifier_token = context.Consume();
  113. context.AddLeafNode(NodeKind::AccessModifierKeyword, modifier_token);
  114. saw_modifier = true;
  115. break;
  116. }
  117. case Lex::TokenKind::Base:
  118. // `base` may be followed by:
  119. // - a colon
  120. // => assume it is an introducer, as in `extend base: BaseType;`.
  121. // - a modifier or an introducer
  122. // => assume it is a modifier, as in `base class`; which is handled
  123. // by falling through to the next case.
  124. // Anything else is an error.
  125. if (context.PositionIs(Lex::TokenKind::Colon, Lookahead::NextToken)) {
  126. context.ReplacePlaceholderNode(
  127. state.subtree_start, NodeKind::BaseIntroducer, context.Consume());
  128. // Reuse state here to retain its `subtree_start`
  129. state.state = State::BaseDecl;
  130. context.PushState(state);
  131. context.PushState(State::Expr);
  132. context.AddLeafNode(NodeKind::BaseColon, context.Consume());
  133. return;
  134. } else if (!TokenIsModifierOrIntroducer(
  135. context.PositionKind(Lookahead::NextToken))) {
  136. // TODO: If the next token isn't a colon or `class`, try to recover
  137. // based on whether we're in a class, whether we have an `extend`
  138. // modifier, and the following tokens.
  139. context.AddLeafNode(NodeKind::InvalidParse, context.Consume(),
  140. /*has_error=*/true);
  141. CARBON_DIAGNOSTIC(ExpectedAfterBase, Error,
  142. "`class` or `:` expected after `base`.");
  143. context.emitter().Emit(*context.position(), ExpectedAfterBase);
  144. OutputInvalidParseSubtree(context, state.subtree_start);
  145. return;
  146. }
  147. [[fallthrough]];
  148. // If we see a declaration modifier keyword token, add it as a leaf node
  149. // and repeat with the next token.
  150. case Lex::TokenKind::Abstract:
  151. case Lex::TokenKind::Default:
  152. case Lex::TokenKind::Final:
  153. case Lex::TokenKind::Virtual: {
  154. auto modifier_token = context.Consume();
  155. context.AddLeafNode(NodeKind::DeclModifierKeyword, modifier_token);
  156. saw_modifier = true;
  157. break;
  158. }
  159. case Lex::TokenKind::Impl: {
  160. // `impl` is considered a declaration modifier if it is followed by
  161. // another modifier or an introducer.
  162. if (TokenIsModifierOrIntroducer(
  163. context.PositionKind(Lookahead::NextToken))) {
  164. context.AddLeafNode(NodeKind::DeclModifierKeyword, context.Consume());
  165. saw_modifier = true;
  166. } else {
  167. // TODO: Treat this `impl` token as a declaration introducer
  168. HandleUnrecognizedDecl(context, state.subtree_start);
  169. return;
  170. }
  171. break;
  172. }
  173. // If we see a declaration introducer keyword token, replace the
  174. // placeholder node and switch to a state to parse the rest of the
  175. // declaration. We don't allow namespace or empty declarations here since
  176. // they can't have modifiers and don't use bracketing parse nodes that
  177. // would allow a variable number of modifier nodes.
  178. case Lex::TokenKind::Class: {
  179. introducer(NodeKind::ClassIntroducer,
  180. State::TypeAfterIntroducerAsClass);
  181. return;
  182. }
  183. case Lex::TokenKind::Constraint: {
  184. introducer(NodeKind::NamedConstraintIntroducer,
  185. State::TypeAfterIntroducerAsNamedConstraint);
  186. return;
  187. }
  188. case Lex::TokenKind::Fn: {
  189. introducer(NodeKind::FunctionIntroducer, State::FunctionIntroducer);
  190. return;
  191. }
  192. case Lex::TokenKind::Interface: {
  193. introducer(NodeKind::InterfaceIntroducer,
  194. State::TypeAfterIntroducerAsInterface);
  195. return;
  196. }
  197. case Lex::TokenKind::Var: {
  198. introducer(NodeKind::VariableIntroducer, State::VarAsDecl);
  199. return;
  200. }
  201. case Lex::TokenKind::Let: {
  202. introducer(NodeKind::LetIntroducer, State::Let);
  203. return;
  204. }
  205. // We don't allow namespace or empty declarations after a modifier since
  206. // they can't have modifiers and don't use bracketing parse nodes that
  207. // would allow a variable number of modifier nodes.
  208. case Lex::TokenKind::Namespace: {
  209. if (saw_modifier) {
  210. CARBON_DIAGNOSTIC(NamespaceAfterModifiers, Error,
  211. "`namespace` unexpected after modifiers.");
  212. context.emitter().Emit(*context.position(), NamespaceAfterModifiers);
  213. OutputInvalidParseSubtree(context, state.subtree_start);
  214. } else {
  215. introducer(NodeKind::NamespaceStart, State::Namespace);
  216. }
  217. return;
  218. }
  219. case Lex::TokenKind::Semi: {
  220. if (saw_modifier) {
  221. HandleUnrecognizedDecl(context, state.subtree_start);
  222. } else {
  223. context.ReplacePlaceholderNode(
  224. state.subtree_start, NodeKind::EmptyDecl, context.Consume());
  225. }
  226. return;
  227. }
  228. default: {
  229. // For anything else, report an error and output an invalid parse node
  230. // or subtree.
  231. HandleUnrecognizedDecl(context, state.subtree_start);
  232. return;
  233. }
  234. }
  235. }
  236. }
  237. } // namespace Carbon::Parse