resolve_names.cpp 24 KB

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