resolve_names.cpp 27 KB

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