handle_import_and_package.cpp 11 KB

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