resolve_names.cpp 28 KB

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