merge.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. Substitutions substitutions) -> 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. SubstType(context, prev_param_ref.type_id(), substitutions))) {
  165. diagnose();
  166. return false;
  167. }
  168. if (new_param_ref.Is<SemIR::AddrPattern>()) {
  169. new_param_ref =
  170. context.insts().Get(new_param_ref.As<SemIR::AddrPattern>().inner_id);
  171. prev_param_ref =
  172. context.insts().Get(prev_param_ref.As<SemIR::AddrPattern>().inner_id);
  173. if (new_param_ref.kind() != prev_param_ref.kind()) {
  174. diagnose();
  175. return false;
  176. }
  177. }
  178. if (new_param_ref.Is<SemIR::AnyBindName>()) {
  179. new_param_ref =
  180. context.insts().Get(new_param_ref.As<SemIR::AnyBindName>().value_id);
  181. prev_param_ref =
  182. context.insts().Get(prev_param_ref.As<SemIR::AnyBindName>().value_id);
  183. }
  184. auto new_param = new_param_ref.As<SemIR::Param>();
  185. auto prev_param = prev_param_ref.As<SemIR::Param>();
  186. if (new_param.name_id != prev_param.name_id) {
  187. diagnose();
  188. return false;
  189. }
  190. return true;
  191. }
  192. // Returns false if the param refs differ for a redeclaration.
  193. static auto CheckRedeclParams(Context& context, SemIRLoc new_decl_loc,
  194. SemIR::InstBlockId new_param_refs_id,
  195. SemIRLoc prev_decl_loc,
  196. SemIR::InstBlockId prev_param_refs_id,
  197. llvm::StringLiteral param_diag_label,
  198. Substitutions substitutions) -> bool {
  199. // This will often occur for empty params.
  200. if (new_param_refs_id == prev_param_refs_id) {
  201. return true;
  202. }
  203. // If exactly one of the parameter lists was present, they differ.
  204. if (new_param_refs_id.is_valid() != prev_param_refs_id.is_valid()) {
  205. CARBON_DIAGNOSTIC(RedeclParamListDiffers, Error,
  206. "Redeclaration differs because of {1}{0}parameter list.",
  207. llvm::StringLiteral, llvm::StringLiteral);
  208. CARBON_DIAGNOSTIC(RedeclParamListPrevious, Note,
  209. "Previously declared with{1} {0}parameter list.",
  210. llvm::StringLiteral, llvm::StringLiteral);
  211. context.emitter()
  212. .Build(
  213. new_decl_loc, RedeclParamListDiffers, param_diag_label,
  214. new_param_refs_id.is_valid() ? llvm::StringLiteral("") : "missing ")
  215. .Note(prev_decl_loc, RedeclParamListPrevious, param_diag_label,
  216. prev_param_refs_id.is_valid() ? llvm::StringLiteral("") : "out")
  217. .Emit();
  218. return false;
  219. }
  220. CARBON_CHECK(new_param_refs_id.is_valid() && prev_param_refs_id.is_valid());
  221. const auto new_param_ref_ids = context.inst_blocks().Get(new_param_refs_id);
  222. const auto prev_param_ref_ids = context.inst_blocks().Get(prev_param_refs_id);
  223. if (new_param_ref_ids.size() != prev_param_ref_ids.size()) {
  224. CARBON_DIAGNOSTIC(
  225. RedeclParamCountDiffers, Error,
  226. "Redeclaration differs because of {0}parameter count of {1}.",
  227. llvm::StringLiteral, int32_t);
  228. CARBON_DIAGNOSTIC(RedeclParamCountPrevious, Note,
  229. "Previously declared with {0}parameter count of {1}.",
  230. llvm::StringLiteral, int32_t);
  231. context.emitter()
  232. .Build(new_decl_loc, RedeclParamCountDiffers, param_diag_label,
  233. new_param_ref_ids.size())
  234. .Note(prev_decl_loc, RedeclParamCountPrevious, param_diag_label,
  235. prev_param_ref_ids.size())
  236. .Emit();
  237. return false;
  238. }
  239. for (auto [index, new_param_ref_id, prev_param_ref_id] :
  240. llvm::enumerate(new_param_ref_ids, prev_param_ref_ids)) {
  241. if (!CheckRedeclParam(context, param_diag_label, index, new_param_ref_id,
  242. prev_param_ref_id, substitutions)) {
  243. return false;
  244. }
  245. }
  246. return true;
  247. }
  248. // Returns true if the two nodes represent the same syntax.
  249. // TODO: Detect raw identifiers (will require token changes).
  250. static auto IsNodeSyntaxEqual(Context& context, Parse::NodeId new_node_id,
  251. Parse::NodeId prev_node_id) -> bool {
  252. if (context.parse_tree().node_kind(new_node_id) !=
  253. context.parse_tree().node_kind(prev_node_id)) {
  254. return false;
  255. }
  256. // TODO: Should there be a trivial way to check if we need to check spellings?
  257. // Identifiers and literals need their text checked for cross-file matching,
  258. // but not intra-file. Keywords and operators shouldn't need the token text
  259. // examined at all.
  260. auto new_spelling = context.tokens().GetTokenText(
  261. context.parse_tree().node_token(new_node_id));
  262. auto prev_spelling = context.tokens().GetTokenText(
  263. context.parse_tree().node_token(prev_node_id));
  264. return new_spelling == prev_spelling;
  265. }
  266. // Returns false if redeclaration parameter syntax doesn't match.
  267. static auto CheckRedeclParamSyntax(Context& context,
  268. Parse::NodeId new_first_param_node_id,
  269. Parse::NodeId new_last_param_node_id,
  270. Parse::NodeId prev_first_param_node_id,
  271. Parse::NodeId prev_last_param_node_id)
  272. -> bool {
  273. // Parse nodes may not always be available to compare.
  274. // TODO: Support cross-file syntax checks. Right now imports provide invalid
  275. // nodes, and we'll need to follow the declaration to its original file to
  276. // get the parse tree.
  277. if (!new_first_param_node_id.is_valid() ||
  278. !prev_first_param_node_id.is_valid()) {
  279. return true;
  280. }
  281. CARBON_CHECK(new_last_param_node_id.is_valid())
  282. << "new_last_param_node_id.is_valid should match "
  283. "new_first_param_node_id.is_valid";
  284. CARBON_CHECK(prev_last_param_node_id.is_valid())
  285. << "prev_last_param_node_id.is_valid should match "
  286. "prev_first_param_node_id.is_valid";
  287. auto new_range = context.parse_tree().postorder(new_first_param_node_id,
  288. new_last_param_node_id);
  289. auto prev_range = context.parse_tree().postorder(prev_first_param_node_id,
  290. prev_last_param_node_id);
  291. // zip is using the shortest range. If they differ in length, there should be
  292. // some difference inside the range because the range includes parameter
  293. // brackets. As a consequence, we don't explicitly handle different range
  294. // sizes here.
  295. for (auto [new_node_id, prev_node_id] : llvm::zip(new_range, prev_range)) {
  296. if (!IsNodeSyntaxEqual(context, new_node_id, prev_node_id)) {
  297. CARBON_DIAGNOSTIC(RedeclParamSyntaxDiffers, Error,
  298. "Redeclaration syntax differs here.");
  299. CARBON_DIAGNOSTIC(RedeclParamSyntaxPrevious, Note,
  300. "Comparing with previous declaration here.");
  301. context.emitter()
  302. .Build(new_node_id, RedeclParamSyntaxDiffers)
  303. .Note(prev_node_id, RedeclParamSyntaxPrevious)
  304. .Emit();
  305. return false;
  306. }
  307. }
  308. return true;
  309. }
  310. auto CheckRedeclParamsMatch(Context& context, const DeclParams& new_entity,
  311. const DeclParams& prev_entity,
  312. Substitutions substitutions, bool check_syntax)
  313. -> bool {
  314. if (EntityHasParamError(context, new_entity) ||
  315. EntityHasParamError(context, prev_entity)) {
  316. return false;
  317. }
  318. if (!CheckRedeclParams(context, new_entity.loc,
  319. new_entity.implicit_param_refs_id, prev_entity.loc,
  320. prev_entity.implicit_param_refs_id, "implicit ",
  321. substitutions)) {
  322. return false;
  323. }
  324. if (!CheckRedeclParams(context, new_entity.loc, new_entity.param_refs_id,
  325. prev_entity.loc, prev_entity.param_refs_id, "",
  326. substitutions)) {
  327. return false;
  328. }
  329. if (check_syntax &&
  330. !CheckRedeclParamSyntax(context, new_entity.first_param_node_id,
  331. new_entity.last_param_node_id,
  332. prev_entity.first_param_node_id,
  333. prev_entity.last_param_node_id)) {
  334. return false;
  335. }
  336. return true;
  337. }
  338. } // namespace Carbon::Check