resolve_names.cpp 28 KB

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