resolve_names.cpp 27 KB

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