merge.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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/check/merge.h"
  5. #include "toolchain/base/kind_switch.h"
  6. #include "toolchain/check/import_ref.h"
  7. #include "toolchain/sem_ir/ids.h"
  8. #include "toolchain/sem_ir/typed_insts.h"
  9. namespace Carbon::Check {
  10. CARBON_DIAGNOSTIC(RedeclPrevDecl, Note, "previously declared here");
  11. // Diagnoses a redeclaration which is redundant.
  12. static auto DiagnoseRedundant(Context& context, Lex::TokenKind decl_kind,
  13. SemIR::NameId name_id, SemIRLoc new_loc,
  14. SemIRLoc prev_loc) -> void {
  15. CARBON_DIAGNOSTIC(RedeclRedundant, Error,
  16. "redeclaration of `{0} {1}` is redundant", Lex::TokenKind,
  17. SemIR::NameId);
  18. context.emitter()
  19. .Build(new_loc, RedeclRedundant, decl_kind, name_id)
  20. .Note(prev_loc, RedeclPrevDecl)
  21. .Emit();
  22. }
  23. // Diagnoses a redefinition.
  24. static auto DiagnoseRedef(Context& context, Lex::TokenKind decl_kind,
  25. SemIR::NameId name_id, SemIRLoc new_loc,
  26. SemIRLoc prev_loc) -> void {
  27. CARBON_DIAGNOSTIC(RedeclRedef, Error, "redefinition of `{0} {1}`",
  28. Lex::TokenKind, SemIR::NameId);
  29. CARBON_DIAGNOSTIC(RedeclPrevDef, Note, "previously defined here");
  30. context.emitter()
  31. .Build(new_loc, RedeclRedef, decl_kind, name_id)
  32. .Note(prev_loc, RedeclPrevDef)
  33. .Emit();
  34. }
  35. // Diagnoses an `extern` versus non-`extern` mismatch.
  36. static auto DiagnoseExternMismatch(Context& context, Lex::TokenKind decl_kind,
  37. SemIR::NameId name_id, SemIRLoc new_loc,
  38. SemIRLoc prev_loc) -> void {
  39. CARBON_DIAGNOSTIC(RedeclExternMismatch, Error,
  40. "redeclarations of `{0} {1}` must match use of `extern`",
  41. Lex::TokenKind, SemIR::NameId);
  42. context.emitter()
  43. .Build(new_loc, RedeclExternMismatch, decl_kind, name_id)
  44. .Note(prev_loc, RedeclPrevDecl)
  45. .Emit();
  46. }
  47. // Diagnoses `extern library` declared in a library importing the owned entity.
  48. static auto DiagnoseExternLibraryInImporter(Context& context,
  49. Lex::TokenKind decl_kind,
  50. SemIR::NameId name_id,
  51. SemIRLoc new_loc, SemIRLoc prev_loc)
  52. -> void {
  53. CARBON_DIAGNOSTIC(ExternLibraryInImporter, Error,
  54. "cannot declare imported `{0} {1}` as `extern library`",
  55. Lex::TokenKind, SemIR::NameId);
  56. context.emitter()
  57. .Build(new_loc, ExternLibraryInImporter, decl_kind, name_id)
  58. .Note(prev_loc, RedeclPrevDecl)
  59. .Emit();
  60. }
  61. // Diagnoses `extern library` pointing to the wrong library.
  62. static auto DiagnoseExternLibraryIncorrect(Context& context, SemIRLoc new_loc,
  63. SemIRLoc prev_loc) -> void {
  64. CARBON_DIAGNOSTIC(
  65. ExternLibraryIncorrect, Error,
  66. "declaration in {0} doesn't match `extern library` declaration",
  67. SemIR::LibraryNameId);
  68. CARBON_DIAGNOSTIC(ExternLibraryExpected, Note,
  69. "previously declared with `extern library` here");
  70. context.emitter()
  71. .Build(new_loc, ExternLibraryIncorrect, context.sem_ir().library_id())
  72. .Note(prev_loc, ExternLibraryExpected)
  73. .Emit();
  74. }
  75. auto DiagnoseExternRequiresDeclInApiFile(Context& context, SemIRLoc loc)
  76. -> void {
  77. CARBON_DIAGNOSTIC(
  78. ExternRequiresDeclInApiFile, Error,
  79. "`extern` entities must have a declaration in the API file");
  80. context.emitter().Build(loc, ExternRequiresDeclInApiFile).Emit();
  81. }
  82. // Checks to see if a structurally valid redeclaration is allowed in context.
  83. // These all still merge.
  84. auto CheckIsAllowedRedecl(Context& context, Lex::TokenKind decl_kind,
  85. SemIR::NameId name_id, RedeclInfo new_decl,
  86. RedeclInfo prev_decl, SemIR::ImportIRId import_ir_id)
  87. -> void {
  88. if (!import_ir_id.is_valid()) {
  89. // Check for disallowed redeclarations in the same file.
  90. if (!new_decl.is_definition) {
  91. DiagnoseRedundant(context, decl_kind, name_id, new_decl.loc,
  92. prev_decl.loc);
  93. return;
  94. }
  95. if (prev_decl.is_definition) {
  96. DiagnoseRedef(context, decl_kind, name_id, new_decl.loc, prev_decl.loc);
  97. return;
  98. }
  99. if (prev_decl.is_extern != new_decl.is_extern) {
  100. DiagnoseExternMismatch(context, decl_kind, name_id, new_decl.loc,
  101. prev_decl.loc);
  102. return;
  103. }
  104. return;
  105. }
  106. if (import_ir_id == SemIR::ImportIRId::ApiForImpl) {
  107. // Check for disallowed redeclarations in the same library. Note that a
  108. // forward declaration in the impl is allowed.
  109. if (prev_decl.is_definition) {
  110. if (new_decl.is_definition) {
  111. DiagnoseRedef(context, decl_kind, name_id, new_decl.loc, prev_decl.loc);
  112. } else {
  113. DiagnoseRedundant(context, decl_kind, name_id, new_decl.loc,
  114. prev_decl.loc);
  115. }
  116. return;
  117. }
  118. if (prev_decl.is_extern != new_decl.is_extern) {
  119. DiagnoseExternMismatch(context, decl_kind, name_id, new_decl.loc,
  120. prev_decl.loc);
  121. return;
  122. }
  123. return;
  124. }
  125. // Check for disallowed redeclarations cross-library.
  126. if (new_decl.is_extern && context.IsImplFile()) {
  127. // We continue after issuing the "missing API declaration" diagnostic,
  128. // because it may still be helpful to note other issues with the
  129. // declarations.
  130. DiagnoseExternRequiresDeclInApiFile(context, new_decl.loc);
  131. }
  132. if (prev_decl.is_extern != new_decl.is_extern) {
  133. DiagnoseExternMismatch(context, decl_kind, name_id, new_decl.loc,
  134. prev_decl.loc);
  135. return;
  136. }
  137. if (!prev_decl.extern_library_id.is_valid()) {
  138. if (new_decl.extern_library_id.is_valid()) {
  139. DiagnoseExternLibraryInImporter(context, decl_kind, name_id, new_decl.loc,
  140. prev_decl.loc);
  141. } else {
  142. DiagnoseRedundant(context, decl_kind, name_id, new_decl.loc,
  143. prev_decl.loc);
  144. }
  145. return;
  146. }
  147. if (prev_decl.extern_library_id != SemIR::LibraryNameId::Error &&
  148. prev_decl.extern_library_id != context.sem_ir().library_id()) {
  149. DiagnoseExternLibraryIncorrect(context, new_decl.loc, prev_decl.loc);
  150. return;
  151. }
  152. }
  153. auto ReplacePrevInstForMerge(Context& context, SemIR::NameScopeId scope_id,
  154. SemIR::NameId name_id, SemIR::InstId new_inst_id)
  155. -> void {
  156. auto& scope = context.name_scopes().Get(scope_id);
  157. if (auto lookup = scope.name_map.Lookup(name_id)) {
  158. scope.names[lookup.value()].inst_id = new_inst_id;
  159. }
  160. }
  161. // Returns true if there was an error in declaring the entity, which will have
  162. // previously been diagnosed.
  163. static auto EntityHasParamError(Context& context, const DeclParams& info)
  164. -> bool {
  165. for (auto param_refs_id : {info.implicit_param_refs_id, info.param_refs_id}) {
  166. if (param_refs_id.is_valid() &&
  167. param_refs_id != SemIR::InstBlockId::Empty) {
  168. for (auto param_id : context.inst_blocks().Get(param_refs_id)) {
  169. if (context.insts().Get(param_id).type_id() == SemIR::TypeId::Error) {
  170. return true;
  171. }
  172. }
  173. }
  174. }
  175. return false;
  176. }
  177. // Returns false if a param differs for a redeclaration. The caller is expected
  178. // to provide a diagnostic.
  179. static auto CheckRedeclParam(Context& context,
  180. llvm::StringLiteral param_diag_label,
  181. int32_t param_index,
  182. SemIR::InstId new_param_ref_id,
  183. SemIR::InstId prev_param_ref_id,
  184. SemIR::SpecificId prev_specific_id) -> bool {
  185. // TODO: Consider differentiating between type and name mistakes. For now,
  186. // taking the simpler approach because I also think we may want to refactor
  187. // params.
  188. auto diagnose = [&]() {
  189. CARBON_DIAGNOSTIC(RedeclParamDiffers, Error,
  190. "redeclaration differs at {0}parameter {1}",
  191. llvm::StringLiteral, int32_t);
  192. CARBON_DIAGNOSTIC(RedeclParamPrevious, Note,
  193. "previous declaration's corresponding {0}parameter here",
  194. llvm::StringLiteral);
  195. context.emitter()
  196. .Build(new_param_ref_id, RedeclParamDiffers, param_diag_label,
  197. param_index + 1)
  198. .Note(prev_param_ref_id, RedeclParamPrevious, param_diag_label)
  199. .Emit();
  200. };
  201. auto new_param_ref = context.insts().Get(new_param_ref_id);
  202. auto prev_param_ref = context.insts().Get(prev_param_ref_id);
  203. if (new_param_ref.kind() != prev_param_ref.kind() ||
  204. !context.types().AreEqualAcrossDeclarations(
  205. new_param_ref.type_id(),
  206. SemIR::GetTypeInSpecific(context.sem_ir(), prev_specific_id,
  207. prev_param_ref.type_id()))) {
  208. diagnose();
  209. return false;
  210. }
  211. if (new_param_ref.Is<SemIR::AddrPattern>()) {
  212. new_param_ref =
  213. context.insts().Get(new_param_ref.As<SemIR::AddrPattern>().inner_id);
  214. prev_param_ref =
  215. context.insts().Get(prev_param_ref.As<SemIR::AddrPattern>().inner_id);
  216. if (new_param_ref.kind() != prev_param_ref.kind()) {
  217. diagnose();
  218. return false;
  219. }
  220. }
  221. if (new_param_ref.Is<SemIR::AnyBindName>()) {
  222. new_param_ref =
  223. context.insts().Get(new_param_ref.As<SemIR::AnyBindName>().value_id);
  224. prev_param_ref =
  225. context.insts().Get(prev_param_ref.As<SemIR::AnyBindName>().value_id);
  226. }
  227. auto new_param = new_param_ref.As<SemIR::Param>();
  228. auto prev_param = prev_param_ref.As<SemIR::Param>();
  229. if (new_param.name_id != prev_param.name_id) {
  230. diagnose();
  231. return false;
  232. }
  233. return true;
  234. }
  235. // Returns false if the param refs differ for a redeclaration.
  236. static auto CheckRedeclParams(Context& context, SemIRLoc new_decl_loc,
  237. SemIR::InstBlockId new_param_refs_id,
  238. SemIRLoc prev_decl_loc,
  239. SemIR::InstBlockId prev_param_refs_id,
  240. llvm::StringLiteral param_diag_label,
  241. SemIR::SpecificId prev_specific_id) -> bool {
  242. // This will often occur for empty params.
  243. if (new_param_refs_id == prev_param_refs_id) {
  244. return true;
  245. }
  246. // If exactly one of the parameter lists was present, they differ.
  247. if (new_param_refs_id.is_valid() != prev_param_refs_id.is_valid()) {
  248. CARBON_DIAGNOSTIC(RedeclParamListDiffers, Error,
  249. "redeclaration differs because of {1}{0}parameter list",
  250. llvm::StringLiteral, llvm::StringLiteral);
  251. CARBON_DIAGNOSTIC(RedeclParamListPrevious, Note,
  252. "previously declared with{1} {0}parameter list",
  253. llvm::StringLiteral, llvm::StringLiteral);
  254. context.emitter()
  255. .Build(
  256. new_decl_loc, RedeclParamListDiffers, param_diag_label,
  257. new_param_refs_id.is_valid() ? llvm::StringLiteral("") : "missing ")
  258. .Note(prev_decl_loc, RedeclParamListPrevious, param_diag_label,
  259. prev_param_refs_id.is_valid() ? llvm::StringLiteral("") : "out")
  260. .Emit();
  261. return false;
  262. }
  263. CARBON_CHECK(new_param_refs_id.is_valid() && prev_param_refs_id.is_valid());
  264. const auto new_param_ref_ids = context.inst_blocks().Get(new_param_refs_id);
  265. const auto prev_param_ref_ids = context.inst_blocks().Get(prev_param_refs_id);
  266. if (new_param_ref_ids.size() != prev_param_ref_ids.size()) {
  267. CARBON_DIAGNOSTIC(
  268. RedeclParamCountDiffers, Error,
  269. "redeclaration differs because of {0}parameter count of {1}",
  270. llvm::StringLiteral, int32_t);
  271. CARBON_DIAGNOSTIC(RedeclParamCountPrevious, Note,
  272. "previously declared with {0}parameter count of {1}",
  273. llvm::StringLiteral, int32_t);
  274. context.emitter()
  275. .Build(new_decl_loc, RedeclParamCountDiffers, param_diag_label,
  276. new_param_ref_ids.size())
  277. .Note(prev_decl_loc, RedeclParamCountPrevious, param_diag_label,
  278. prev_param_ref_ids.size())
  279. .Emit();
  280. return false;
  281. }
  282. for (auto [index, new_param_ref_id, prev_param_ref_id] :
  283. llvm::enumerate(new_param_ref_ids, prev_param_ref_ids)) {
  284. if (!CheckRedeclParam(context, param_diag_label, index, new_param_ref_id,
  285. prev_param_ref_id, prev_specific_id)) {
  286. return false;
  287. }
  288. }
  289. return true;
  290. }
  291. // Returns true if the two nodes represent the same syntax.
  292. // TODO: Detect raw identifiers (will require token changes).
  293. static auto IsNodeSyntaxEqual(Context& context, Parse::NodeId new_node_id,
  294. Parse::NodeId prev_node_id) -> bool {
  295. if (context.parse_tree().node_kind(new_node_id) !=
  296. context.parse_tree().node_kind(prev_node_id)) {
  297. return false;
  298. }
  299. // TODO: Should there be a trivial way to check if we need to check spellings?
  300. // Identifiers and literals need their text checked for cross-file matching,
  301. // but not intra-file. Keywords and operators shouldn't need the token text
  302. // examined at all.
  303. auto new_spelling = context.tokens().GetTokenText(
  304. context.parse_tree().node_token(new_node_id));
  305. auto prev_spelling = context.tokens().GetTokenText(
  306. context.parse_tree().node_token(prev_node_id));
  307. return new_spelling == prev_spelling;
  308. }
  309. // Returns false if redeclaration parameter syntax doesn't match.
  310. static auto CheckRedeclParamSyntax(Context& context,
  311. Parse::NodeId new_first_param_node_id,
  312. Parse::NodeId new_last_param_node_id,
  313. Parse::NodeId prev_first_param_node_id,
  314. Parse::NodeId prev_last_param_node_id)
  315. -> bool {
  316. // Parse nodes may not always be available to compare.
  317. // TODO: Support cross-file syntax checks. Right now imports provide invalid
  318. // nodes, and we'll need to follow the declaration to its original file to
  319. // get the parse tree.
  320. if (!new_first_param_node_id.is_valid() ||
  321. !prev_first_param_node_id.is_valid()) {
  322. return true;
  323. }
  324. CARBON_CHECK(new_last_param_node_id.is_valid(),
  325. "new_last_param_node_id.is_valid should match "
  326. "new_first_param_node_id.is_valid");
  327. CARBON_CHECK(prev_last_param_node_id.is_valid(),
  328. "prev_last_param_node_id.is_valid should match "
  329. "prev_first_param_node_id.is_valid");
  330. auto new_range = Parse::Tree::PostorderIterator::MakeRange(
  331. new_first_param_node_id, new_last_param_node_id);
  332. auto prev_range = Parse::Tree::PostorderIterator::MakeRange(
  333. prev_first_param_node_id, prev_last_param_node_id);
  334. // zip is using the shortest range. If they differ in length, there should be
  335. // some difference inside the range because the range includes parameter
  336. // brackets. As a consequence, we don't explicitly handle different range
  337. // sizes here.
  338. for (auto [new_node_id, prev_node_id] : llvm::zip(new_range, prev_range)) {
  339. if (!IsNodeSyntaxEqual(context, new_node_id, prev_node_id)) {
  340. CARBON_DIAGNOSTIC(RedeclParamSyntaxDiffers, Error,
  341. "redeclaration syntax differs here");
  342. CARBON_DIAGNOSTIC(RedeclParamSyntaxPrevious, Note,
  343. "comparing with previous declaration here");
  344. context.emitter()
  345. .Build(new_node_id, RedeclParamSyntaxDiffers)
  346. .Note(prev_node_id, RedeclParamSyntaxPrevious)
  347. .Emit();
  348. return false;
  349. }
  350. }
  351. return true;
  352. }
  353. auto CheckRedeclParamsMatch(Context& context, const DeclParams& new_entity,
  354. const DeclParams& prev_entity,
  355. SemIR::SpecificId prev_specific_id,
  356. bool check_syntax) -> bool {
  357. if (EntityHasParamError(context, new_entity) ||
  358. EntityHasParamError(context, prev_entity)) {
  359. return false;
  360. }
  361. if (!CheckRedeclParams(context, new_entity.loc,
  362. new_entity.implicit_param_refs_id, prev_entity.loc,
  363. prev_entity.implicit_param_refs_id, "implicit ",
  364. prev_specific_id)) {
  365. return false;
  366. }
  367. if (!CheckRedeclParams(context, new_entity.loc, new_entity.param_refs_id,
  368. prev_entity.loc, prev_entity.param_refs_id, "",
  369. prev_specific_id)) {
  370. return false;
  371. }
  372. if (check_syntax &&
  373. !CheckRedeclParamSyntax(context, new_entity.first_param_node_id,
  374. new_entity.last_param_node_id,
  375. prev_entity.first_param_node_id,
  376. prev_entity.last_param_node_id)) {
  377. return false;
  378. }
  379. return true;
  380. }
  381. } // namespace Carbon::Check