merge.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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/diagnostics/format_providers.h"
  8. #include "toolchain/sem_ir/ids.h"
  9. #include "toolchain/sem_ir/typed_insts.h"
  10. namespace Carbon::Check {
  11. CARBON_DIAGNOSTIC(RedeclPrevDecl, Note, "previously declared here");
  12. // Diagnoses a redeclaration which is redundant.
  13. static auto DiagnoseRedundant(Context& context, Lex::TokenKind decl_kind,
  14. SemIR::NameId name_id, SemIRLoc new_loc,
  15. SemIRLoc prev_loc) -> void {
  16. CARBON_DIAGNOSTIC(RedeclRedundant, Error,
  17. "redeclaration of `{0} {1}` is redundant", Lex::TokenKind,
  18. SemIR::NameId);
  19. context.emitter()
  20. .Build(new_loc, RedeclRedundant, decl_kind, name_id)
  21. .Note(prev_loc, RedeclPrevDecl)
  22. .Emit();
  23. }
  24. // Diagnoses a redefinition.
  25. static auto DiagnoseRedef(Context& context, Lex::TokenKind decl_kind,
  26. SemIR::NameId name_id, SemIRLoc new_loc,
  27. SemIRLoc prev_loc) -> void {
  28. CARBON_DIAGNOSTIC(RedeclRedef, Error, "redefinition of `{0} {1}`",
  29. Lex::TokenKind, SemIR::NameId);
  30. CARBON_DIAGNOSTIC(RedeclPrevDef, Note, "previously defined here");
  31. context.emitter()
  32. .Build(new_loc, RedeclRedef, decl_kind, name_id)
  33. .Note(prev_loc, RedeclPrevDef)
  34. .Emit();
  35. }
  36. // Diagnoses an `extern` versus non-`extern` mismatch.
  37. static auto DiagnoseExternMismatch(Context& context, Lex::TokenKind decl_kind,
  38. SemIR::NameId name_id, SemIRLoc new_loc,
  39. SemIRLoc prev_loc) -> void {
  40. CARBON_DIAGNOSTIC(RedeclExternMismatch, Error,
  41. "redeclarations of `{0} {1}` must match use of `extern`",
  42. Lex::TokenKind, SemIR::NameId);
  43. context.emitter()
  44. .Build(new_loc, RedeclExternMismatch, decl_kind, name_id)
  45. .Note(prev_loc, RedeclPrevDecl)
  46. .Emit();
  47. }
  48. // Diagnoses `extern library` declared in a library importing the owned entity.
  49. static auto DiagnoseExternLibraryInImporter(Context& context,
  50. Lex::TokenKind decl_kind,
  51. SemIR::NameId name_id,
  52. SemIRLoc new_loc, SemIRLoc prev_loc)
  53. -> void {
  54. CARBON_DIAGNOSTIC(ExternLibraryInImporter, Error,
  55. "cannot declare imported `{0} {1}` as `extern library`",
  56. Lex::TokenKind, SemIR::NameId);
  57. context.emitter()
  58. .Build(new_loc, ExternLibraryInImporter, decl_kind, name_id)
  59. .Note(prev_loc, RedeclPrevDecl)
  60. .Emit();
  61. }
  62. // Diagnoses `extern library` pointing to the wrong library.
  63. static auto DiagnoseExternLibraryIncorrect(Context& context, SemIRLoc new_loc,
  64. SemIRLoc prev_loc) -> void {
  65. CARBON_DIAGNOSTIC(
  66. ExternLibraryIncorrect, Error,
  67. "declaration in {0} doesn't match `extern library` declaration",
  68. SemIR::LibraryNameId);
  69. CARBON_DIAGNOSTIC(ExternLibraryExpected, Note,
  70. "previously declared with `extern library` here");
  71. context.emitter()
  72. .Build(new_loc, ExternLibraryIncorrect, context.sem_ir().library_id())
  73. .Note(prev_loc, ExternLibraryExpected)
  74. .Emit();
  75. }
  76. auto DiagnoseExternRequiresDeclInApiFile(Context& context, SemIRLoc loc)
  77. -> void {
  78. CARBON_DIAGNOSTIC(
  79. ExternRequiresDeclInApiFile, Error,
  80. "`extern` entities must have a declaration in the API file");
  81. context.emitter().Build(loc, ExternRequiresDeclInApiFile).Emit();
  82. }
  83. auto DiagnoseIfInvalidRedecl(Context& context, Lex::TokenKind decl_kind,
  84. SemIR::NameId name_id, RedeclInfo new_decl,
  85. RedeclInfo prev_decl,
  86. SemIR::ImportIRId import_ir_id) -> void {
  87. if (!import_ir_id.has_value()) {
  88. // Check for disallowed redeclarations in the same file.
  89. if (!new_decl.is_definition) {
  90. DiagnoseRedundant(context, decl_kind, name_id, new_decl.loc,
  91. prev_decl.loc);
  92. return;
  93. }
  94. if (prev_decl.is_definition) {
  95. DiagnoseRedef(context, decl_kind, name_id, new_decl.loc, prev_decl.loc);
  96. return;
  97. }
  98. if (prev_decl.is_extern != new_decl.is_extern) {
  99. DiagnoseExternMismatch(context, decl_kind, name_id, new_decl.loc,
  100. prev_decl.loc);
  101. return;
  102. }
  103. return;
  104. }
  105. if (import_ir_id == SemIR::ImportIRId::ApiForImpl) {
  106. // Check for disallowed redeclarations in the same library. Note that a
  107. // forward declaration in the impl is allowed.
  108. if (prev_decl.is_definition) {
  109. if (new_decl.is_definition) {
  110. DiagnoseRedef(context, decl_kind, name_id, new_decl.loc, prev_decl.loc);
  111. } else {
  112. DiagnoseRedundant(context, decl_kind, name_id, new_decl.loc,
  113. prev_decl.loc);
  114. }
  115. return;
  116. }
  117. if (prev_decl.is_extern != new_decl.is_extern) {
  118. DiagnoseExternMismatch(context, decl_kind, name_id, new_decl.loc,
  119. prev_decl.loc);
  120. return;
  121. }
  122. return;
  123. }
  124. // Check for disallowed redeclarations cross-library.
  125. if (new_decl.is_extern && context.IsImplFile()) {
  126. // We continue after issuing the "missing API declaration" diagnostic,
  127. // because it may still be helpful to note other issues with the
  128. // declarations.
  129. DiagnoseExternRequiresDeclInApiFile(context, new_decl.loc);
  130. }
  131. if (prev_decl.is_extern != new_decl.is_extern) {
  132. DiagnoseExternMismatch(context, decl_kind, name_id, new_decl.loc,
  133. prev_decl.loc);
  134. return;
  135. }
  136. if (!prev_decl.extern_library_id.has_value()) {
  137. if (new_decl.extern_library_id.has_value()) {
  138. DiagnoseExternLibraryInImporter(context, decl_kind, name_id, new_decl.loc,
  139. prev_decl.loc);
  140. } else {
  141. DiagnoseRedundant(context, decl_kind, name_id, new_decl.loc,
  142. prev_decl.loc);
  143. }
  144. return;
  145. }
  146. if (prev_decl.extern_library_id != SemIR::LibraryNameId::Error &&
  147. prev_decl.extern_library_id != context.sem_ir().library_id()) {
  148. DiagnoseExternLibraryIncorrect(context, new_decl.loc, prev_decl.loc);
  149. return;
  150. }
  151. }
  152. auto ReplacePrevInstForMerge(Context& context, SemIR::NameScopeId scope_id,
  153. SemIR::NameId name_id, SemIR::InstId new_inst_id)
  154. -> void {
  155. auto& scope = context.name_scopes().Get(scope_id);
  156. auto entry_id = scope.Lookup(name_id);
  157. if (entry_id) {
  158. auto& result = scope.GetEntry(*entry_id).result;
  159. result = SemIR::ScopeLookupResult::MakeWrappedLookupResult(
  160. new_inst_id, result.access_kind());
  161. }
  162. }
  163. // Returns true if there was an error in declaring the entity, which will have
  164. // previously been diagnosed.
  165. static auto EntityHasParamError(Context& context, const DeclParams& info)
  166. -> bool {
  167. for (auto param_patterns_id :
  168. {info.implicit_param_patterns_id, info.param_patterns_id}) {
  169. if (param_patterns_id.has_value() &&
  170. param_patterns_id != SemIR::InstBlockId::Empty) {
  171. for (auto param_id : context.inst_blocks().Get(param_patterns_id)) {
  172. if (context.insts().Get(param_id).type_id() ==
  173. SemIR::ErrorInst::SingletonTypeId) {
  174. return true;
  175. }
  176. }
  177. }
  178. }
  179. return false;
  180. }
  181. // Returns false if a param differs for a redeclaration. The caller is expected
  182. // to provide a diagnostic.
  183. static auto CheckRedeclParam(Context& context, bool is_implicit_param,
  184. int32_t param_index,
  185. SemIR::InstId new_param_pattern_id,
  186. SemIR::InstId prev_param_pattern_id,
  187. SemIR::SpecificId prev_specific_id, bool diagnose)
  188. -> bool {
  189. // TODO: Consider differentiating between type and name mistakes. For now,
  190. // taking the simpler approach because I also think we may want to refactor
  191. // params.
  192. CARBON_DIAGNOSTIC(
  193. RedeclParamPrevious, Note,
  194. "previous declaration's corresponding {0:implicit |}parameter here",
  195. BoolAsSelect);
  196. auto emit_diagnostic = [&]() {
  197. if (!diagnose) {
  198. return;
  199. }
  200. CARBON_DIAGNOSTIC(RedeclParamDiffers, Error,
  201. "redeclaration differs at {0:implicit |}parameter {1}",
  202. BoolAsSelect, int32_t);
  203. context.emitter()
  204. .Build(new_param_pattern_id, RedeclParamDiffers, is_implicit_param,
  205. param_index + 1)
  206. .Note(prev_param_pattern_id, RedeclParamPrevious, is_implicit_param)
  207. .Emit();
  208. };
  209. auto new_param_pattern = context.insts().Get(new_param_pattern_id);
  210. auto prev_param_pattern = context.insts().Get(prev_param_pattern_id);
  211. if (new_param_pattern.kind() != prev_param_pattern.kind()) {
  212. emit_diagnostic();
  213. return false;
  214. }
  215. auto prev_param_type_id = SemIR::GetTypeInSpecific(
  216. context.sem_ir(), prev_specific_id, prev_param_pattern.type_id());
  217. if (!context.types().AreEqualAcrossDeclarations(new_param_pattern.type_id(),
  218. prev_param_type_id)) {
  219. if (!diagnose) {
  220. return false;
  221. }
  222. CARBON_DIAGNOSTIC(RedeclParamDiffersType, Error,
  223. "type {3} of {0:implicit |}parameter {1} in "
  224. "redeclaration differs from previous parameter type {2}",
  225. BoolAsSelect, int32_t, SemIR::TypeId, SemIR::TypeId);
  226. context.emitter()
  227. .Build(new_param_pattern_id, RedeclParamDiffersType, is_implicit_param,
  228. param_index + 1, prev_param_type_id, new_param_pattern.type_id())
  229. .Note(prev_param_pattern_id, RedeclParamPrevious, is_implicit_param)
  230. .Emit();
  231. return false;
  232. }
  233. if (new_param_pattern.Is<SemIR::AddrPattern>()) {
  234. new_param_pattern = context.insts().Get(
  235. new_param_pattern.As<SemIR::AddrPattern>().inner_id);
  236. prev_param_pattern = context.insts().Get(
  237. prev_param_pattern.As<SemIR::AddrPattern>().inner_id);
  238. if (new_param_pattern.kind() != prev_param_pattern.kind()) {
  239. emit_diagnostic();
  240. return false;
  241. }
  242. }
  243. new_param_pattern = context.insts().Get(
  244. new_param_pattern.As<SemIR::ValueParamPattern>().subpattern_id);
  245. prev_param_pattern = context.insts().Get(
  246. prev_param_pattern.As<SemIR::ValueParamPattern>().subpattern_id);
  247. if (new_param_pattern.kind() != prev_param_pattern.kind()) {
  248. emit_diagnostic();
  249. return false;
  250. }
  251. auto new_entity_name = context.entity_names().Get(
  252. new_param_pattern.As<SemIR::AnyBindingPattern>().entity_name_id);
  253. auto prev_entity_name = context.entity_names().Get(
  254. prev_param_pattern.As<SemIR::AnyBindingPattern>().entity_name_id);
  255. if (new_entity_name.name_id != prev_entity_name.name_id) {
  256. emit_diagnostic();
  257. return false;
  258. }
  259. return true;
  260. }
  261. // Returns false if the param refs differ for a redeclaration.
  262. static auto CheckRedeclParams(Context& context, SemIRLoc new_decl_loc,
  263. SemIR::InstBlockId new_param_patterns_id,
  264. SemIRLoc prev_decl_loc,
  265. SemIR::InstBlockId prev_param_patterns_id,
  266. bool is_implicit_param,
  267. SemIR::SpecificId prev_specific_id, bool diagnose)
  268. -> bool {
  269. // This will often occur for empty params.
  270. if (new_param_patterns_id == prev_param_patterns_id) {
  271. return true;
  272. }
  273. // If exactly one of the parameter lists was present, they differ.
  274. if (new_param_patterns_id.has_value() != prev_param_patterns_id.has_value()) {
  275. if (!diagnose) {
  276. return false;
  277. }
  278. CARBON_DIAGNOSTIC(RedeclParamListDiffers, Error,
  279. "redeclaration differs because of "
  280. "{1:|missing }{0:implicit |}parameter list",
  281. BoolAsSelect, BoolAsSelect);
  282. CARBON_DIAGNOSTIC(RedeclParamListPrevious, Note,
  283. "previously declared "
  284. "{1:with|without} {0:implicit |}parameter list",
  285. BoolAsSelect, BoolAsSelect);
  286. context.emitter()
  287. .Build(new_decl_loc, RedeclParamListDiffers, is_implicit_param,
  288. new_param_patterns_id.has_value())
  289. .Note(prev_decl_loc, RedeclParamListPrevious, is_implicit_param,
  290. prev_param_patterns_id.has_value())
  291. .Emit();
  292. return false;
  293. }
  294. CARBON_CHECK(new_param_patterns_id.has_value() &&
  295. prev_param_patterns_id.has_value());
  296. const auto new_param_pattern_ids =
  297. context.inst_blocks().Get(new_param_patterns_id);
  298. const auto prev_param_pattern_ids =
  299. context.inst_blocks().Get(prev_param_patterns_id);
  300. if (new_param_pattern_ids.size() != prev_param_pattern_ids.size()) {
  301. if (!diagnose) {
  302. return false;
  303. }
  304. CARBON_DIAGNOSTIC(
  305. RedeclParamCountDiffers, Error,
  306. "redeclaration differs because of {0:implicit |}parameter count of {1}",
  307. BoolAsSelect, int32_t);
  308. CARBON_DIAGNOSTIC(
  309. RedeclParamCountPrevious, Note,
  310. "previously declared with {0:implicit |}parameter count of {1}",
  311. BoolAsSelect, int32_t);
  312. context.emitter()
  313. .Build(new_decl_loc, RedeclParamCountDiffers, is_implicit_param,
  314. new_param_pattern_ids.size())
  315. .Note(prev_decl_loc, RedeclParamCountPrevious, is_implicit_param,
  316. prev_param_pattern_ids.size())
  317. .Emit();
  318. return false;
  319. }
  320. for (auto [index, new_param_pattern_id, prev_param_pattern_id] :
  321. llvm::enumerate(new_param_pattern_ids, prev_param_pattern_ids)) {
  322. if (!CheckRedeclParam(context, is_implicit_param, index,
  323. new_param_pattern_id, prev_param_pattern_id,
  324. prev_specific_id, diagnose)) {
  325. return false;
  326. }
  327. }
  328. return true;
  329. }
  330. // Returns true if the two nodes represent the same syntax.
  331. // TODO: Detect raw identifiers (will require token changes).
  332. static auto IsNodeSyntaxEqual(Context& context, Parse::NodeId new_node_id,
  333. Parse::NodeId prev_node_id) -> bool {
  334. if (context.parse_tree().node_kind(new_node_id) !=
  335. context.parse_tree().node_kind(prev_node_id)) {
  336. return false;
  337. }
  338. // TODO: Should there be a trivial way to check if we need to check spellings?
  339. // Identifiers and literals need their text checked for cross-file matching,
  340. // but not intra-file. Keywords and operators shouldn't need the token text
  341. // examined at all.
  342. auto new_spelling = context.tokens().GetTokenText(
  343. context.parse_tree().node_token(new_node_id));
  344. auto prev_spelling = context.tokens().GetTokenText(
  345. context.parse_tree().node_token(prev_node_id));
  346. return new_spelling == prev_spelling;
  347. }
  348. // Returns false if redeclaration parameter syntax doesn't match.
  349. static auto CheckRedeclParamSyntax(Context& context,
  350. Parse::NodeId new_first_param_node_id,
  351. Parse::NodeId new_last_param_node_id,
  352. Parse::NodeId prev_first_param_node_id,
  353. Parse::NodeId prev_last_param_node_id,
  354. bool diagnose) -> bool {
  355. // Parse nodes may not always be available to compare.
  356. // TODO: Support cross-file syntax checks. Right now imports provide
  357. // `NodeId::None`, and we'll need to follow the declaration to its original
  358. // file to get the parse tree.
  359. if (!new_first_param_node_id.has_value() ||
  360. !prev_first_param_node_id.has_value()) {
  361. return true;
  362. }
  363. CARBON_CHECK(new_last_param_node_id.has_value(),
  364. "new_last_param_node_id.has_value should match "
  365. "new_first_param_node_id.has_value");
  366. CARBON_CHECK(prev_last_param_node_id.has_value(),
  367. "prev_last_param_node_id.has_value should match "
  368. "prev_first_param_node_id.has_value");
  369. Parse::Tree::PostorderIterator new_iter(new_first_param_node_id);
  370. Parse::Tree::PostorderIterator new_end(new_last_param_node_id);
  371. Parse::Tree::PostorderIterator prev_iter(prev_first_param_node_id);
  372. Parse::Tree::PostorderIterator prev_end(prev_last_param_node_id);
  373. // Done when one past the last node to check.
  374. ++new_end;
  375. ++prev_end;
  376. // Compare up to the shortest length.
  377. for (; new_iter != new_end && prev_iter != prev_end;
  378. ++new_iter, ++prev_iter) {
  379. auto new_node_id = *new_iter;
  380. auto prev_node_id = *prev_iter;
  381. if (!IsNodeSyntaxEqual(context, new_node_id, prev_node_id)) {
  382. // Skip difference if it is `Self as` vs. `as` in an `impl` declaration.
  383. // https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p3763.md#redeclarations
  384. auto new_node_kind = context.parse_tree().node_kind(new_node_id);
  385. auto prev_node_kind = context.parse_tree().node_kind(prev_node_id);
  386. if (new_node_kind == Parse::NodeKind::DefaultSelfImplAs &&
  387. prev_node_kind == Parse::NodeKind::SelfTypeNameExpr &&
  388. context.parse_tree().node_kind(prev_iter[1]) ==
  389. Parse::NodeKind::TypeImplAs) {
  390. ++prev_iter;
  391. continue;
  392. }
  393. if (prev_node_kind == Parse::NodeKind::DefaultSelfImplAs &&
  394. new_node_kind == Parse::NodeKind::SelfTypeNameExpr &&
  395. context.parse_tree().node_kind(new_iter[1]) ==
  396. Parse::NodeKind::TypeImplAs) {
  397. ++new_iter;
  398. continue;
  399. }
  400. if (!diagnose) {
  401. return false;
  402. }
  403. CARBON_DIAGNOSTIC(RedeclParamSyntaxDiffers, Error,
  404. "redeclaration syntax differs here");
  405. CARBON_DIAGNOSTIC(RedeclParamSyntaxPrevious, Note,
  406. "comparing with previous declaration here");
  407. context.emitter()
  408. .Build(new_node_id, RedeclParamSyntaxDiffers)
  409. .Note(prev_node_id, RedeclParamSyntaxPrevious)
  410. .Emit();
  411. return false;
  412. }
  413. }
  414. // The prefixes are the same, but the lengths may still be different. This is
  415. // only relevant for `impl` declarations where the final bracketing node is
  416. // not included in the range of nodes being compared, and in those cases
  417. // `diagnose` is false.
  418. if (new_iter != new_end) {
  419. CARBON_CHECK(!diagnose);
  420. return false;
  421. } else if (prev_iter != prev_end) {
  422. CARBON_CHECK(!diagnose);
  423. return false;
  424. }
  425. return true;
  426. }
  427. auto CheckRedeclParamsMatch(Context& context, const DeclParams& new_entity,
  428. const DeclParams& prev_entity,
  429. SemIR::SpecificId prev_specific_id,
  430. bool check_syntax, bool diagnose) -> bool {
  431. if (EntityHasParamError(context, new_entity) ||
  432. EntityHasParamError(context, prev_entity)) {
  433. return false;
  434. }
  435. if (!CheckRedeclParams(
  436. context, new_entity.loc, new_entity.implicit_param_patterns_id,
  437. prev_entity.loc, prev_entity.implicit_param_patterns_id,
  438. /*is_implicit_param=*/true, prev_specific_id, diagnose)) {
  439. return false;
  440. }
  441. if (!CheckRedeclParams(context, new_entity.loc, new_entity.param_patterns_id,
  442. prev_entity.loc, prev_entity.param_patterns_id,
  443. /*is_implicit_param=*/false, prev_specific_id,
  444. diagnose)) {
  445. return false;
  446. }
  447. if (check_syntax &&
  448. !CheckRedeclParamSyntax(context, new_entity.first_param_node_id,
  449. new_entity.last_param_node_id,
  450. prev_entity.first_param_node_id,
  451. prev_entity.last_param_node_id, diagnose)) {
  452. return false;
  453. }
  454. return true;
  455. }
  456. } // namespace Carbon::Check