merge.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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) {
  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) {
  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) {
  39. CARBON_DIAGNOSTIC(RedeclExternMismatch, Error,
  40. "Redeclarations of `{0} {1}` in the same library must "
  41. "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 when multiple non-`extern` declarations are found.
  49. static auto DiagnoseNonExtern(Context& context, Lex::TokenKind decl_kind,
  50. SemIR::NameId name_id, SemIRLoc new_loc,
  51. SemIRLoc prev_loc) {
  52. CARBON_DIAGNOSTIC(RedeclNonExtern, Error,
  53. "Only one library can declare `{0} {1}` without `extern`.",
  54. Lex::TokenKind, SemIR::NameId);
  55. context.emitter()
  56. .Build(new_loc, RedeclNonExtern, decl_kind, name_id)
  57. .Note(prev_loc, RedeclPrevDecl)
  58. .Emit();
  59. }
  60. // Checks to see if a structurally valid redeclaration is allowed in context.
  61. // These all still merge.
  62. auto CheckIsAllowedRedecl(Context& context, Lex::TokenKind decl_kind,
  63. SemIR::NameId name_id, RedeclInfo new_decl,
  64. RedeclInfo prev_decl, SemIR::ImportIRId import_ir_id)
  65. -> void {
  66. if (!import_ir_id.is_valid()) {
  67. // Check for disallowed redeclarations in the same file.
  68. if (!new_decl.is_definition) {
  69. DiagnoseRedundant(context, decl_kind, name_id, new_decl.loc,
  70. prev_decl.loc);
  71. return;
  72. }
  73. if (prev_decl.is_definition) {
  74. DiagnoseRedef(context, decl_kind, name_id, new_decl.loc, prev_decl.loc);
  75. return;
  76. }
  77. // `extern` definitions are prevented at creation; this is only
  78. // checking for a non-`extern` definition after an `extern` declaration.
  79. if (prev_decl.is_extern) {
  80. DiagnoseExternMismatch(context, decl_kind, name_id, new_decl.loc,
  81. prev_decl.loc);
  82. return;
  83. }
  84. return;
  85. }
  86. if (import_ir_id == SemIR::ImportIRId::ApiForImpl) {
  87. // Check for disallowed redeclarations in the same library. Note that a
  88. // forward declaration in the impl is allowed.
  89. if (prev_decl.is_definition) {
  90. if (new_decl.is_definition) {
  91. DiagnoseRedef(context, decl_kind, name_id, new_decl.loc, prev_decl.loc);
  92. } else {
  93. DiagnoseRedundant(context, decl_kind, name_id, new_decl.loc,
  94. prev_decl.loc);
  95. }
  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. // Check for disallowed redeclarations cross-library.
  106. if (!new_decl.is_extern && !prev_decl.is_extern) {
  107. DiagnoseNonExtern(context, decl_kind, name_id, new_decl.loc, prev_decl.loc);
  108. return;
  109. }
  110. }
  111. auto ReplacePrevInstForMerge(Context& context, SemIR::NameScopeId scope_id,
  112. SemIR::NameId name_id, SemIR::InstId new_inst_id)
  113. -> void {
  114. auto& scope = context.name_scopes().Get(scope_id);
  115. if (auto lookup = scope.name_map.Lookup(name_id)) {
  116. scope.names[lookup.value()].inst_id = new_inst_id;
  117. }
  118. }
  119. // Returns true if there was an error in declaring the entity, which will have
  120. // previously been diagnosed.
  121. static auto EntityHasParamError(Context& context, const DeclParams& info)
  122. -> bool {
  123. for (auto param_refs_id : {info.implicit_param_refs_id, info.param_refs_id}) {
  124. if (param_refs_id.is_valid() &&
  125. param_refs_id != SemIR::InstBlockId::Empty) {
  126. for (auto param_id : context.inst_blocks().Get(param_refs_id)) {
  127. if (context.insts().Get(param_id).type_id() == SemIR::TypeId::Error) {
  128. return true;
  129. }
  130. }
  131. }
  132. }
  133. return false;
  134. }
  135. // Returns false if a param differs for a redeclaration. The caller is expected
  136. // to provide a diagnostic.
  137. static auto CheckRedeclParam(Context& context,
  138. llvm::StringLiteral param_diag_label,
  139. int32_t param_index,
  140. SemIR::InstId new_param_ref_id,
  141. SemIR::InstId prev_param_ref_id,
  142. SemIR::SpecificId prev_specific_id) -> bool {
  143. // TODO: Consider differentiating between type and name mistakes. For now,
  144. // taking the simpler approach because I also think we may want to refactor
  145. // params.
  146. auto diagnose = [&]() {
  147. CARBON_DIAGNOSTIC(RedeclParamDiffers, Error,
  148. "Redeclaration differs at {0}parameter {1}.",
  149. llvm::StringLiteral, int32_t);
  150. CARBON_DIAGNOSTIC(RedeclParamPrevious, Note,
  151. "Previous declaration's corresponding {0}parameter here.",
  152. llvm::StringLiteral);
  153. context.emitter()
  154. .Build(new_param_ref_id, RedeclParamDiffers, param_diag_label,
  155. param_index + 1)
  156. .Note(prev_param_ref_id, RedeclParamPrevious, param_diag_label)
  157. .Emit();
  158. };
  159. auto new_param_ref = context.insts().Get(new_param_ref_id);
  160. auto prev_param_ref = context.insts().Get(prev_param_ref_id);
  161. if (new_param_ref.kind() != prev_param_ref.kind() ||
  162. !context.types().AreEqualAcrossDeclarations(
  163. new_param_ref.type_id(),
  164. SemIR::GetTypeInSpecific(context.sem_ir(), prev_specific_id,
  165. prev_param_ref.type_id()))) {
  166. diagnose();
  167. return false;
  168. }
  169. if (new_param_ref.Is<SemIR::AddrPattern>()) {
  170. new_param_ref =
  171. context.insts().Get(new_param_ref.As<SemIR::AddrPattern>().inner_id);
  172. prev_param_ref =
  173. context.insts().Get(prev_param_ref.As<SemIR::AddrPattern>().inner_id);
  174. if (new_param_ref.kind() != prev_param_ref.kind()) {
  175. diagnose();
  176. return false;
  177. }
  178. }
  179. if (new_param_ref.Is<SemIR::AnyBindName>()) {
  180. new_param_ref =
  181. context.insts().Get(new_param_ref.As<SemIR::AnyBindName>().value_id);
  182. prev_param_ref =
  183. context.insts().Get(prev_param_ref.As<SemIR::AnyBindName>().value_id);
  184. }
  185. auto new_param = new_param_ref.As<SemIR::Param>();
  186. auto prev_param = prev_param_ref.As<SemIR::Param>();
  187. if (new_param.name_id != prev_param.name_id) {
  188. diagnose();
  189. return false;
  190. }
  191. return true;
  192. }
  193. // Returns false if the param refs differ for a redeclaration.
  194. static auto CheckRedeclParams(Context& context, SemIRLoc new_decl_loc,
  195. SemIR::InstBlockId new_param_refs_id,
  196. SemIRLoc prev_decl_loc,
  197. SemIR::InstBlockId prev_param_refs_id,
  198. llvm::StringLiteral param_diag_label,
  199. SemIR::SpecificId prev_specific_id) -> bool {
  200. // This will often occur for empty params.
  201. if (new_param_refs_id == prev_param_refs_id) {
  202. return true;
  203. }
  204. // If exactly one of the parameter lists was present, they differ.
  205. if (new_param_refs_id.is_valid() != prev_param_refs_id.is_valid()) {
  206. CARBON_DIAGNOSTIC(RedeclParamListDiffers, Error,
  207. "Redeclaration differs because of {1}{0}parameter list.",
  208. llvm::StringLiteral, llvm::StringLiteral);
  209. CARBON_DIAGNOSTIC(RedeclParamListPrevious, Note,
  210. "Previously declared with{1} {0}parameter list.",
  211. llvm::StringLiteral, llvm::StringLiteral);
  212. context.emitter()
  213. .Build(
  214. new_decl_loc, RedeclParamListDiffers, param_diag_label,
  215. new_param_refs_id.is_valid() ? llvm::StringLiteral("") : "missing ")
  216. .Note(prev_decl_loc, RedeclParamListPrevious, param_diag_label,
  217. prev_param_refs_id.is_valid() ? llvm::StringLiteral("") : "out")
  218. .Emit();
  219. return false;
  220. }
  221. CARBON_CHECK(new_param_refs_id.is_valid() && prev_param_refs_id.is_valid());
  222. const auto new_param_ref_ids = context.inst_blocks().Get(new_param_refs_id);
  223. const auto prev_param_ref_ids = context.inst_blocks().Get(prev_param_refs_id);
  224. if (new_param_ref_ids.size() != prev_param_ref_ids.size()) {
  225. CARBON_DIAGNOSTIC(
  226. RedeclParamCountDiffers, Error,
  227. "Redeclaration differs because of {0}parameter count of {1}.",
  228. llvm::StringLiteral, int32_t);
  229. CARBON_DIAGNOSTIC(RedeclParamCountPrevious, Note,
  230. "Previously declared with {0}parameter count of {1}.",
  231. llvm::StringLiteral, int32_t);
  232. context.emitter()
  233. .Build(new_decl_loc, RedeclParamCountDiffers, param_diag_label,
  234. new_param_ref_ids.size())
  235. .Note(prev_decl_loc, RedeclParamCountPrevious, param_diag_label,
  236. prev_param_ref_ids.size())
  237. .Emit();
  238. return false;
  239. }
  240. for (auto [index, new_param_ref_id, prev_param_ref_id] :
  241. llvm::enumerate(new_param_ref_ids, prev_param_ref_ids)) {
  242. if (!CheckRedeclParam(context, param_diag_label, index, new_param_ref_id,
  243. prev_param_ref_id, prev_specific_id)) {
  244. return false;
  245. }
  246. }
  247. return true;
  248. }
  249. // Returns true if the two nodes represent the same syntax.
  250. // TODO: Detect raw identifiers (will require token changes).
  251. static auto IsNodeSyntaxEqual(Context& context, Parse::NodeId new_node_id,
  252. Parse::NodeId prev_node_id) -> bool {
  253. if (context.parse_tree().node_kind(new_node_id) !=
  254. context.parse_tree().node_kind(prev_node_id)) {
  255. return false;
  256. }
  257. // TODO: Should there be a trivial way to check if we need to check spellings?
  258. // Identifiers and literals need their text checked for cross-file matching,
  259. // but not intra-file. Keywords and operators shouldn't need the token text
  260. // examined at all.
  261. auto new_spelling = context.tokens().GetTokenText(
  262. context.parse_tree().node_token(new_node_id));
  263. auto prev_spelling = context.tokens().GetTokenText(
  264. context.parse_tree().node_token(prev_node_id));
  265. return new_spelling == prev_spelling;
  266. }
  267. // Returns false if redeclaration parameter syntax doesn't match.
  268. static auto CheckRedeclParamSyntax(Context& context,
  269. Parse::NodeId new_first_param_node_id,
  270. Parse::NodeId new_last_param_node_id,
  271. Parse::NodeId prev_first_param_node_id,
  272. Parse::NodeId prev_last_param_node_id)
  273. -> bool {
  274. // Parse nodes may not always be available to compare.
  275. // TODO: Support cross-file syntax checks. Right now imports provide invalid
  276. // nodes, and we'll need to follow the declaration to its original file to
  277. // get the parse tree.
  278. if (!new_first_param_node_id.is_valid() ||
  279. !prev_first_param_node_id.is_valid()) {
  280. return true;
  281. }
  282. CARBON_CHECK(new_last_param_node_id.is_valid())
  283. << "new_last_param_node_id.is_valid should match "
  284. "new_first_param_node_id.is_valid";
  285. CARBON_CHECK(prev_last_param_node_id.is_valid())
  286. << "prev_last_param_node_id.is_valid should match "
  287. "prev_first_param_node_id.is_valid";
  288. auto new_range = Parse::Tree::PostorderIterator::MakeRange(
  289. new_first_param_node_id, new_last_param_node_id);
  290. auto prev_range = Parse::Tree::PostorderIterator::MakeRange(
  291. prev_first_param_node_id, prev_last_param_node_id);
  292. // zip is using the shortest range. If they differ in length, there should be
  293. // some difference inside the range because the range includes parameter
  294. // brackets. As a consequence, we don't explicitly handle different range
  295. // sizes here.
  296. for (auto [new_node_id, prev_node_id] : llvm::zip(new_range, prev_range)) {
  297. if (!IsNodeSyntaxEqual(context, new_node_id, prev_node_id)) {
  298. CARBON_DIAGNOSTIC(RedeclParamSyntaxDiffers, Error,
  299. "Redeclaration syntax differs here.");
  300. CARBON_DIAGNOSTIC(RedeclParamSyntaxPrevious, Note,
  301. "Comparing with previous declaration here.");
  302. context.emitter()
  303. .Build(new_node_id, RedeclParamSyntaxDiffers)
  304. .Note(prev_node_id, RedeclParamSyntaxPrevious)
  305. .Emit();
  306. return false;
  307. }
  308. }
  309. return true;
  310. }
  311. auto CheckRedeclParamsMatch(Context& context, const DeclParams& new_entity,
  312. const DeclParams& prev_entity,
  313. SemIR::SpecificId prev_specific_id,
  314. bool check_syntax) -> bool {
  315. if (EntityHasParamError(context, new_entity) ||
  316. EntityHasParamError(context, prev_entity)) {
  317. return false;
  318. }
  319. if (!CheckRedeclParams(context, new_entity.loc,
  320. new_entity.implicit_param_refs_id, prev_entity.loc,
  321. prev_entity.implicit_param_refs_id, "implicit ",
  322. prev_specific_id)) {
  323. return false;
  324. }
  325. if (!CheckRedeclParams(context, new_entity.loc, new_entity.param_refs_id,
  326. prev_entity.loc, prev_entity.param_refs_id, "",
  327. prev_specific_id)) {
  328. return false;
  329. }
  330. if (check_syntax &&
  331. !CheckRedeclParamSyntax(context, new_entity.first_param_node_id,
  332. new_entity.last_param_node_id,
  333. prev_entity.first_param_node_id,
  334. prev_entity.last_param_node_id)) {
  335. return false;
  336. }
  337. return true;
  338. }
  339. } // namespace Carbon::Check