merge.cpp 20 KB

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