resolve_names.cpp 28 KB

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