resolve_names.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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. // If we're already in a `.Self` context, remember it so that we can
  234. // reuse its value for the inner `.Self`.
  235. if (auto enclosing_dot_self =
  236. enclosing_scope.Resolve(".Self", where.source_loc());
  237. enclosing_dot_self.ok()) {
  238. where.set_enclosing_dot_self(
  239. &cast<GenericBinding>(enclosing_dot_self->base()));
  240. }
  241. // Introduce `.Self` into scope on the right of the `where` keyword.
  242. StaticScope where_scope;
  243. where_scope.AddParent(&enclosing_scope);
  244. CARBON_RETURN_IF_ERROR(where_scope.Add(".Self", &where.self_binding()));
  245. for (Nonnull<WhereClause*> clause : where.clauses()) {
  246. CARBON_RETURN_IF_ERROR(ResolveNames(*clause, where_scope));
  247. }
  248. break;
  249. }
  250. case ExpressionKind::ArrayTypeLiteral: {
  251. auto& array_literal = cast<ArrayTypeLiteral>(expression);
  252. CARBON_RETURN_IF_ERROR(ResolveNames(
  253. array_literal.element_type_expression(), enclosing_scope));
  254. CARBON_RETURN_IF_ERROR(
  255. ResolveNames(array_literal.size_expression(), enclosing_scope));
  256. break;
  257. }
  258. case ExpressionKind::BoolTypeLiteral:
  259. case ExpressionKind::BoolLiteral:
  260. case ExpressionKind::IntTypeLiteral:
  261. case ExpressionKind::ContinuationTypeLiteral:
  262. case ExpressionKind::IntLiteral:
  263. case ExpressionKind::StringLiteral:
  264. case ExpressionKind::StringTypeLiteral:
  265. case ExpressionKind::TypeTypeLiteral:
  266. case ExpressionKind::ValueLiteral:
  267. break;
  268. case ExpressionKind::UnimplementedExpression:
  269. return ProgramError(expression.source_loc()) << "Unimplemented";
  270. }
  271. return Success();
  272. }
  273. static auto ResolveNames(WhereClause& clause,
  274. const StaticScope& enclosing_scope)
  275. -> ErrorOr<Success> {
  276. switch (clause.kind()) {
  277. case WhereClauseKind::IsWhereClause: {
  278. auto& is_clause = cast<IsWhereClause>(clause);
  279. CARBON_RETURN_IF_ERROR(ResolveNames(is_clause.type(), enclosing_scope));
  280. CARBON_RETURN_IF_ERROR(
  281. ResolveNames(is_clause.constraint(), enclosing_scope));
  282. break;
  283. }
  284. case WhereClauseKind::EqualsWhereClause: {
  285. auto& equals_clause = cast<EqualsWhereClause>(clause);
  286. CARBON_RETURN_IF_ERROR(
  287. ResolveNames(equals_clause.lhs(), enclosing_scope));
  288. CARBON_RETURN_IF_ERROR(
  289. ResolveNames(equals_clause.rhs(), enclosing_scope));
  290. break;
  291. }
  292. case WhereClauseKind::RewriteWhereClause: {
  293. auto& rewrite_clause = cast<RewriteWhereClause>(clause);
  294. CARBON_RETURN_IF_ERROR(
  295. ResolveNames(rewrite_clause.replacement(), enclosing_scope));
  296. break;
  297. }
  298. }
  299. return Success();
  300. }
  301. static auto ResolveNames(Pattern& pattern, StaticScope& enclosing_scope)
  302. -> ErrorOr<Success> {
  303. switch (pattern.kind()) {
  304. case PatternKind::BindingPattern: {
  305. auto& binding = cast<BindingPattern>(pattern);
  306. CARBON_RETURN_IF_ERROR(ResolveNames(binding.type(), enclosing_scope));
  307. if (binding.name() != AnonymousName) {
  308. CARBON_RETURN_IF_ERROR(enclosing_scope.Add(binding.name(), &binding));
  309. }
  310. break;
  311. }
  312. case PatternKind::GenericBinding: {
  313. auto& binding = cast<GenericBinding>(pattern);
  314. // `.Self` is in scope in the context of the type.
  315. StaticScope self_scope;
  316. self_scope.AddParent(&enclosing_scope);
  317. CARBON_RETURN_IF_ERROR(self_scope.Add(".Self", &binding));
  318. CARBON_RETURN_IF_ERROR(ResolveNames(binding.type(), self_scope));
  319. if (binding.name() != AnonymousName) {
  320. CARBON_RETURN_IF_ERROR(enclosing_scope.Add(binding.name(), &binding));
  321. }
  322. break;
  323. }
  324. case PatternKind::TuplePattern:
  325. for (Nonnull<Pattern*> field : cast<TuplePattern>(pattern).fields()) {
  326. CARBON_RETURN_IF_ERROR(ResolveNames(*field, enclosing_scope));
  327. }
  328. break;
  329. case PatternKind::AlternativePattern: {
  330. auto& alternative = cast<AlternativePattern>(pattern);
  331. CARBON_RETURN_IF_ERROR(
  332. ResolveNames(alternative.choice_type(), enclosing_scope));
  333. CARBON_RETURN_IF_ERROR(
  334. ResolveNames(alternative.arguments(), enclosing_scope));
  335. break;
  336. }
  337. case PatternKind::ExpressionPattern:
  338. CARBON_RETURN_IF_ERROR(ResolveNames(
  339. cast<ExpressionPattern>(pattern).expression(), enclosing_scope));
  340. break;
  341. case PatternKind::AutoPattern:
  342. break;
  343. case PatternKind::VarPattern:
  344. CARBON_RETURN_IF_ERROR(
  345. ResolveNames(cast<VarPattern>(pattern).pattern(), enclosing_scope));
  346. break;
  347. case PatternKind::AddrPattern:
  348. CARBON_RETURN_IF_ERROR(
  349. ResolveNames(cast<AddrPattern>(pattern).binding(), enclosing_scope));
  350. break;
  351. }
  352. return Success();
  353. }
  354. static auto ResolveNames(Statement& statement, StaticScope& enclosing_scope)
  355. -> ErrorOr<Success> {
  356. switch (statement.kind()) {
  357. case StatementKind::ExpressionStatement:
  358. CARBON_RETURN_IF_ERROR(ResolveNames(
  359. cast<ExpressionStatement>(statement).expression(), enclosing_scope));
  360. break;
  361. case StatementKind::Assign: {
  362. auto& assign = cast<Assign>(statement);
  363. CARBON_RETURN_IF_ERROR(ResolveNames(assign.lhs(), enclosing_scope));
  364. CARBON_RETURN_IF_ERROR(ResolveNames(assign.rhs(), enclosing_scope));
  365. break;
  366. }
  367. case StatementKind::VariableDefinition: {
  368. auto& def = cast<VariableDefinition>(statement);
  369. if (def.has_init()) {
  370. CARBON_RETURN_IF_ERROR(ResolveNames(def.init(), enclosing_scope));
  371. }
  372. CARBON_RETURN_IF_ERROR(ResolveNames(def.pattern(), enclosing_scope));
  373. if (def.is_returned()) {
  374. CARBON_CHECK(def.pattern().kind() == PatternKind::BindingPattern)
  375. << def.pattern().source_loc()
  376. << "returned var definition can only be a binding pattern";
  377. CARBON_RETURN_IF_ERROR(enclosing_scope.AddReturnedVar(
  378. ValueNodeView(&cast<BindingPattern>(def.pattern()))));
  379. }
  380. break;
  381. }
  382. case StatementKind::If: {
  383. auto& if_stmt = cast<If>(statement);
  384. CARBON_RETURN_IF_ERROR(
  385. ResolveNames(if_stmt.condition(), enclosing_scope));
  386. CARBON_RETURN_IF_ERROR(
  387. ResolveNames(if_stmt.then_block(), enclosing_scope));
  388. if (if_stmt.else_block().has_value()) {
  389. CARBON_RETURN_IF_ERROR(
  390. ResolveNames(**if_stmt.else_block(), enclosing_scope));
  391. }
  392. break;
  393. }
  394. case StatementKind::ReturnVar: {
  395. auto& ret_var_stmt = cast<ReturnVar>(statement);
  396. std::optional<ValueNodeView> returned_var_def_view =
  397. enclosing_scope.ResolveReturned();
  398. if (!returned_var_def_view.has_value()) {
  399. return ProgramError(ret_var_stmt.source_loc())
  400. << "`return var` is not allowed without a returned var defined "
  401. "in scope.";
  402. }
  403. ret_var_stmt.set_value_node(*returned_var_def_view);
  404. break;
  405. }
  406. case StatementKind::ReturnExpression: {
  407. auto& ret_exp_stmt = cast<ReturnExpression>(statement);
  408. std::optional<ValueNodeView> returned_var_def_view =
  409. enclosing_scope.ResolveReturned();
  410. if (returned_var_def_view.has_value()) {
  411. return ProgramError(ret_exp_stmt.source_loc())
  412. << "`return <expression>` is not allowed with a returned var "
  413. "defined in scope: "
  414. << returned_var_def_view->base().source_loc();
  415. }
  416. CARBON_RETURN_IF_ERROR(
  417. ResolveNames(ret_exp_stmt.expression(), enclosing_scope));
  418. break;
  419. }
  420. case StatementKind::Block: {
  421. auto& block = cast<Block>(statement);
  422. StaticScope block_scope;
  423. block_scope.AddParent(&enclosing_scope);
  424. for (Nonnull<Statement*> sub_statement : block.statements()) {
  425. CARBON_RETURN_IF_ERROR(ResolveNames(*sub_statement, block_scope));
  426. }
  427. break;
  428. }
  429. case StatementKind::While: {
  430. auto& while_stmt = cast<While>(statement);
  431. CARBON_RETURN_IF_ERROR(
  432. ResolveNames(while_stmt.condition(), enclosing_scope));
  433. CARBON_RETURN_IF_ERROR(ResolveNames(while_stmt.body(), enclosing_scope));
  434. break;
  435. }
  436. case StatementKind::For: {
  437. StaticScope statement_scope;
  438. statement_scope.AddParent(&enclosing_scope);
  439. auto& for_stmt = cast<For>(statement);
  440. CARBON_RETURN_IF_ERROR(
  441. ResolveNames(for_stmt.loop_target(), statement_scope));
  442. CARBON_RETURN_IF_ERROR(
  443. ResolveNames(for_stmt.variable_declaration(), statement_scope));
  444. CARBON_RETURN_IF_ERROR(ResolveNames(for_stmt.body(), statement_scope));
  445. break;
  446. }
  447. case StatementKind::Match: {
  448. auto& match = cast<Match>(statement);
  449. CARBON_RETURN_IF_ERROR(ResolveNames(match.expression(), enclosing_scope));
  450. for (Match::Clause& clause : match.clauses()) {
  451. StaticScope clause_scope;
  452. clause_scope.AddParent(&enclosing_scope);
  453. CARBON_RETURN_IF_ERROR(ResolveNames(clause.pattern(), clause_scope));
  454. CARBON_RETURN_IF_ERROR(ResolveNames(clause.statement(), clause_scope));
  455. }
  456. break;
  457. }
  458. case StatementKind::Continuation: {
  459. auto& continuation = cast<Continuation>(statement);
  460. CARBON_RETURN_IF_ERROR(
  461. enclosing_scope.Add(continuation.name(), &continuation,
  462. StaticScope::NameStatus::DeclaredButNotUsable));
  463. StaticScope continuation_scope;
  464. continuation_scope.AddParent(&enclosing_scope);
  465. CARBON_RETURN_IF_ERROR(ResolveNames(cast<Continuation>(statement).body(),
  466. continuation_scope));
  467. enclosing_scope.MarkUsable(continuation.name());
  468. break;
  469. }
  470. case StatementKind::Run:
  471. CARBON_RETURN_IF_ERROR(
  472. ResolveNames(cast<Run>(statement).argument(), enclosing_scope));
  473. break;
  474. case StatementKind::Await:
  475. case StatementKind::Break:
  476. case StatementKind::Continue:
  477. break;
  478. }
  479. return Success();
  480. }
  481. static auto ResolveMemberNames(llvm::ArrayRef<Nonnull<Declaration*>> members,
  482. StaticScope& scope, ResolveFunctionBodies bodies)
  483. -> ErrorOr<Success> {
  484. for (Nonnull<Declaration*> member : members) {
  485. CARBON_RETURN_IF_ERROR(AddExposedNames(*member, scope));
  486. }
  487. if (bodies != ResolveFunctionBodies::Immediately) {
  488. for (Nonnull<Declaration*> member : members) {
  489. CARBON_RETURN_IF_ERROR(
  490. ResolveNames(*member, scope, ResolveFunctionBodies::Skip));
  491. }
  492. }
  493. if (bodies != ResolveFunctionBodies::Skip) {
  494. for (Nonnull<Declaration*> member : members) {
  495. CARBON_RETURN_IF_ERROR(
  496. ResolveNames(*member, scope, ResolveFunctionBodies::Immediately));
  497. }
  498. }
  499. return Success();
  500. }
  501. static auto ResolveNames(Declaration& declaration, StaticScope& enclosing_scope,
  502. ResolveFunctionBodies bodies) -> ErrorOr<Success> {
  503. switch (declaration.kind()) {
  504. case DeclarationKind::InterfaceDeclaration: {
  505. auto& iface = cast<InterfaceDeclaration>(declaration);
  506. StaticScope iface_scope;
  507. iface_scope.AddParent(&enclosing_scope);
  508. enclosing_scope.MarkDeclared(iface.name());
  509. if (iface.params().has_value()) {
  510. CARBON_RETURN_IF_ERROR(ResolveNames(**iface.params(), iface_scope));
  511. }
  512. enclosing_scope.MarkUsable(iface.name());
  513. // Don't resolve names in the type of the self binding. The
  514. // InterfaceDeclaration constructor already did that.
  515. CARBON_RETURN_IF_ERROR(iface_scope.Add("Self", iface.self()));
  516. CARBON_RETURN_IF_ERROR(
  517. ResolveMemberNames(iface.members(), iface_scope, bodies));
  518. break;
  519. }
  520. case DeclarationKind::ImplDeclaration: {
  521. auto& impl = cast<ImplDeclaration>(declaration);
  522. StaticScope impl_scope;
  523. impl_scope.AddParent(&enclosing_scope);
  524. for (Nonnull<GenericBinding*> binding : impl.deduced_parameters()) {
  525. CARBON_RETURN_IF_ERROR(ResolveNames(binding->type(), impl_scope));
  526. CARBON_RETURN_IF_ERROR(impl_scope.Add(binding->name(), binding));
  527. }
  528. CARBON_RETURN_IF_ERROR(ResolveNames(*impl.impl_type(), impl_scope));
  529. // Only add `Self` to the impl_scope if it is not already in the enclosing
  530. // scope. Add `Self` after we resolve names for the impl_type, so you
  531. // can't write something like `impl Vector(Self) as ...`. Add `Self`
  532. // before resolving names in the interface, so you can write something
  533. // like `impl VeryLongTypeName as AddWith(Self)`
  534. if (!enclosing_scope.Resolve("Self", impl.source_loc()).ok()) {
  535. CARBON_RETURN_IF_ERROR(AddExposedNames(*impl.self(), impl_scope));
  536. }
  537. CARBON_RETURN_IF_ERROR(ResolveNames(impl.interface(), impl_scope));
  538. CARBON_RETURN_IF_ERROR(
  539. ResolveMemberNames(impl.members(), impl_scope, bodies));
  540. break;
  541. }
  542. case DeclarationKind::DestructorDeclaration:
  543. case DeclarationKind::FunctionDeclaration: {
  544. auto& function = cast<CallableDeclaration>(declaration);
  545. StaticScope function_scope;
  546. function_scope.AddParent(&enclosing_scope);
  547. enclosing_scope.MarkDeclared(function.name());
  548. for (Nonnull<GenericBinding*> binding : function.deduced_parameters()) {
  549. CARBON_RETURN_IF_ERROR(ResolveNames(*binding, function_scope));
  550. }
  551. if (function.is_method()) {
  552. CARBON_RETURN_IF_ERROR(
  553. ResolveNames(function.me_pattern(), function_scope));
  554. }
  555. CARBON_RETURN_IF_ERROR(
  556. ResolveNames(function.param_pattern(), function_scope));
  557. if (function.return_term().type_expression().has_value()) {
  558. CARBON_RETURN_IF_ERROR(ResolveNames(
  559. **function.return_term().type_expression(), function_scope));
  560. }
  561. enclosing_scope.MarkUsable(function.name());
  562. if (function.body().has_value() &&
  563. bodies != ResolveFunctionBodies::Skip) {
  564. CARBON_RETURN_IF_ERROR(ResolveNames(**function.body(), function_scope));
  565. }
  566. break;
  567. }
  568. case DeclarationKind::ClassDeclaration: {
  569. auto& class_decl = cast<ClassDeclaration>(declaration);
  570. StaticScope class_scope;
  571. class_scope.AddParent(&enclosing_scope);
  572. enclosing_scope.MarkDeclared(class_decl.name());
  573. if (class_decl.base_expr().has_value()) {
  574. CARBON_RETURN_IF_ERROR(
  575. ResolveNames(**class_decl.base_expr(), class_scope));
  576. }
  577. if (class_decl.type_params().has_value()) {
  578. CARBON_RETURN_IF_ERROR(
  579. ResolveNames(**class_decl.type_params(), class_scope));
  580. }
  581. enclosing_scope.MarkUsable(class_decl.name());
  582. CARBON_RETURN_IF_ERROR(AddExposedNames(*class_decl.self(), class_scope));
  583. CARBON_RETURN_IF_ERROR(
  584. ResolveMemberNames(class_decl.members(), class_scope, bodies));
  585. break;
  586. }
  587. case DeclarationKind::MixinDeclaration: {
  588. auto& mixin_decl = cast<MixinDeclaration>(declaration);
  589. StaticScope mixin_scope;
  590. mixin_scope.AddParent(&enclosing_scope);
  591. enclosing_scope.MarkDeclared(mixin_decl.name());
  592. if (mixin_decl.params().has_value()) {
  593. CARBON_RETURN_IF_ERROR(
  594. ResolveNames(**mixin_decl.params(), mixin_scope));
  595. }
  596. enclosing_scope.MarkUsable(mixin_decl.name());
  597. CARBON_RETURN_IF_ERROR(mixin_scope.Add("Self", mixin_decl.self()));
  598. CARBON_RETURN_IF_ERROR(
  599. ResolveMemberNames(mixin_decl.members(), mixin_scope, bodies));
  600. break;
  601. }
  602. case DeclarationKind::MixDeclaration: {
  603. auto& mix_decl = cast<MixDeclaration>(declaration);
  604. CARBON_RETURN_IF_ERROR(ResolveNames(mix_decl.mixin(), enclosing_scope));
  605. break;
  606. }
  607. case DeclarationKind::ChoiceDeclaration: {
  608. auto& choice = cast<ChoiceDeclaration>(declaration);
  609. StaticScope choice_scope;
  610. choice_scope.AddParent(&enclosing_scope);
  611. enclosing_scope.MarkDeclared(choice.name());
  612. if (choice.type_params().has_value()) {
  613. CARBON_RETURN_IF_ERROR(
  614. ResolveNames(**choice.type_params(), choice_scope));
  615. }
  616. // Alternative names are never used unqualified, so we don't need to
  617. // add the alternatives to a scope, or introduce a new scope; we only
  618. // need to check for duplicates.
  619. std::set<std::string_view> alternative_names;
  620. for (Nonnull<AlternativeSignature*> alternative : choice.alternatives()) {
  621. CARBON_RETURN_IF_ERROR(
  622. ResolveNames(alternative->signature(), choice_scope));
  623. if (!alternative_names.insert(alternative->name()).second) {
  624. return ProgramError(alternative->source_loc())
  625. << "Duplicate name `" << alternative->name()
  626. << "` in choice type";
  627. }
  628. }
  629. enclosing_scope.MarkUsable(choice.name());
  630. break;
  631. }
  632. case DeclarationKind::VariableDeclaration: {
  633. auto& var = cast<VariableDeclaration>(declaration);
  634. CARBON_RETURN_IF_ERROR(ResolveNames(var.binding(), enclosing_scope));
  635. if (var.has_initializer()) {
  636. CARBON_RETURN_IF_ERROR(
  637. ResolveNames(var.initializer(), enclosing_scope));
  638. }
  639. break;
  640. }
  641. case DeclarationKind::InterfaceExtendsDeclaration: {
  642. auto& extends = cast<InterfaceExtendsDeclaration>(declaration);
  643. CARBON_RETURN_IF_ERROR(ResolveNames(*extends.base(), enclosing_scope));
  644. break;
  645. }
  646. case DeclarationKind::InterfaceImplDeclaration: {
  647. auto& impl = cast<InterfaceImplDeclaration>(declaration);
  648. CARBON_RETURN_IF_ERROR(ResolveNames(*impl.impl_type(), enclosing_scope));
  649. CARBON_RETURN_IF_ERROR(ResolveNames(*impl.constraint(), enclosing_scope));
  650. break;
  651. }
  652. case DeclarationKind::AssociatedConstantDeclaration: {
  653. auto& let = cast<AssociatedConstantDeclaration>(declaration);
  654. CARBON_RETURN_IF_ERROR(ResolveNames(let.binding(), enclosing_scope));
  655. break;
  656. }
  657. case DeclarationKind::SelfDeclaration: {
  658. CARBON_FATAL() << "Unreachable: resolving names for `Self` declaration";
  659. }
  660. case DeclarationKind::AliasDeclaration: {
  661. auto& alias = cast<AliasDeclaration>(declaration);
  662. enclosing_scope.MarkDeclared(alias.name());
  663. CARBON_RETURN_IF_ERROR(ResolveNames(alias.target(), enclosing_scope));
  664. enclosing_scope.MarkUsable(alias.name());
  665. break;
  666. }
  667. }
  668. return Success();
  669. }
  670. auto ResolveNames(AST& ast) -> ErrorOr<Success> {
  671. StaticScope file_scope;
  672. for (auto* declaration : ast.declarations) {
  673. CARBON_RETURN_IF_ERROR(AddExposedNames(*declaration, file_scope));
  674. }
  675. for (auto* declaration : ast.declarations) {
  676. CARBON_RETURN_IF_ERROR(ResolveNames(
  677. *declaration, file_scope, ResolveFunctionBodies::AfterDeclarations));
  678. }
  679. return ResolveNames(**ast.main_call, file_scope);
  680. }
  681. } // namespace Carbon