handle_import_and_package.cpp 6.6 KB

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