resolve_names.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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 "explorer/interpreter/resolve_names.h"
  5. #include <set>
  6. #include "explorer/ast/declaration.h"
  7. #include "explorer/ast/expression.h"
  8. #include "explorer/ast/pattern.h"
  9. #include "explorer/ast/statement.h"
  10. #include "explorer/ast/static_scope.h"
  11. #include "llvm/Support/Casting.h"
  12. #include "llvm/Support/Error.h"
  13. using llvm::cast;
  14. namespace Carbon {
  15. // Adds the names exposed by the given AST node to enclosing_scope.
  16. static auto AddExposedNames(const Declaration& declaration,
  17. StaticScope& enclosing_scope) -> ErrorOr<Success> {
  18. switch (declaration.kind()) {
  19. case DeclarationKind::InterfaceDeclaration: {
  20. auto& iface_decl = cast<InterfaceDeclaration>(declaration);
  21. CARBON_RETURN_IF_ERROR(
  22. enclosing_scope.Add(iface_decl.name(), &iface_decl,
  23. StaticScope::NameStatus::KnownButNotDeclared));
  24. break;
  25. }
  26. case DeclarationKind::ImplDeclaration: {
  27. // Nothing to do here
  28. break;
  29. }
  30. case DeclarationKind::FunctionDeclaration: {
  31. auto& func = cast<FunctionDeclaration>(declaration);
  32. CARBON_RETURN_IF_ERROR(enclosing_scope.Add(
  33. func.name(), &func, StaticScope::NameStatus::KnownButNotDeclared));
  34. break;
  35. }
  36. case DeclarationKind::ClassDeclaration: {
  37. auto& class_decl = cast<ClassDeclaration>(declaration);
  38. CARBON_RETURN_IF_ERROR(
  39. enclosing_scope.Add(class_decl.name(), &class_decl,
  40. StaticScope::NameStatus::KnownButNotDeclared));
  41. break;
  42. }
  43. case DeclarationKind::ChoiceDeclaration: {
  44. auto& choice = cast<ChoiceDeclaration>(declaration);
  45. CARBON_RETURN_IF_ERROR(
  46. enclosing_scope.Add(choice.name(), &choice,
  47. StaticScope::NameStatus::KnownButNotDeclared));
  48. break;
  49. }
  50. case DeclarationKind::VariableDeclaration: {
  51. auto& var = cast<VariableDeclaration>(declaration);
  52. if (var.binding().name() != AnonymousName) {
  53. CARBON_RETURN_IF_ERROR(
  54. enclosing_scope.Add(var.binding().name(), &var.binding(),
  55. StaticScope::NameStatus::KnownButNotDeclared));
  56. }
  57. break;
  58. }
  59. case DeclarationKind::AssociatedConstantDeclaration: {
  60. auto& let = cast<AssociatedConstantDeclaration>(declaration);
  61. if (let.binding().name() != AnonymousName) {
  62. CARBON_RETURN_IF_ERROR(
  63. enclosing_scope.Add(let.binding().name(), &let.binding()));
  64. }
  65. break;
  66. }
  67. case DeclarationKind::SelfDeclaration: {
  68. auto& self = cast<SelfDeclaration>(declaration);
  69. CARBON_RETURN_IF_ERROR(enclosing_scope.Add("Self", &self));
  70. break;
  71. }
  72. case DeclarationKind::AliasDeclaration: {
  73. auto& alias = cast<AliasDeclaration>(declaration);
  74. CARBON_RETURN_IF_ERROR(enclosing_scope.Add(
  75. alias.name(), &alias, StaticScope::NameStatus::KnownButNotDeclared));
  76. break;
  77. }
  78. }
  79. return Success();
  80. }
  81. namespace {
  82. enum class ResolveFunctionBodies {
  83. // Do not resolve names in function bodies.
  84. Skip,
  85. // Resolve all names. When visiting a declaration with members, resolve
  86. // names in member function bodies after resolving the names in all member
  87. // declarations, as if the bodies appeared after all the declarations.
  88. AfterDeclarations,
  89. // Resolve names in function bodies immediately. This is appropriate when
  90. // the declarations of all members of enclosing classes, interfaces, and
  91. // similar have already been resolved.
  92. Immediately,
  93. };
  94. } // namespace
  95. // Traverses the sub-AST rooted at the given node, resolving all names within
  96. // it using enclosing_scope, and updating enclosing_scope to add names to
  97. // it as they become available. In scopes where names are only visible below
  98. // their point of declaration (such as block scopes in C++), this is implemented
  99. // as a single pass, recursively calling ResolveNames on the elements of the
  100. // scope in order. In scopes where names are also visible above their point of
  101. // declaration (such as class scopes in C++), this requires three passes: first
  102. // calling AddExposedNames on each element of the scope to populate a
  103. // StaticScope, and then calling ResolveNames on each element, passing it the
  104. // already-populated StaticScope but skipping member function bodies, and
  105. // finally calling ResolvedNames again on each element, and this time resolving
  106. // member function bodies.
  107. static auto ResolveNames(Expression& expression,
  108. const StaticScope& enclosing_scope)
  109. -> ErrorOr<Success>;
  110. static auto ResolveNames(WhereClause& clause,
  111. const StaticScope& enclosing_scope)
  112. -> ErrorOr<Success>;
  113. static auto ResolveNames(Pattern& pattern, StaticScope& enclosing_scope)
  114. -> ErrorOr<Success>;
  115. static auto ResolveNames(Statement& statement, StaticScope& enclosing_scope)
  116. -> ErrorOr<Success>;
  117. static auto ResolveNames(Declaration& declaration, StaticScope& enclosing_scope,
  118. ResolveFunctionBodies bodies) -> ErrorOr<Success>;
  119. static auto ResolveNames(Expression& expression,
  120. const StaticScope& enclosing_scope)
  121. -> ErrorOr<Success> {
  122. switch (expression.kind()) {
  123. case ExpressionKind::CallExpression: {
  124. auto& call = cast<CallExpression>(expression);
  125. CARBON_RETURN_IF_ERROR(ResolveNames(call.function(), enclosing_scope));
  126. CARBON_RETURN_IF_ERROR(ResolveNames(call.argument(), enclosing_scope));
  127. break;
  128. }
  129. case ExpressionKind::FunctionTypeLiteral: {
  130. auto& fun_type = cast<FunctionTypeLiteral>(expression);
  131. CARBON_RETURN_IF_ERROR(
  132. ResolveNames(fun_type.parameter(), enclosing_scope));
  133. CARBON_RETURN_IF_ERROR(
  134. ResolveNames(fun_type.return_type(), enclosing_scope));
  135. break;
  136. }
  137. case ExpressionKind::SimpleMemberAccessExpression:
  138. CARBON_RETURN_IF_ERROR(
  139. ResolveNames(cast<SimpleMemberAccessExpression>(expression).object(),
  140. enclosing_scope));
  141. break;
  142. case ExpressionKind::CompoundMemberAccessExpression: {
  143. auto& access = cast<CompoundMemberAccessExpression>(expression);
  144. CARBON_RETURN_IF_ERROR(ResolveNames(access.object(), enclosing_scope));
  145. CARBON_RETURN_IF_ERROR(ResolveNames(access.path(), enclosing_scope));
  146. break;
  147. }
  148. case ExpressionKind::IndexExpression: {
  149. auto& index = cast<IndexExpression>(expression);
  150. CARBON_RETURN_IF_ERROR(ResolveNames(index.object(), enclosing_scope));
  151. CARBON_RETURN_IF_ERROR(ResolveNames(index.offset(), enclosing_scope));
  152. break;
  153. }
  154. case ExpressionKind::OperatorExpression:
  155. for (Nonnull<Expression*> operand :
  156. cast<OperatorExpression>(expression).arguments()) {
  157. CARBON_RETURN_IF_ERROR(ResolveNames(*operand, enclosing_scope));
  158. }
  159. break;
  160. case ExpressionKind::TupleLiteral:
  161. for (Nonnull<Expression*> field :
  162. cast<TupleLiteral>(expression).fields()) {
  163. CARBON_RETURN_IF_ERROR(ResolveNames(*field, enclosing_scope));
  164. }
  165. break;
  166. case ExpressionKind::StructLiteral:
  167. for (FieldInitializer& init : cast<StructLiteral>(expression).fields()) {
  168. CARBON_RETURN_IF_ERROR(
  169. ResolveNames(init.expression(), enclosing_scope));
  170. }
  171. break;
  172. case ExpressionKind::StructTypeLiteral:
  173. for (FieldInitializer& init :
  174. cast<StructTypeLiteral>(expression).fields()) {
  175. CARBON_RETURN_IF_ERROR(
  176. ResolveNames(init.expression(), enclosing_scope));
  177. }
  178. break;
  179. case ExpressionKind::IdentifierExpression: {
  180. auto& identifier = cast<IdentifierExpression>(expression);
  181. CARBON_ASSIGN_OR_RETURN(
  182. const auto value_node,
  183. enclosing_scope.Resolve(identifier.name(), identifier.source_loc()));
  184. identifier.set_value_node(value_node);
  185. break;
  186. }
  187. case ExpressionKind::DotSelfExpression: {
  188. auto& dot_self = cast<DotSelfExpression>(expression);
  189. CARBON_ASSIGN_OR_RETURN(
  190. const auto value_node,
  191. enclosing_scope.Resolve(".Self", dot_self.source_loc()));
  192. dot_self.set_self_binding(const_cast<GenericBinding*>(
  193. &cast<GenericBinding>(value_node.base())));
  194. break;
  195. }
  196. case ExpressionKind::IntrinsicExpression:
  197. CARBON_RETURN_IF_ERROR(ResolveNames(
  198. cast<IntrinsicExpression>(expression).args(), enclosing_scope));
  199. break;
  200. case ExpressionKind::IfExpression: {
  201. auto& if_expr = cast<IfExpression>(expression);
  202. CARBON_RETURN_IF_ERROR(
  203. ResolveNames(if_expr.condition(), enclosing_scope));
  204. CARBON_RETURN_IF_ERROR(
  205. ResolveNames(if_expr.then_expression(), enclosing_scope));
  206. CARBON_RETURN_IF_ERROR(
  207. ResolveNames(if_expr.else_expression(), enclosing_scope));
  208. break;
  209. }
  210. case ExpressionKind::WhereExpression: {
  211. auto& where = cast<WhereExpression>(expression);
  212. CARBON_RETURN_IF_ERROR(
  213. ResolveNames(where.self_binding().type(), enclosing_scope));
  214. // Introduce `.Self` into scope on the right of the `where` keyword.
  215. StaticScope where_scope;
  216. where_scope.AddParent(&enclosing_scope);
  217. CARBON_RETURN_IF_ERROR(where_scope.Add(".Self", &where.self_binding()));
  218. for (Nonnull<WhereClause*> clause : where.clauses()) {
  219. CARBON_RETURN_IF_ERROR(ResolveNames(*clause, where_scope));
  220. }
  221. break;
  222. }
  223. case ExpressionKind::ArrayTypeLiteral: {
  224. auto& array_literal = cast<ArrayTypeLiteral>(expression);
  225. CARBON_RETURN_IF_ERROR(ResolveNames(
  226. array_literal.element_type_expression(), enclosing_scope));
  227. CARBON_RETURN_IF_ERROR(
  228. ResolveNames(array_literal.size_expression(), enclosing_scope));
  229. break;
  230. }
  231. case ExpressionKind::BoolTypeLiteral:
  232. case ExpressionKind::BoolLiteral:
  233. case ExpressionKind::IntTypeLiteral:
  234. case ExpressionKind::ContinuationTypeLiteral:
  235. case ExpressionKind::IntLiteral:
  236. case ExpressionKind::StringLiteral:
  237. case ExpressionKind::StringTypeLiteral:
  238. case ExpressionKind::TypeTypeLiteral:
  239. case ExpressionKind::ValueLiteral:
  240. break;
  241. case ExpressionKind::InstantiateImpl: // created after name resolution
  242. case ExpressionKind::UnimplementedExpression:
  243. return CompilationError(expression.source_loc()) << "Unimplemented";
  244. }
  245. return Success();
  246. }
  247. static auto ResolveNames(WhereClause& clause,
  248. const StaticScope& enclosing_scope)
  249. -> ErrorOr<Success> {
  250. switch (clause.kind()) {
  251. case WhereClauseKind::IsWhereClause: {
  252. auto& is_clause = cast<IsWhereClause>(clause);
  253. CARBON_RETURN_IF_ERROR(ResolveNames(is_clause.type(), enclosing_scope));
  254. CARBON_RETURN_IF_ERROR(
  255. ResolveNames(is_clause.constraint(), enclosing_scope));
  256. break;
  257. }
  258. case WhereClauseKind::EqualsWhereClause: {
  259. auto& equals_clause = cast<EqualsWhereClause>(clause);
  260. CARBON_RETURN_IF_ERROR(
  261. ResolveNames(equals_clause.lhs(), enclosing_scope));
  262. CARBON_RETURN_IF_ERROR(
  263. ResolveNames(equals_clause.rhs(), enclosing_scope));
  264. break;
  265. }
  266. }
  267. return Success();
  268. }
  269. static auto ResolveNames(Pattern& pattern, StaticScope& enclosing_scope)
  270. -> ErrorOr<Success> {
  271. switch (pattern.kind()) {
  272. case PatternKind::BindingPattern: {
  273. auto& binding = cast<BindingPattern>(pattern);
  274. CARBON_RETURN_IF_ERROR(ResolveNames(binding.type(), enclosing_scope));
  275. if (binding.name() != AnonymousName) {
  276. CARBON_RETURN_IF_ERROR(enclosing_scope.Add(binding.name(), &binding));
  277. }
  278. break;
  279. }
  280. case PatternKind::GenericBinding: {
  281. auto& binding = cast<GenericBinding>(pattern);
  282. // `.Self` is in scope in the context of the type.
  283. StaticScope self_scope;
  284. self_scope.AddParent(&enclosing_scope);
  285. CARBON_RETURN_IF_ERROR(self_scope.Add(".Self", &binding));
  286. CARBON_RETURN_IF_ERROR(ResolveNames(binding.type(), self_scope));
  287. if (binding.name() != AnonymousName) {
  288. CARBON_RETURN_IF_ERROR(enclosing_scope.Add(binding.name(), &binding));
  289. }
  290. break;
  291. }
  292. case PatternKind::TuplePattern:
  293. for (Nonnull<Pattern*> field : cast<TuplePattern>(pattern).fields()) {
  294. CARBON_RETURN_IF_ERROR(ResolveNames(*field, enclosing_scope));
  295. }
  296. break;
  297. case PatternKind::AlternativePattern: {
  298. auto& alternative = cast<AlternativePattern>(pattern);
  299. CARBON_RETURN_IF_ERROR(
  300. ResolveNames(alternative.choice_type(), enclosing_scope));
  301. CARBON_RETURN_IF_ERROR(
  302. ResolveNames(alternative.arguments(), enclosing_scope));
  303. break;
  304. }
  305. case PatternKind::ExpressionPattern:
  306. CARBON_RETURN_IF_ERROR(ResolveNames(
  307. cast<ExpressionPattern>(pattern).expression(), enclosing_scope));
  308. break;
  309. case PatternKind::AutoPattern:
  310. break;
  311. case PatternKind::VarPattern:
  312. CARBON_RETURN_IF_ERROR(
  313. ResolveNames(cast<VarPattern>(pattern).pattern(), enclosing_scope));
  314. break;
  315. case PatternKind::AddrPattern:
  316. CARBON_RETURN_IF_ERROR(
  317. ResolveNames(cast<AddrPattern>(pattern).binding(), enclosing_scope));
  318. break;
  319. }
  320. return Success();
  321. }
  322. static auto ResolveNames(Statement& statement, StaticScope& enclosing_scope)
  323. -> ErrorOr<Success> {
  324. switch (statement.kind()) {
  325. case StatementKind::ExpressionStatement:
  326. CARBON_RETURN_IF_ERROR(ResolveNames(
  327. cast<ExpressionStatement>(statement).expression(), enclosing_scope));
  328. break;
  329. case StatementKind::Assign: {
  330. auto& assign = cast<Assign>(statement);
  331. CARBON_RETURN_IF_ERROR(ResolveNames(assign.lhs(), enclosing_scope));
  332. CARBON_RETURN_IF_ERROR(ResolveNames(assign.rhs(), enclosing_scope));
  333. break;
  334. }
  335. case StatementKind::VariableDefinition: {
  336. auto& def = cast<VariableDefinition>(statement);
  337. if (def.has_init()) {
  338. CARBON_RETURN_IF_ERROR(ResolveNames(def.init(), enclosing_scope));
  339. }
  340. CARBON_RETURN_IF_ERROR(ResolveNames(def.pattern(), enclosing_scope));
  341. if (def.is_returned()) {
  342. CARBON_CHECK(def.pattern().kind() == PatternKind::BindingPattern)
  343. << def.pattern().source_loc()
  344. << "returned var definition can only be a binding pattern";
  345. CARBON_RETURN_IF_ERROR(enclosing_scope.AddReturnedVar(
  346. ValueNodeView(&cast<BindingPattern>(def.pattern()))));
  347. }
  348. break;
  349. }
  350. case StatementKind::If: {
  351. auto& if_stmt = cast<If>(statement);
  352. CARBON_RETURN_IF_ERROR(
  353. ResolveNames(if_stmt.condition(), enclosing_scope));
  354. CARBON_RETURN_IF_ERROR(
  355. ResolveNames(if_stmt.then_block(), enclosing_scope));
  356. if (if_stmt.else_block().has_value()) {
  357. CARBON_RETURN_IF_ERROR(
  358. ResolveNames(**if_stmt.else_block(), enclosing_scope));
  359. }
  360. break;
  361. }
  362. case StatementKind::ReturnVar: {
  363. auto& ret_var_stmt = cast<ReturnVar>(statement);
  364. std::optional<ValueNodeView> returned_var_def_view =
  365. enclosing_scope.ResolveReturned();
  366. if (!returned_var_def_view.has_value()) {
  367. return CompilationError(ret_var_stmt.source_loc())
  368. << "`return var` is not allowed without a returned var defined "
  369. "in scope.";
  370. }
  371. ret_var_stmt.set_value_node(*returned_var_def_view);
  372. break;
  373. }
  374. case StatementKind::ReturnExpression: {
  375. auto& ret_exp_stmt = cast<ReturnExpression>(statement);
  376. std::optional<ValueNodeView> returned_var_def_view =
  377. enclosing_scope.ResolveReturned();
  378. if (returned_var_def_view.has_value()) {
  379. return CompilationError(ret_exp_stmt.source_loc())
  380. << "`return <expression>` is not allowed with a returned var "
  381. "defined in scope: "
  382. << returned_var_def_view->base().source_loc();
  383. }
  384. CARBON_RETURN_IF_ERROR(
  385. ResolveNames(ret_exp_stmt.expression(), enclosing_scope));
  386. break;
  387. }
  388. case StatementKind::Block: {
  389. auto& block = cast<Block>(statement);
  390. StaticScope block_scope;
  391. block_scope.AddParent(&enclosing_scope);
  392. for (Nonnull<Statement*> sub_statement : block.statements()) {
  393. CARBON_RETURN_IF_ERROR(ResolveNames(*sub_statement, block_scope));
  394. }
  395. break;
  396. }
  397. case StatementKind::While: {
  398. auto& while_stmt = cast<While>(statement);
  399. CARBON_RETURN_IF_ERROR(
  400. ResolveNames(while_stmt.condition(), enclosing_scope));
  401. CARBON_RETURN_IF_ERROR(ResolveNames(while_stmt.body(), enclosing_scope));
  402. break;
  403. }
  404. case StatementKind::For: {
  405. StaticScope statement_scope;
  406. statement_scope.AddParent(&enclosing_scope);
  407. auto& for_stmt = cast<For>(statement);
  408. CARBON_RETURN_IF_ERROR(
  409. ResolveNames(for_stmt.loop_target(), statement_scope));
  410. CARBON_RETURN_IF_ERROR(
  411. ResolveNames(for_stmt.variable_declaration(), statement_scope));
  412. CARBON_RETURN_IF_ERROR(ResolveNames(for_stmt.body(), statement_scope));
  413. break;
  414. }
  415. case StatementKind::Match: {
  416. auto& match = cast<Match>(statement);
  417. CARBON_RETURN_IF_ERROR(ResolveNames(match.expression(), enclosing_scope));
  418. for (Match::Clause& clause : match.clauses()) {
  419. StaticScope clause_scope;
  420. clause_scope.AddParent(&enclosing_scope);
  421. CARBON_RETURN_IF_ERROR(ResolveNames(clause.pattern(), clause_scope));
  422. CARBON_RETURN_IF_ERROR(ResolveNames(clause.statement(), clause_scope));
  423. }
  424. break;
  425. }
  426. case StatementKind::Continuation: {
  427. auto& continuation = cast<Continuation>(statement);
  428. CARBON_RETURN_IF_ERROR(
  429. enclosing_scope.Add(continuation.name(), &continuation,
  430. StaticScope::NameStatus::DeclaredButNotUsable));
  431. StaticScope continuation_scope;
  432. continuation_scope.AddParent(&enclosing_scope);
  433. CARBON_RETURN_IF_ERROR(ResolveNames(cast<Continuation>(statement).body(),
  434. continuation_scope));
  435. enclosing_scope.MarkUsable(continuation.name());
  436. break;
  437. }
  438. case StatementKind::Run:
  439. CARBON_RETURN_IF_ERROR(
  440. ResolveNames(cast<Run>(statement).argument(), enclosing_scope));
  441. break;
  442. case StatementKind::Await:
  443. case StatementKind::Break:
  444. case StatementKind::Continue:
  445. break;
  446. }
  447. return Success();
  448. }
  449. static auto ResolveMemberNames(llvm::ArrayRef<Nonnull<Declaration*>> members,
  450. StaticScope& scope, ResolveFunctionBodies bodies)
  451. -> ErrorOr<Success> {
  452. for (Nonnull<Declaration*> member : members) {
  453. CARBON_RETURN_IF_ERROR(AddExposedNames(*member, scope));
  454. }
  455. if (bodies != ResolveFunctionBodies::Immediately) {
  456. for (Nonnull<Declaration*> member : members) {
  457. CARBON_RETURN_IF_ERROR(
  458. ResolveNames(*member, scope, ResolveFunctionBodies::Skip));
  459. }
  460. }
  461. if (bodies != ResolveFunctionBodies::Skip) {
  462. for (Nonnull<Declaration*> member : members) {
  463. CARBON_RETURN_IF_ERROR(
  464. ResolveNames(*member, scope, ResolveFunctionBodies::Immediately));
  465. }
  466. }
  467. return Success();
  468. }
  469. static auto ResolveNames(Declaration& declaration, StaticScope& enclosing_scope,
  470. ResolveFunctionBodies bodies) -> ErrorOr<Success> {
  471. switch (declaration.kind()) {
  472. case DeclarationKind::InterfaceDeclaration: {
  473. auto& iface = cast<InterfaceDeclaration>(declaration);
  474. StaticScope iface_scope;
  475. iface_scope.AddParent(&enclosing_scope);
  476. enclosing_scope.MarkDeclared(iface.name());
  477. if (iface.params().has_value()) {
  478. CARBON_RETURN_IF_ERROR(ResolveNames(**iface.params(), iface_scope));
  479. }
  480. enclosing_scope.MarkUsable(iface.name());
  481. CARBON_RETURN_IF_ERROR(iface_scope.Add("Self", iface.self()));
  482. CARBON_RETURN_IF_ERROR(
  483. ResolveMemberNames(iface.members(), iface_scope, bodies));
  484. break;
  485. }
  486. case DeclarationKind::ImplDeclaration: {
  487. auto& impl = cast<ImplDeclaration>(declaration);
  488. StaticScope impl_scope;
  489. impl_scope.AddParent(&enclosing_scope);
  490. for (Nonnull<GenericBinding*> binding : impl.deduced_parameters()) {
  491. CARBON_RETURN_IF_ERROR(ResolveNames(binding->type(), impl_scope));
  492. CARBON_RETURN_IF_ERROR(impl_scope.Add(binding->name(), binding));
  493. }
  494. CARBON_RETURN_IF_ERROR(ResolveNames(*impl.impl_type(), impl_scope));
  495. // Only add `Self` to the impl_scope if it is not already in the enclosing
  496. // scope. Add `Self` after we resolve names for the impl_type, so you
  497. // can't write something like `impl Vector(Self) as ...`. Add `Self`
  498. // before resolving names in the interface, so you can write something
  499. // like `impl VeryLongTypeName as AddWith(Self)`
  500. if (!enclosing_scope.Resolve("Self", impl.source_loc()).ok()) {
  501. CARBON_RETURN_IF_ERROR(AddExposedNames(*impl.self(), impl_scope));
  502. }
  503. CARBON_RETURN_IF_ERROR(ResolveNames(impl.interface(), impl_scope));
  504. CARBON_RETURN_IF_ERROR(
  505. ResolveMemberNames(impl.members(), impl_scope, bodies));
  506. break;
  507. }
  508. case DeclarationKind::FunctionDeclaration: {
  509. auto& function = cast<FunctionDeclaration>(declaration);
  510. StaticScope function_scope;
  511. function_scope.AddParent(&enclosing_scope);
  512. enclosing_scope.MarkDeclared(function.name());
  513. for (Nonnull<GenericBinding*> binding : function.deduced_parameters()) {
  514. CARBON_RETURN_IF_ERROR(ResolveNames(*binding, function_scope));
  515. }
  516. if (function.is_method()) {
  517. CARBON_RETURN_IF_ERROR(
  518. ResolveNames(function.me_pattern(), function_scope));
  519. }
  520. CARBON_RETURN_IF_ERROR(
  521. ResolveNames(function.param_pattern(), function_scope));
  522. if (function.return_term().type_expression().has_value()) {
  523. CARBON_RETURN_IF_ERROR(ResolveNames(
  524. **function.return_term().type_expression(), function_scope));
  525. }
  526. enclosing_scope.MarkUsable(function.name());
  527. if (function.body().has_value() &&
  528. bodies != ResolveFunctionBodies::Skip) {
  529. CARBON_RETURN_IF_ERROR(ResolveNames(**function.body(), function_scope));
  530. }
  531. break;
  532. }
  533. case DeclarationKind::ClassDeclaration: {
  534. auto& class_decl = cast<ClassDeclaration>(declaration);
  535. StaticScope class_scope;
  536. class_scope.AddParent(&enclosing_scope);
  537. enclosing_scope.MarkDeclared(class_decl.name());
  538. if (class_decl.type_params().has_value()) {
  539. CARBON_RETURN_IF_ERROR(
  540. ResolveNames(**class_decl.type_params(), class_scope));
  541. }
  542. enclosing_scope.MarkUsable(class_decl.name());
  543. CARBON_RETURN_IF_ERROR(AddExposedNames(*class_decl.self(), class_scope));
  544. CARBON_RETURN_IF_ERROR(
  545. ResolveMemberNames(class_decl.members(), class_scope, bodies));
  546. break;
  547. }
  548. case DeclarationKind::ChoiceDeclaration: {
  549. auto& choice = cast<ChoiceDeclaration>(declaration);
  550. StaticScope choice_scope;
  551. choice_scope.AddParent(&enclosing_scope);
  552. enclosing_scope.MarkDeclared(choice.name());
  553. if (choice.type_params().has_value()) {
  554. CARBON_RETURN_IF_ERROR(
  555. ResolveNames(**choice.type_params(), choice_scope));
  556. }
  557. // Alternative names are never used unqualified, so we don't need to
  558. // add the alternatives to a scope, or introduce a new scope; we only
  559. // need to check for duplicates.
  560. std::set<std::string_view> alternative_names;
  561. for (Nonnull<AlternativeSignature*> alternative : choice.alternatives()) {
  562. CARBON_RETURN_IF_ERROR(
  563. ResolveNames(alternative->signature(), choice_scope));
  564. if (!alternative_names.insert(alternative->name()).second) {
  565. return CompilationError(alternative->source_loc())
  566. << "Duplicate name `" << alternative->name()
  567. << "` in choice type";
  568. }
  569. }
  570. enclosing_scope.MarkUsable(choice.name());
  571. break;
  572. }
  573. case DeclarationKind::VariableDeclaration: {
  574. auto& var = cast<VariableDeclaration>(declaration);
  575. CARBON_RETURN_IF_ERROR(ResolveNames(var.binding(), enclosing_scope));
  576. if (var.has_initializer()) {
  577. CARBON_RETURN_IF_ERROR(
  578. ResolveNames(var.initializer(), enclosing_scope));
  579. }
  580. break;
  581. }
  582. case DeclarationKind::AssociatedConstantDeclaration: {
  583. auto& let = cast<AssociatedConstantDeclaration>(declaration);
  584. CARBON_RETURN_IF_ERROR(ResolveNames(let.binding(), enclosing_scope));
  585. break;
  586. }
  587. case DeclarationKind::SelfDeclaration: {
  588. CARBON_FATAL() << "Unreachable: resolving names for `Self` declaration";
  589. }
  590. case DeclarationKind::AliasDeclaration: {
  591. auto& alias = cast<AliasDeclaration>(declaration);
  592. enclosing_scope.MarkDeclared(alias.name());
  593. CARBON_RETURN_IF_ERROR(ResolveNames(alias.target(), enclosing_scope));
  594. enclosing_scope.MarkUsable(alias.name());
  595. break;
  596. }
  597. }
  598. return Success();
  599. }
  600. auto ResolveNames(AST& ast) -> ErrorOr<Success> {
  601. StaticScope file_scope;
  602. for (auto declaration : ast.declarations) {
  603. CARBON_RETURN_IF_ERROR(AddExposedNames(*declaration, file_scope));
  604. }
  605. for (auto declaration : ast.declarations) {
  606. CARBON_RETURN_IF_ERROR(ResolveNames(
  607. *declaration, file_scope, ResolveFunctionBodies::AfterDeclarations));
  608. }
  609. return ResolveNames(**ast.main_call, file_scope);
  610. }
  611. } // namespace Carbon