handle_import_and_package.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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::State 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::State 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. template <const Parse::NodeKind& DeclKind>
  33. static auto HandleDeclContent(Context& context, Context::State state,
  34. bool is_export, 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 (DeclKind == NodeKind::LibraryDecl ||
  40. (DeclKind == 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 package name
  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 if (auto cpp = context.ConsumeIf(Lex::TokenKind::Cpp)) {
  56. names.package_id = PackageNameId::Cpp;
  57. context.AddLeafNode(NodeKind::CppPackageName, *cpp);
  58. } else {
  59. CARBON_DIAGNOSTIC(ExpectedIdentifierAfterPackage, Error,
  60. "expected identifier after `package`");
  61. CARBON_DIAGNOSTIC(ExpectedIdentifierAfterImport, Error,
  62. "expected identifier or `library` after `import`");
  63. context.emitter().Emit(package_name_position,
  64. DeclKind == NodeKind::PackageDecl
  65. ? ExpectedIdentifierAfterPackage
  66. : ExpectedIdentifierAfterImport);
  67. on_parse_error();
  68. return;
  69. }
  70. if (names.is_export) {
  71. names.is_export = false;
  72. state.has_error = true;
  73. CARBON_DIAGNOSTIC(ExportImportPackage, Error,
  74. "`export` cannot be used when importing a package");
  75. context.emitter().Emit(package_name_position, ExportImportPackage);
  76. }
  77. }
  78. // Parse the optional library keyword.
  79. bool accept_default = !names.package_id.has_value();
  80. if constexpr (DeclKind == NodeKind::LibraryDecl) {
  81. auto library_id = context.ParseLibraryName(accept_default);
  82. if (!library_id) {
  83. on_parse_error();
  84. return;
  85. }
  86. names.library_id = *library_id;
  87. } else {
  88. auto next_kind = context.PositionKind();
  89. if (next_kind == Lex::TokenKind::Library) {
  90. if (auto library_id = context.ParseLibrarySpecifier(accept_default)) {
  91. names.library_id = *library_id;
  92. } else {
  93. on_parse_error();
  94. return;
  95. }
  96. } else if (DeclKind == NodeKind::ImportDecl &&
  97. next_kind == Lex::TokenKind::Inline) {
  98. auto inline_token = context.ConsumeChecked(Lex::TokenKind::Inline);
  99. auto body_position = *context.position();
  100. auto inline_body_token = context.ConsumeIf(Lex::TokenKind::StringLiteral);
  101. names.inline_body_id = context.AddNode<NodeKind::InlineImportBody>(
  102. body_position, /*has_error=*/!inline_body_token);
  103. context.AddNode(NodeKind::InlineImportSpecifier, inline_token,
  104. /*has_error=*/false);
  105. if (!inline_body_token) {
  106. CARBON_DIAGNOSTIC(ExpectedStringAfterInline, Error,
  107. "expected string literal after `inline`");
  108. context.emitter().Emit(body_position, ExpectedStringAfterInline);
  109. on_parse_error();
  110. return;
  111. }
  112. } else if (next_kind == Lex::TokenKind::StringLiteral ||
  113. (accept_default && next_kind == Lex::TokenKind::Default)) {
  114. // If we come across a string literal and we didn't parse `library
  115. // "..."` yet, then most probably the user forgot to add `library`
  116. // before the library name.
  117. CARBON_DIAGNOSTIC(MissingLibraryKeyword, Error,
  118. "missing `library` keyword");
  119. context.emitter().Emit(*context.position(), MissingLibraryKeyword);
  120. on_parse_error();
  121. return;
  122. }
  123. }
  124. if (auto semi = context.ConsumeIf(Lex::TokenKind::Semi)) {
  125. names.node_id = context.AddNode<DeclKind>(*semi, state.has_error);
  126. if constexpr (DeclKind == NodeKind::ImportDecl) {
  127. context.AddImport(names);
  128. } else {
  129. context.set_packaging_decl(names, is_impl);
  130. }
  131. } else {
  132. context.DiagnoseExpectedDeclSemi(context.tokens().GetKind(state.token));
  133. on_parse_error();
  134. }
  135. }
  136. // Returns true if currently in a valid state for imports, false otherwise. May
  137. // update the packaging state respectively.
  138. static auto VerifyInImports(Context& context, Lex::TokenIndex intro_token)
  139. -> bool {
  140. switch (context.packaging_state()) {
  141. case Context::PackagingState::FileStart:
  142. // `package` is no longer allowed, but `import` may repeat.
  143. context.set_packaging_state(Context::PackagingState::InImports);
  144. return true;
  145. case Context::PackagingState::InImports:
  146. return true;
  147. case Context::PackagingState::AfterNonPackagingDecl: {
  148. context.set_packaging_state(
  149. Context::PackagingState::InImportsAfterNonPackagingDecl);
  150. CARBON_DIAGNOSTIC(ImportTooLate, Error,
  151. "`import` declarations must come after the `package` "
  152. "declaration (if present) and before any other "
  153. "entities in the file");
  154. CARBON_DIAGNOSTIC(FirstDecl, Note, "first declaration is here");
  155. context.emitter()
  156. .Build(intro_token, ImportTooLate)
  157. .Note(context.first_non_packaging_token(), FirstDecl)
  158. .Emit();
  159. return false;
  160. }
  161. case Context::PackagingState::InImportsAfterNonPackagingDecl:
  162. // There is a sequential block of misplaced `import` statements, which can
  163. // occur if a declaration is added above `import`s. Avoid duplicate
  164. // warnings.
  165. return false;
  166. }
  167. }
  168. // Diagnoses if `export` is used in an `impl` file.
  169. static auto RestrictExportToApi(Context& context, Context::State& state)
  170. -> void {
  171. // Error for both Main//default and every implementation file.
  172. auto packaging = context.tree().packaging_decl();
  173. if (!packaging || packaging->is_impl) {
  174. CARBON_DIAGNOSTIC(ExportFromImpl, Error,
  175. "`export` is only allowed in API files");
  176. context.emitter().Emit(state.token, ExportFromImpl);
  177. state.has_error = true;
  178. }
  179. }
  180. auto HandleImport(Context& context) -> void {
  181. auto state = context.PopState();
  182. auto on_parse_error = [&] {
  183. OnParseError(context, state, NodeKind::ImportDecl);
  184. };
  185. if (VerifyInImports(context, state.token)) {
  186. // Scan the modifiers to see if this import declaration is exported.
  187. bool is_export = HasModifier(context, state, Lex::TokenKind::Export);
  188. if (is_export) {
  189. RestrictExportToApi(context, state);
  190. }
  191. HandleDeclContent<NodeKind::ImportDecl>(context, state, is_export,
  192. /*is_impl=*/false, on_parse_error);
  193. } else {
  194. on_parse_error();
  195. }
  196. }
  197. auto HandleExportName(Context& context) -> void {
  198. auto state = context.PopState();
  199. RestrictExportToApi(context, state);
  200. context.PushState(state, StateKind::ExportNameFinish);
  201. context.PushState(StateKind::DeclNameAndParams, state.token);
  202. }
  203. auto HandleExportNameFinish(Context& context) -> void {
  204. auto state = context.PopState();
  205. context.AddNodeExpectingDeclSemi(state, NodeKind::ExportDecl,
  206. Lex::TokenKind::Export,
  207. /*is_def_allowed=*/false);
  208. }
  209. // Handles common logic for `package` and `library`.
  210. template <const Parse::NodeKind& DeclKind>
  211. static auto HandlePackageAndLibraryDecls(Context& context,
  212. Lex::TokenKind intro_token_kind)
  213. -> void {
  214. auto state = context.PopState();
  215. bool is_impl = HasModifier(context, state, Lex::TokenKind::Impl);
  216. auto on_parse_error = [&] { OnParseError(context, state, DeclKind); };
  217. if (state.token != Lex::TokenIndex::FirstNonCommentToken) {
  218. CARBON_DIAGNOSTIC(
  219. PackageTooLate, Error,
  220. "the `{0}` declaration must be the first non-comment line",
  221. Lex::TokenKind);
  222. CARBON_DIAGNOSTIC(FirstNonCommentLine, Note,
  223. "first non-comment line is here");
  224. context.emitter()
  225. .Build(state.token, PackageTooLate, intro_token_kind)
  226. .Note(Lex::TokenIndex::FirstNonCommentToken, FirstNonCommentLine)
  227. .Emit();
  228. on_parse_error();
  229. return;
  230. }
  231. // `package`/`library` is no longer allowed, but `import` may repeat.
  232. context.set_packaging_state(Context::PackagingState::InImports);
  233. HandleDeclContent<DeclKind>(context, state, /*is_export=*/false, is_impl,
  234. on_parse_error);
  235. }
  236. auto HandlePackage(Context& context) -> void {
  237. HandlePackageAndLibraryDecls<NodeKind::PackageDecl>(context,
  238. Lex::TokenKind::Package);
  239. }
  240. auto HandleLibrary(Context& context) -> void {
  241. HandlePackageAndLibraryDecls<NodeKind::LibraryDecl>(context,
  242. Lex::TokenKind::Library);
  243. }
  244. } // namespace Carbon::Parse