handle_import_and_package.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/base/shared_value_stores.h"
  5. #include "toolchain/lex/token_kind.h"
  6. #include "toolchain/lex/tokenized_buffer.h"
  7. #include "toolchain/parse/context.h"
  8. #include "toolchain/parse/handle.h"
  9. #include "toolchain/parse/node_ids.h"
  10. #include "toolchain/parse/node_kind.h"
  11. namespace Carbon::Parse {
  12. // Provides common error exiting logic that skips to the semi, if present.
  13. static auto OnParseError(Context& context, Context::StateStackEntry state,
  14. NodeKind declaration) -> void {
  15. context.AddNode(declaration, context.SkipPastLikelyEnd(state.token),
  16. /*has_error=*/true);
  17. }
  18. // Determines whether the specified modifier appears within the introducer of
  19. // the given declaration.
  20. // TODO: Restructure how we handle packaging declarations to avoid the need to
  21. // do this.
  22. static auto HasModifier(Context& context, Context::StateStackEntry state,
  23. Lex::TokenKind modifier) -> bool {
  24. for (Lex::TokenIterator it(state.token); it != context.position(); ++it) {
  25. if (context.tokens().GetKind(*it) == modifier) {
  26. return true;
  27. }
  28. }
  29. return false;
  30. }
  31. // Handles everything after the declaration's introducer.
  32. static auto HandleDeclContent(Context& context, Context::StateStackEntry state,
  33. NodeKind declaration, bool is_export,
  34. bool is_impl,
  35. llvm::function_ref<auto()->void> on_parse_error)
  36. -> void {
  37. Tree::PackagingNames names = {.is_export = is_export};
  38. // Parse the package name.
  39. if (declaration == NodeKind::LibraryDecl ||
  40. (declaration == NodeKind::ImportDecl &&
  41. context.PositionIs(Lex::TokenKind::Library))) {
  42. // This is either `library ...` or `import library ...`, so no package name
  43. // is expected.
  44. } else {
  45. // We require a package name. This is either an identifier or the `Core`
  46. // keyword.
  47. auto package_name_position = *context.position();
  48. if (auto ident = context.ConsumeIf(Lex::TokenKind::Identifier)) {
  49. names.package_id =
  50. PackageNameId::ForIdentifier(context.tokens().GetIdentifier(*ident));
  51. context.AddLeafNode(NodeKind::IdentifierPackageName, *ident);
  52. } else if (auto core = context.ConsumeIf(Lex::TokenKind::Core)) {
  53. names.package_id = PackageNameId::Core;
  54. context.AddLeafNode(NodeKind::CorePackageName, *core);
  55. } else {
  56. CARBON_DIAGNOSTIC(ExpectedIdentifierAfterPackage, Error,
  57. "expected identifier after `package`");
  58. CARBON_DIAGNOSTIC(ExpectedIdentifierAfterImport, Error,
  59. "expected identifier or `library` after `import`");
  60. context.emitter().Emit(package_name_position,
  61. declaration == NodeKind::PackageDecl
  62. ? ExpectedIdentifierAfterPackage
  63. : ExpectedIdentifierAfterImport);
  64. on_parse_error();
  65. return;
  66. }
  67. if (names.is_export) {
  68. names.is_export = false;
  69. state.has_error = true;
  70. CARBON_DIAGNOSTIC(ExportImportPackage, Error,
  71. "`export` cannot be used when importing a package");
  72. context.emitter().Emit(package_name_position, ExportImportPackage);
  73. }
  74. }
  75. // Parse the optional library keyword.
  76. bool accept_default = !names.package_id.has_value();
  77. if (declaration == NodeKind::LibraryDecl) {
  78. auto library_id = context.ParseLibraryName(accept_default);
  79. if (!library_id) {
  80. on_parse_error();
  81. return;
  82. }
  83. names.library_id = *library_id;
  84. } else {
  85. auto next_kind = context.PositionKind();
  86. if (next_kind == Lex::TokenKind::Library) {
  87. if (auto library_id = context.ParseLibrarySpecifier(accept_default)) {
  88. names.library_id = *library_id;
  89. } else {
  90. on_parse_error();
  91. return;
  92. }
  93. } else if (next_kind == Lex::TokenKind::StringLiteral ||
  94. (accept_default && next_kind == Lex::TokenKind::Default)) {
  95. // If we come across a string literal and we didn't parse `library
  96. // "..."` yet, then most probably the user forgot to add `library`
  97. // before the library name.
  98. CARBON_DIAGNOSTIC(MissingLibraryKeyword, Error,
  99. "missing `library` keyword");
  100. context.emitter().Emit(*context.position(), MissingLibraryKeyword);
  101. on_parse_error();
  102. return;
  103. }
  104. }
  105. if (auto semi = context.ConsumeIf(Lex::TokenKind::Semi)) {
  106. auto node_id = context.AddNode(declaration, *semi, state.has_error);
  107. names.node_id = context.tree().As<AnyPackagingDeclId>(node_id);
  108. if (declaration == NodeKind::ImportDecl) {
  109. context.AddImport(names);
  110. } else {
  111. context.set_packaging_decl(names, is_impl);
  112. }
  113. } else {
  114. context.DiagnoseExpectedDeclSemi(context.tokens().GetKind(state.token));
  115. on_parse_error();
  116. }
  117. }
  118. // Returns true if currently in a valid state for imports, false otherwise. May
  119. // update the packaging state respectively.
  120. static auto VerifyInImports(Context& context, Lex::TokenIndex intro_token)
  121. -> bool {
  122. switch (context.packaging_state()) {
  123. case Context::PackagingState::FileStart:
  124. // `package` is no longer allowed, but `import` may repeat.
  125. context.set_packaging_state(Context::PackagingState::InImports);
  126. return true;
  127. case Context::PackagingState::InImports:
  128. return true;
  129. case Context::PackagingState::AfterNonPackagingDecl: {
  130. context.set_packaging_state(
  131. Context::PackagingState::InImportsAfterNonPackagingDecl);
  132. CARBON_DIAGNOSTIC(ImportTooLate, Error,
  133. "`import` declarations must come after the `package` "
  134. "declaration (if present) and before any other "
  135. "entities in the file");
  136. CARBON_DIAGNOSTIC(FirstDecl, Note, "first declaration is here");
  137. context.emitter()
  138. .Build(intro_token, ImportTooLate)
  139. .Note(context.first_non_packaging_token(), FirstDecl)
  140. .Emit();
  141. return false;
  142. }
  143. case Context::PackagingState::InImportsAfterNonPackagingDecl:
  144. // There is a sequential block of misplaced `import` statements, which can
  145. // occur if a declaration is added above `import`s. Avoid duplicate
  146. // warnings.
  147. return false;
  148. }
  149. }
  150. // Diagnoses if `export` is used in an `impl` file.
  151. static auto RestrictExportToApi(Context& context,
  152. Context::StateStackEntry& state) -> void {
  153. // Error for both Main//default and every implementation file.
  154. auto packaging = context.tree().packaging_decl();
  155. if (!packaging || packaging->is_impl) {
  156. CARBON_DIAGNOSTIC(ExportFromImpl, Error,
  157. "`export` is only allowed in API files");
  158. context.emitter().Emit(state.token, ExportFromImpl);
  159. state.has_error = true;
  160. }
  161. }
  162. auto HandleImport(Context& context) -> void {
  163. auto state = context.PopState();
  164. auto declaration = NodeKind::ImportDecl;
  165. auto on_parse_error = [&] { OnParseError(context, state, declaration); };
  166. if (VerifyInImports(context, state.token)) {
  167. // Scan the modifiers to see if this import declaration is exported.
  168. bool is_export = HasModifier(context, state, Lex::TokenKind::Export);
  169. if (is_export) {
  170. RestrictExportToApi(context, state);
  171. }
  172. HandleDeclContent(context, state, declaration, is_export,
  173. /*is_impl=*/false, on_parse_error);
  174. } else {
  175. on_parse_error();
  176. }
  177. }
  178. auto HandleExportName(Context& context) -> void {
  179. auto state = context.PopState();
  180. RestrictExportToApi(context, state);
  181. context.PushState(state, State::ExportNameFinish);
  182. context.PushState(State::DeclNameAndParams, state.token);
  183. }
  184. auto HandleExportNameFinish(Context& context) -> void {
  185. auto state = context.PopState();
  186. context.AddNodeExpectingDeclSemi(state, NodeKind::ExportDecl,
  187. Lex::TokenKind::Export,
  188. /*is_def_allowed=*/false);
  189. }
  190. // Handles common logic for `package` and `library`.
  191. static auto HandlePackageAndLibraryDecls(Context& context,
  192. Lex::TokenKind intro_token_kind,
  193. NodeKind declaration) -> void {
  194. auto state = context.PopState();
  195. bool is_impl = HasModifier(context, state, Lex::TokenKind::Impl);
  196. auto on_parse_error = [&] { OnParseError(context, state, declaration); };
  197. if (state.token != Lex::TokenIndex::FirstNonCommentToken) {
  198. CARBON_DIAGNOSTIC(
  199. PackageTooLate, Error,
  200. "the `{0}` declaration must be the first non-comment line",
  201. Lex::TokenKind);
  202. CARBON_DIAGNOSTIC(FirstNonCommentLine, Note,
  203. "first non-comment line is here");
  204. context.emitter()
  205. .Build(state.token, PackageTooLate, intro_token_kind)
  206. .Note(Lex::TokenIndex::FirstNonCommentToken, FirstNonCommentLine)
  207. .Emit();
  208. on_parse_error();
  209. return;
  210. }
  211. // `package`/`library` is no longer allowed, but `import` may repeat.
  212. context.set_packaging_state(Context::PackagingState::InImports);
  213. HandleDeclContent(context, state, declaration, /*is_export=*/false, is_impl,
  214. on_parse_error);
  215. }
  216. auto HandlePackage(Context& context) -> void {
  217. HandlePackageAndLibraryDecls(context, Lex::TokenKind::Package,
  218. NodeKind::PackageDecl);
  219. }
  220. auto HandleLibrary(Context& context) -> void {
  221. HandlePackageAndLibraryDecls(context, Lex::TokenKind::Library,
  222. NodeKind::LibraryDecl);
  223. }
  224. } // namespace Carbon::Parse