merge.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. // Checks to see if a structurally valid redeclaration is allowed in context.
  84. // These all still merge.
  85. auto CheckIsAllowedRedecl(Context& context, Lex::TokenKind decl_kind,
  86. SemIR::NameId name_id, RedeclInfo new_decl,
  87. RedeclInfo prev_decl, SemIR::ImportIRId import_ir_id)
  88. -> void {
  89. if (!import_ir_id.is_valid()) {
  90. // Check for disallowed redeclarations in the same file.
  91. if (!new_decl.is_definition) {
  92. DiagnoseRedundant(context, decl_kind, name_id, new_decl.loc,
  93. prev_decl.loc);
  94. return;
  95. }
  96. if (prev_decl.is_definition) {
  97. DiagnoseRedef(context, decl_kind, name_id, new_decl.loc, prev_decl.loc);
  98. return;
  99. }
  100. if (prev_decl.is_extern != new_decl.is_extern) {
  101. DiagnoseExternMismatch(context, decl_kind, name_id, new_decl.loc,
  102. prev_decl.loc);
  103. return;
  104. }
  105. return;
  106. }
  107. if (import_ir_id == SemIR::ImportIRId::ApiForImpl) {
  108. // Check for disallowed redeclarations in the same library. Note that a
  109. // forward declaration in the impl is allowed.
  110. if (prev_decl.is_definition) {
  111. if (new_decl.is_definition) {
  112. DiagnoseRedef(context, decl_kind, name_id, new_decl.loc, prev_decl.loc);
  113. } else {
  114. DiagnoseRedundant(context, decl_kind, name_id, new_decl.loc,
  115. prev_decl.loc);
  116. }
  117. return;
  118. }
  119. if (prev_decl.is_extern != new_decl.is_extern) {
  120. DiagnoseExternMismatch(context, decl_kind, name_id, new_decl.loc,
  121. prev_decl.loc);
  122. return;
  123. }
  124. return;
  125. }
  126. // Check for disallowed redeclarations cross-library.
  127. if (new_decl.is_extern && context.IsImplFile()) {
  128. // We continue after issuing the "missing API declaration" diagnostic,
  129. // because it may still be helpful to note other issues with the
  130. // declarations.
  131. DiagnoseExternRequiresDeclInApiFile(context, new_decl.loc);
  132. }
  133. if (prev_decl.is_extern != new_decl.is_extern) {
  134. DiagnoseExternMismatch(context, decl_kind, name_id, new_decl.loc,
  135. prev_decl.loc);
  136. return;
  137. }
  138. if (!prev_decl.extern_library_id.is_valid()) {
  139. if (new_decl.extern_library_id.is_valid()) {
  140. DiagnoseExternLibraryInImporter(context, decl_kind, name_id, new_decl.loc,
  141. prev_decl.loc);
  142. } else {
  143. DiagnoseRedundant(context, decl_kind, name_id, new_decl.loc,
  144. prev_decl.loc);
  145. }
  146. return;
  147. }
  148. if (prev_decl.extern_library_id != SemIR::LibraryNameId::Error &&
  149. prev_decl.extern_library_id != context.sem_ir().library_id()) {
  150. DiagnoseExternLibraryIncorrect(context, new_decl.loc, prev_decl.loc);
  151. return;
  152. }
  153. }
  154. auto ReplacePrevInstForMerge(Context& context, SemIR::NameScopeId scope_id,
  155. SemIR::NameId name_id, SemIR::InstId new_inst_id)
  156. -> void {
  157. auto& scope = context.name_scopes().Get(scope_id);
  158. if (auto lookup = scope.name_map.Lookup(name_id)) {
  159. scope.names[lookup.value()].inst_id = new_inst_id;
  160. }
  161. }
  162. // Returns true if there was an error in declaring the entity, which will have
  163. // previously been diagnosed.
  164. static auto EntityHasParamError(Context& context, const DeclParams& info)
  165. -> bool {
  166. for (auto param_patterns_id :
  167. {info.implicit_param_patterns_id, info.param_patterns_id}) {
  168. if (param_patterns_id.is_valid() &&
  169. param_patterns_id != SemIR::InstBlockId::Empty) {
  170. for (auto param_id : context.inst_blocks().Get(param_patterns_id)) {
  171. if (context.insts().Get(param_id).type_id() == SemIR::TypeId::Error) {
  172. return true;
  173. }
  174. }
  175. }
  176. }
  177. return false;
  178. }
  179. // Returns false if a param differs for a redeclaration. The caller is expected
  180. // to provide a diagnostic.
  181. static auto CheckRedeclParam(Context& context, bool is_implicit_param,
  182. int32_t param_index,
  183. SemIR::InstId new_param_pattern_id,
  184. SemIR::InstId prev_param_pattern_id,
  185. SemIR::SpecificId prev_specific_id, bool diagnose)
  186. -> bool {
  187. // TODO: Consider differentiating between type and name mistakes. For now,
  188. // taking the simpler approach because I also think we may want to refactor
  189. // params.
  190. auto emit_diagnostic = [&]() {
  191. if (!diagnose) {
  192. return;
  193. }
  194. CARBON_DIAGNOSTIC(RedeclParamDiffers, Error,
  195. "redeclaration differs at {0:implicit |}parameter {1}",
  196. BoolAsSelect, int32_t);
  197. CARBON_DIAGNOSTIC(
  198. RedeclParamPrevious, Note,
  199. "previous declaration's corresponding {0:implicit |}parameter here",
  200. BoolAsSelect);
  201. context.emitter()
  202. .Build(new_param_pattern_id, RedeclParamDiffers, is_implicit_param,
  203. param_index + 1)
  204. .Note(prev_param_pattern_id, RedeclParamPrevious, is_implicit_param)
  205. .Emit();
  206. };
  207. auto new_param_pattern = context.insts().Get(new_param_pattern_id);
  208. auto prev_param_pattern = context.insts().Get(prev_param_pattern_id);
  209. if (new_param_pattern.kind() != prev_param_pattern.kind() ||
  210. !context.types().AreEqualAcrossDeclarations(
  211. new_param_pattern.type_id(),
  212. SemIR::GetTypeInSpecific(context.sem_ir(), prev_specific_id,
  213. prev_param_pattern.type_id()))) {
  214. emit_diagnostic();
  215. return false;
  216. }
  217. if (new_param_pattern.Is<SemIR::AddrPattern>()) {
  218. new_param_pattern = context.insts().Get(
  219. new_param_pattern.As<SemIR::AddrPattern>().inner_id);
  220. prev_param_pattern = context.insts().Get(
  221. prev_param_pattern.As<SemIR::AddrPattern>().inner_id);
  222. if (new_param_pattern.kind() != prev_param_pattern.kind()) {
  223. emit_diagnostic();
  224. return false;
  225. }
  226. }
  227. new_param_pattern = context.insts().Get(
  228. new_param_pattern.As<SemIR::ParamPattern>().subpattern_id);
  229. prev_param_pattern = context.insts().Get(
  230. prev_param_pattern.As<SemIR::ParamPattern>().subpattern_id);
  231. if (new_param_pattern.kind() != prev_param_pattern.kind()) {
  232. emit_diagnostic();
  233. return false;
  234. }
  235. auto new_entity_name = context.entity_names().Get(
  236. new_param_pattern.As<SemIR::AnyBindingPattern>().entity_name_id);
  237. auto prev_entity_name = context.entity_names().Get(
  238. prev_param_pattern.As<SemIR::AnyBindingPattern>().entity_name_id);
  239. if (new_entity_name.name_id != prev_entity_name.name_id) {
  240. emit_diagnostic();
  241. return false;
  242. }
  243. return true;
  244. }
  245. // Returns false if the param refs differ for a redeclaration.
  246. static auto CheckRedeclParams(Context& context, SemIRLoc new_decl_loc,
  247. SemIR::InstBlockId new_param_patterns_id,
  248. SemIRLoc prev_decl_loc,
  249. SemIR::InstBlockId prev_param_patterns_id,
  250. bool is_implicit_param,
  251. SemIR::SpecificId prev_specific_id, bool diagnose)
  252. -> bool {
  253. // This will often occur for empty params.
  254. if (new_param_patterns_id == prev_param_patterns_id) {
  255. return true;
  256. }
  257. // If exactly one of the parameter lists was present, they differ.
  258. if (new_param_patterns_id.is_valid() != prev_param_patterns_id.is_valid()) {
  259. if (!diagnose) {
  260. return false;
  261. }
  262. CARBON_DIAGNOSTIC(RedeclParamListDiffers, Error,
  263. "redeclaration differs because of "
  264. "{1:|missing }{0:implicit |}parameter list",
  265. BoolAsSelect, BoolAsSelect);
  266. CARBON_DIAGNOSTIC(RedeclParamListPrevious, Note,
  267. "previously declared "
  268. "{1:with|without} {0:implicit |}parameter list",
  269. BoolAsSelect, BoolAsSelect);
  270. context.emitter()
  271. .Build(new_decl_loc, RedeclParamListDiffers, is_implicit_param,
  272. new_param_patterns_id.is_valid())
  273. .Note(prev_decl_loc, RedeclParamListPrevious, is_implicit_param,
  274. prev_param_patterns_id.is_valid())
  275. .Emit();
  276. return false;
  277. }
  278. CARBON_CHECK(new_param_patterns_id.is_valid() &&
  279. prev_param_patterns_id.is_valid());
  280. const auto new_param_pattern_ids =
  281. context.inst_blocks().Get(new_param_patterns_id);
  282. const auto prev_param_pattern_ids =
  283. context.inst_blocks().Get(prev_param_patterns_id);
  284. if (new_param_pattern_ids.size() != prev_param_pattern_ids.size()) {
  285. if (!diagnose) {
  286. return false;
  287. }
  288. CARBON_DIAGNOSTIC(
  289. RedeclParamCountDiffers, Error,
  290. "redeclaration differs because of {0:implicit |}parameter count of {1}",
  291. BoolAsSelect, int32_t);
  292. CARBON_DIAGNOSTIC(
  293. RedeclParamCountPrevious, Note,
  294. "previously declared with {0:implicit |}parameter count of {1}",
  295. BoolAsSelect, int32_t);
  296. context.emitter()
  297. .Build(new_decl_loc, RedeclParamCountDiffers, is_implicit_param,
  298. new_param_pattern_ids.size())
  299. .Note(prev_decl_loc, RedeclParamCountPrevious, is_implicit_param,
  300. prev_param_pattern_ids.size())
  301. .Emit();
  302. return false;
  303. }
  304. for (auto [index, new_param_pattern_id, prev_param_pattern_id] :
  305. llvm::enumerate(new_param_pattern_ids, prev_param_pattern_ids)) {
  306. if (!CheckRedeclParam(context, is_implicit_param, index,
  307. new_param_pattern_id, prev_param_pattern_id,
  308. prev_specific_id, diagnose)) {
  309. return false;
  310. }
  311. }
  312. return true;
  313. }
  314. // Returns true if the two nodes represent the same syntax.
  315. // TODO: Detect raw identifiers (will require token changes).
  316. static auto IsNodeSyntaxEqual(Context& context, Parse::NodeId new_node_id,
  317. Parse::NodeId prev_node_id) -> bool {
  318. if (context.parse_tree().node_kind(new_node_id) !=
  319. context.parse_tree().node_kind(prev_node_id)) {
  320. return false;
  321. }
  322. // TODO: Should there be a trivial way to check if we need to check spellings?
  323. // Identifiers and literals need their text checked for cross-file matching,
  324. // but not intra-file. Keywords and operators shouldn't need the token text
  325. // examined at all.
  326. auto new_spelling = context.tokens().GetTokenText(
  327. context.parse_tree().node_token(new_node_id));
  328. auto prev_spelling = context.tokens().GetTokenText(
  329. context.parse_tree().node_token(prev_node_id));
  330. return new_spelling == prev_spelling;
  331. }
  332. // Returns false if redeclaration parameter syntax doesn't match.
  333. static auto CheckRedeclParamSyntax(Context& context,
  334. Parse::NodeId new_first_param_node_id,
  335. Parse::NodeId new_last_param_node_id,
  336. Parse::NodeId prev_first_param_node_id,
  337. Parse::NodeId prev_last_param_node_id,
  338. bool diagnose) -> bool {
  339. // Parse nodes may not always be available to compare.
  340. // TODO: Support cross-file syntax checks. Right now imports provide invalid
  341. // nodes, and we'll need to follow the declaration to its original file to
  342. // get the parse tree.
  343. if (!new_first_param_node_id.is_valid() ||
  344. !prev_first_param_node_id.is_valid()) {
  345. return true;
  346. }
  347. CARBON_CHECK(new_last_param_node_id.is_valid(),
  348. "new_last_param_node_id.is_valid should match "
  349. "new_first_param_node_id.is_valid");
  350. CARBON_CHECK(prev_last_param_node_id.is_valid(),
  351. "prev_last_param_node_id.is_valid should match "
  352. "prev_first_param_node_id.is_valid");
  353. auto new_range = Parse::Tree::PostorderIterator::MakeRange(
  354. new_first_param_node_id, new_last_param_node_id);
  355. auto prev_range = Parse::Tree::PostorderIterator::MakeRange(
  356. prev_first_param_node_id, prev_last_param_node_id);
  357. // zip is using the shortest range. If they differ in length, there should be
  358. // some difference inside the range because the range includes parameter
  359. // brackets. As a consequence, we don't explicitly handle different range
  360. // sizes here.
  361. for (auto [new_node_id, prev_node_id] : llvm::zip(new_range, prev_range)) {
  362. if (!IsNodeSyntaxEqual(context, new_node_id, prev_node_id)) {
  363. if (!diagnose) {
  364. return false;
  365. }
  366. CARBON_DIAGNOSTIC(RedeclParamSyntaxDiffers, Error,
  367. "redeclaration syntax differs here");
  368. CARBON_DIAGNOSTIC(RedeclParamSyntaxPrevious, Note,
  369. "comparing with previous declaration here");
  370. context.emitter()
  371. .Build(new_node_id, RedeclParamSyntaxDiffers)
  372. .Note(prev_node_id, RedeclParamSyntaxPrevious)
  373. .Emit();
  374. return false;
  375. }
  376. }
  377. return true;
  378. }
  379. auto CheckRedeclParamsMatch(Context& context, const DeclParams& new_entity,
  380. const DeclParams& prev_entity,
  381. SemIR::SpecificId prev_specific_id,
  382. bool check_syntax, bool diagnose) -> bool {
  383. if (EntityHasParamError(context, new_entity) ||
  384. EntityHasParamError(context, prev_entity)) {
  385. return false;
  386. }
  387. if (!CheckRedeclParams(
  388. context, new_entity.loc, new_entity.implicit_param_patterns_id,
  389. prev_entity.loc, prev_entity.implicit_param_patterns_id,
  390. /*is_implicit_param=*/true, prev_specific_id, diagnose)) {
  391. return false;
  392. }
  393. if (!CheckRedeclParams(context, new_entity.loc, new_entity.param_patterns_id,
  394. prev_entity.loc, prev_entity.param_patterns_id,
  395. /*is_implicit_param=*/false, prev_specific_id,
  396. diagnose)) {
  397. return false;
  398. }
  399. if (check_syntax &&
  400. !CheckRedeclParamSyntax(context, new_entity.first_param_node_id,
  401. new_entity.last_param_node_id,
  402. prev_entity.first_param_node_id,
  403. prev_entity.last_param_node_id, diagnose)) {
  404. return false;
  405. }
  406. return true;
  407. }
  408. } // namespace Carbon::Check