handle_import_and_package.cpp 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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/tokenized_buffer.h"
  5. #include "toolchain/parse/context.h"
  6. namespace Carbon::Parse {
  7. // Provides error exiting logic for `import`/`package`, skipping to the semi.
  8. static auto ExitOnParseError(Context& context, Context::StateStackEntry state,
  9. NodeKind directive) {
  10. auto semi_token = context.SkipPastLikelyEnd(state.token);
  11. return context.AddNode(directive, semi_token ? *semi_token : state.token,
  12. state.subtree_start,
  13. /*has_error=*/true);
  14. }
  15. // Handles the main parsing of `import`/`package`. It's expected that the
  16. // introducer is already added.
  17. static auto HandleImportAndPackage(Context& context,
  18. Context::StateStackEntry state,
  19. NodeKind directive, bool expect_api_or_impl)
  20. -> void {
  21. if (!context.ConsumeAndAddLeafNodeIf(Lex::TokenKind::Identifier,
  22. NodeKind::Name)) {
  23. CARBON_DIAGNOSTIC(ExpectedIdentifierAfterKeyword, Error,
  24. "Expected identifier after `{0}`.", Lex::TokenKind);
  25. context.emitter().Emit(*context.position(), ExpectedIdentifierAfterKeyword,
  26. context.tokens().GetKind(state.token));
  27. ExitOnParseError(context, state, directive);
  28. return;
  29. }
  30. bool library_parsed = false;
  31. if (auto library_token = context.ConsumeIf(Lex::TokenKind::Library)) {
  32. auto library_start = context.tree().size();
  33. if (!context.ConsumeAndAddLeafNodeIf(Lex::TokenKind::StringLiteral,
  34. NodeKind::Literal)) {
  35. CARBON_DIAGNOSTIC(
  36. ExpectedLibraryName, Error,
  37. "Expected a string literal to specify the library name.");
  38. context.emitter().Emit(*context.position(), ExpectedLibraryName);
  39. ExitOnParseError(context, state, directive);
  40. return;
  41. }
  42. context.AddNode(NodeKind::Library, *library_token, library_start,
  43. /*has_error=*/false);
  44. library_parsed = true;
  45. }
  46. auto next_kind = context.tokens().GetKind(*(context.position()));
  47. if (!library_parsed && next_kind == Lex::TokenKind::StringLiteral) {
  48. // If we come acroess a string literal and we didn't parse `library
  49. // "..."` yet, then most probably the user forgot to add `library`
  50. // before the library name.
  51. CARBON_DIAGNOSTIC(MissingLibraryKeyword, Error,
  52. "Missing `library` keyword.");
  53. context.emitter().Emit(*context.position(), MissingLibraryKeyword);
  54. ExitOnParseError(context, state, directive);
  55. return;
  56. }
  57. if (expect_api_or_impl) {
  58. switch (next_kind) {
  59. case Lex::TokenKind::Api: {
  60. context.AddLeafNode(NodeKind::PackageApi, context.Consume());
  61. break;
  62. }
  63. case Lex::TokenKind::Impl: {
  64. context.AddLeafNode(NodeKind::PackageImpl, context.Consume());
  65. break;
  66. }
  67. default: {
  68. CARBON_DIAGNOSTIC(ExpectedApiOrImpl, Error,
  69. "Expected `api` or `impl`.");
  70. context.emitter().Emit(*context.position(), ExpectedApiOrImpl);
  71. ExitOnParseError(context, state, directive);
  72. return;
  73. }
  74. }
  75. }
  76. if (!context.PositionIs(Lex::TokenKind::Semi)) {
  77. context.EmitExpectedDeclSemi(context.tokens().GetKind(state.token));
  78. ExitOnParseError(context, state, directive);
  79. return;
  80. }
  81. context.AddNode(directive, context.Consume(), state.subtree_start,
  82. state.has_error);
  83. }
  84. auto HandleImport(Context& context) -> void {
  85. auto state = context.PopState();
  86. auto intro_token = context.Consume();
  87. context.AddLeafNode(NodeKind::ImportIntroducer, intro_token);
  88. switch (context.packaging_state()) {
  89. case Context::PackagingState::StartOfFile:
  90. // `package` is no longer allowed, but `import` may repeat.
  91. context.set_packaging_state(Context::PackagingState::InImports);
  92. [[clang::fallthrough]];
  93. case Context::PackagingState::InImports:
  94. HandleImportAndPackage(context, state, NodeKind::ImportDirective,
  95. /*expect_api_or_impl=*/false);
  96. break;
  97. case Context::PackagingState::AfterNonPackagingDecl: {
  98. context.set_packaging_state(
  99. Context::PackagingState::InImportsAfterNonPackagingDecl);
  100. CARBON_DIAGNOSTIC(
  101. ImportTooLate, Error,
  102. "`import` directives must come after the `package` directive (if "
  103. "present) and before any other entities in the file.");
  104. CARBON_DIAGNOSTIC(FirstDecl, Note, "First declaration is here.");
  105. context.emitter()
  106. .Build(intro_token, ImportTooLate)
  107. .Note(context.first_non_packaging_token(), FirstDecl)
  108. .Emit();
  109. ExitOnParseError(context, state, NodeKind::ImportDirective);
  110. break;
  111. }
  112. case Context::PackagingState::InImportsAfterNonPackagingDecl:
  113. // There is a sequential block of misplaced `import` statements, which can
  114. // occur if a declaration is added above `import`s. Avoid duplicate
  115. // warnings.
  116. ExitOnParseError(context, state, NodeKind::ImportDirective);
  117. break;
  118. }
  119. }
  120. auto HandlePackage(Context& context) -> void {
  121. auto state = context.PopState();
  122. auto intro_token = context.Consume();
  123. context.AddLeafNode(NodeKind::PackageIntroducer, intro_token);
  124. if (intro_token != Lex::Token::FirstNonCommentToken) {
  125. CARBON_DIAGNOSTIC(
  126. PackageTooLate, Error,
  127. "The `package` directive must be the first non-comment line.");
  128. CARBON_DIAGNOSTIC(FirstNonCommentLine, Note,
  129. "First non-comment line is here.");
  130. context.emitter()
  131. .Build(intro_token, PackageTooLate)
  132. .Note(Lex::Token::FirstNonCommentToken, FirstNonCommentLine)
  133. .Emit();
  134. ExitOnParseError(context, state, NodeKind::PackageDirective);
  135. return;
  136. }
  137. // `package` is no longer allowed, but `import` may repeat.
  138. context.set_packaging_state(Context::PackagingState::InImports);
  139. HandleImportAndPackage(context, state, NodeKind::PackageDirective,
  140. /*expect_api_or_impl=*/true);
  141. }
  142. } // namespace Carbon::Parse