merge.cpp 16 KB

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