resolve_names.cpp 29 KB

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