resolve_names.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  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/ADT/DenseMap.h"
  12. #include "llvm/Support/Casting.h"
  13. #include "llvm/Support/Error.h"
  14. using llvm::cast;
  15. using llvm::dyn_cast;
  16. using llvm::isa;
  17. namespace Carbon {
  18. namespace {
  19. // The name resolver implements a pass that traverses the AST, builds scope
  20. // objects for each scope encountered, and updates all name references to point
  21. // at the value node referenced by the corresponding name.
  22. //
  23. // In scopes where names are only visible below their point of declaration
  24. // (such as block scopes in C++), this is implemented as a single pass,
  25. // recursively calling ResolveNames on the elements of the scope in order. In
  26. // scopes where names are also visible above their point of declaration (such
  27. // as class scopes in C++), this is done in three passes: first calling
  28. // AddExposedNames on each element of the scope to populate a StaticScope, and
  29. // then calling ResolveNames on each element, passing it the already-populated
  30. // StaticScope but skipping member function bodies, and finally calling
  31. // ResolvedNames again on each element, and this time resolving member function
  32. // bodies.
  33. class NameResolver {
  34. public:
  35. enum class ResolveFunctionBodies {
  36. // Do not resolve names in function bodies.
  37. Skip,
  38. // Resolve all names. When visiting a declaration with members, resolve
  39. // names in member function bodies after resolving the names in all member
  40. // declarations, as if the bodies appeared after all the declarations.
  41. AfterDeclarations,
  42. // Resolve names in function bodies immediately. This is appropriate when
  43. // the declarations of all members of enclosing classes, interfaces, and
  44. // similar have already been resolved.
  45. Immediately,
  46. };
  47. // Resolve the qualifier of the given declared name to a scope.
  48. auto ResolveQualifier(DeclaredName name, StaticScope& enclosing_scope,
  49. bool allow_undeclared = false)
  50. -> ErrorOr<Nonnull<StaticScope*>>;
  51. // Add the given name to enclosing_scope. Returns the scope in which the name
  52. // was declared.
  53. auto AddExposedName(DeclaredName name, ValueNodeView value,
  54. StaticScope& enclosing_scope, bool allow_qualified_names)
  55. -> ErrorOr<Nonnull<StaticScope*>>;
  56. // Add the names exposed by the given AST node to enclosing_scope.
  57. auto AddExposedNames(const Declaration& declaration,
  58. StaticScope& enclosing_scope,
  59. bool allow_qualified_names = false) -> ErrorOr<Success>;
  60. // Resolve all names within the given expression by looking them up in the
  61. // enclosing scope. The value returned is the value of the expression, if it
  62. // is an expression within which we can immediately do further name lookup,
  63. // such as a namespace.
  64. auto ResolveNames(Expression& expression, const StaticScope& enclosing_scope)
  65. -> ErrorOr<std::optional<ValueNodeView>>;
  66. // Resolve all names within the given where clause by looking them up in the
  67. // enclosing scope.
  68. auto ResolveNames(WhereClause& clause, const StaticScope& enclosing_scope)
  69. -> ErrorOr<Success>;
  70. // Resolve all names within the given pattern, extending the given scope with
  71. // any introduced names.
  72. auto ResolveNames(Pattern& pattern, StaticScope& enclosing_scope)
  73. -> ErrorOr<Success>;
  74. // Resolve all names within the given statement, extending the given scope
  75. // with any names introduced by declaration statements.
  76. auto ResolveNames(Statement& statement, StaticScope& enclosing_scope)
  77. -> ErrorOr<Success>;
  78. // Resolve all names within the given declaration, extending the given scope
  79. // with the any names introduced by the declaration if they're not already
  80. // present.
  81. auto ResolveNames(Declaration& declaration, StaticScope& enclosing_scope,
  82. ResolveFunctionBodies bodies) -> ErrorOr<Success>;
  83. auto ResolveMemberNames(llvm::ArrayRef<Nonnull<Declaration*>> members,
  84. StaticScope& scope, ResolveFunctionBodies bodies)
  85. -> ErrorOr<Success>;
  86. private:
  87. // Mapping from namespaces to their scopes.
  88. llvm::DenseMap<const NamespaceDeclaration*, StaticScope> namespace_scopes_;
  89. // Mapping from declarations to the scope in which they expose a name.
  90. llvm::DenseMap<const Declaration*, StaticScope*> exposed_name_scopes_;
  91. };
  92. } // namespace
  93. auto NameResolver::ResolveQualifier(DeclaredName name,
  94. StaticScope& enclosing_scope,
  95. bool allow_undeclared)
  96. -> ErrorOr<Nonnull<StaticScope*>> {
  97. Nonnull<StaticScope*> scope = &enclosing_scope;
  98. std::optional<ValueNodeView> scope_node;
  99. for (const auto& [loc, qualifier] : name.qualifiers()) {
  100. // TODO: If we permit qualified names anywhere other than the top level, we
  101. // will need to decide whether the first name in the qualifier is looked up
  102. // only in the innermost enclosing scope or in all enclosing scopes.
  103. CARBON_ASSIGN_OR_RETURN(
  104. ValueNodeView node,
  105. scope->ResolveHere(scope_node, qualifier, loc, allow_undeclared));
  106. scope_node = node;
  107. if (const auto* namespace_decl =
  108. dyn_cast<NamespaceDeclaration>(&node.base())) {
  109. scope = &namespace_scopes_[namespace_decl];
  110. } else {
  111. return ProgramError(name.source_loc())
  112. << PrintAsID(node.base()) << " cannot be used as a name qualifier";
  113. }
  114. }
  115. return scope;
  116. }
  117. auto NameResolver::AddExposedName(DeclaredName name, ValueNodeView value,
  118. StaticScope& enclosing_scope,
  119. bool allow_qualified_names)
  120. -> ErrorOr<Nonnull<StaticScope*>> {
  121. if (name.is_qualified() && !allow_qualified_names) {
  122. return ProgramError(name.source_loc())
  123. << "qualified declaration names are not permitted in this context";
  124. }
  125. // We are just collecting names at this stage, so nothing is marked as
  126. // declared yet. Therefore we don't complain if the qualifier contains a
  127. // known but not declared namespace name.
  128. CARBON_ASSIGN_OR_RETURN(
  129. Nonnull<StaticScope*> scope,
  130. ResolveQualifier(name, enclosing_scope, /*allow_undeclared=*/true));
  131. CARBON_RETURN_IF_ERROR(scope->Add(
  132. name.inner_name(), value, StaticScope::NameStatus::KnownButNotDeclared));
  133. return scope;
  134. }
  135. auto NameResolver::AddExposedNames(const Declaration& declaration,
  136. StaticScope& enclosing_scope,
  137. bool allow_qualified_names)
  138. -> ErrorOr<Success> {
  139. switch (declaration.kind()) {
  140. case DeclarationKind::NamespaceDeclaration: {
  141. const auto& namespace_decl = cast<NamespaceDeclaration>(declaration);
  142. CARBON_ASSIGN_OR_RETURN(
  143. Nonnull<StaticScope*> scope,
  144. AddExposedName(namespace_decl.name(), &namespace_decl,
  145. enclosing_scope, allow_qualified_names));
  146. namespace_scopes_.try_emplace(&namespace_decl, scope);
  147. break;
  148. }
  149. case DeclarationKind::InterfaceDeclaration:
  150. case DeclarationKind::ConstraintDeclaration: {
  151. const auto& iface_decl = cast<ConstraintTypeDeclaration>(declaration);
  152. CARBON_RETURN_IF_ERROR(AddExposedName(iface_decl.name(), &iface_decl,
  153. enclosing_scope,
  154. allow_qualified_names));
  155. break;
  156. }
  157. case DeclarationKind::DestructorDeclaration: {
  158. // TODO: It should not be possible to name the destructor by unqualified
  159. // name.
  160. const auto& func = cast<DestructorDeclaration>(declaration);
  161. // TODO: Add support for qualified destructor declarations. Currently the
  162. // syntax for this is
  163. // destructor Class [self: Self] { ... }
  164. // but see #2567.
  165. CARBON_RETURN_IF_ERROR(enclosing_scope.Add(
  166. "destructor", &func, StaticScope::NameStatus::KnownButNotDeclared));
  167. break;
  168. }
  169. case DeclarationKind::FunctionDeclaration: {
  170. const auto& func = cast<FunctionDeclaration>(declaration);
  171. CARBON_RETURN_IF_ERROR(AddExposedName(func.name(), &func, enclosing_scope,
  172. allow_qualified_names));
  173. break;
  174. }
  175. case DeclarationKind::ClassDeclaration: {
  176. const auto& class_decl = cast<ClassDeclaration>(declaration);
  177. CARBON_RETURN_IF_ERROR(AddExposedName(class_decl.name(), &class_decl,
  178. enclosing_scope,
  179. allow_qualified_names));
  180. break;
  181. }
  182. case DeclarationKind::MixinDeclaration: {
  183. const auto& mixin_decl = cast<MixinDeclaration>(declaration);
  184. CARBON_RETURN_IF_ERROR(AddExposedName(mixin_decl.name(), &mixin_decl,
  185. enclosing_scope,
  186. allow_qualified_names));
  187. break;
  188. }
  189. case DeclarationKind::ChoiceDeclaration: {
  190. const auto& choice = cast<ChoiceDeclaration>(declaration);
  191. CARBON_RETURN_IF_ERROR(AddExposedName(
  192. choice.name(), &choice, enclosing_scope, allow_qualified_names));
  193. break;
  194. }
  195. case DeclarationKind::VariableDeclaration: {
  196. const auto& var = cast<VariableDeclaration>(declaration);
  197. if (var.binding().name() != AnonymousName) {
  198. CARBON_RETURN_IF_ERROR(
  199. enclosing_scope.Add(var.binding().name(), &var.binding(),
  200. StaticScope::NameStatus::KnownButNotDeclared));
  201. }
  202. break;
  203. }
  204. case DeclarationKind::AssociatedConstantDeclaration: {
  205. const auto& let = cast<AssociatedConstantDeclaration>(declaration);
  206. if (let.binding().name() != AnonymousName) {
  207. CARBON_RETURN_IF_ERROR(enclosing_scope.Add(let.binding().name(), &let));
  208. }
  209. break;
  210. }
  211. case DeclarationKind::SelfDeclaration: {
  212. const auto& self = cast<SelfDeclaration>(declaration);
  213. CARBON_RETURN_IF_ERROR(enclosing_scope.Add("Self", &self));
  214. break;
  215. }
  216. case DeclarationKind::AliasDeclaration: {
  217. const auto& alias = cast<AliasDeclaration>(declaration);
  218. CARBON_RETURN_IF_ERROR(AddExposedName(
  219. alias.name(), &alias, enclosing_scope, allow_qualified_names));
  220. break;
  221. }
  222. case DeclarationKind::ImplDeclaration:
  223. case DeclarationKind::MatchFirstDeclaration:
  224. case DeclarationKind::MixDeclaration:
  225. case DeclarationKind::InterfaceExtendsDeclaration:
  226. case DeclarationKind::InterfaceImplDeclaration: {
  227. // These declarations don't have a name to expose.
  228. break;
  229. }
  230. }
  231. return Success();
  232. }
  233. auto NameResolver::ResolveNames(Expression& expression,
  234. const StaticScope& enclosing_scope)
  235. -> ErrorOr<std::optional<ValueNodeView>> {
  236. switch (expression.kind()) {
  237. case ExpressionKind::CallExpression: {
  238. auto& call = cast<CallExpression>(expression);
  239. CARBON_RETURN_IF_ERROR(ResolveNames(call.function(), enclosing_scope));
  240. CARBON_RETURN_IF_ERROR(ResolveNames(call.argument(), enclosing_scope));
  241. break;
  242. }
  243. case ExpressionKind::FunctionTypeLiteral: {
  244. auto& fun_type = cast<FunctionTypeLiteral>(expression);
  245. CARBON_RETURN_IF_ERROR(
  246. ResolveNames(fun_type.parameter(), enclosing_scope));
  247. CARBON_RETURN_IF_ERROR(
  248. ResolveNames(fun_type.return_type(), enclosing_scope));
  249. break;
  250. }
  251. case ExpressionKind::SimpleMemberAccessExpression: {
  252. auto& access = cast<SimpleMemberAccessExpression>(expression);
  253. CARBON_ASSIGN_OR_RETURN(std::optional<ValueNodeView> scope,
  254. ResolveNames(access.object(), enclosing_scope));
  255. // If the left-hand side of the `.` is a namespace, resolve the name.
  256. // TODO: Look through aliases.
  257. if (scope && isa<NamespaceDeclaration>(scope->base())) {
  258. auto ns_it =
  259. namespace_scopes_.find(&cast<NamespaceDeclaration>(scope->base()));
  260. CARBON_CHECK(ns_it != namespace_scopes_.end())
  261. << "name resolved to undeclared namespace";
  262. CARBON_ASSIGN_OR_RETURN(
  263. const auto value_node,
  264. ns_it->second.ResolveHere(scope, access.member_name(),
  265. access.source_loc(),
  266. /*allow_undeclared=*/false));
  267. access.set_value_node(value_node);
  268. return {value_node};
  269. }
  270. break;
  271. }
  272. case ExpressionKind::CompoundMemberAccessExpression: {
  273. auto& access = cast<CompoundMemberAccessExpression>(expression);
  274. CARBON_RETURN_IF_ERROR(ResolveNames(access.object(), enclosing_scope));
  275. CARBON_RETURN_IF_ERROR(ResolveNames(access.path(), enclosing_scope));
  276. break;
  277. }
  278. case ExpressionKind::IndexExpression: {
  279. auto& index = cast<IndexExpression>(expression);
  280. CARBON_RETURN_IF_ERROR(ResolveNames(index.object(), enclosing_scope));
  281. CARBON_RETURN_IF_ERROR(ResolveNames(index.offset(), enclosing_scope));
  282. break;
  283. }
  284. case ExpressionKind::OperatorExpression:
  285. for (Nonnull<Expression*> operand :
  286. cast<OperatorExpression>(expression).arguments()) {
  287. CARBON_RETURN_IF_ERROR(ResolveNames(*operand, enclosing_scope));
  288. }
  289. break;
  290. case ExpressionKind::TupleLiteral:
  291. for (Nonnull<Expression*> field :
  292. cast<TupleLiteral>(expression).fields()) {
  293. CARBON_RETURN_IF_ERROR(ResolveNames(*field, enclosing_scope));
  294. }
  295. break;
  296. case ExpressionKind::StructLiteral:
  297. for (FieldInitializer& init : cast<StructLiteral>(expression).fields()) {
  298. CARBON_RETURN_IF_ERROR(
  299. ResolveNames(init.expression(), enclosing_scope));
  300. }
  301. break;
  302. case ExpressionKind::StructTypeLiteral:
  303. for (FieldInitializer& init :
  304. cast<StructTypeLiteral>(expression).fields()) {
  305. CARBON_RETURN_IF_ERROR(
  306. ResolveNames(init.expression(), enclosing_scope));
  307. }
  308. break;
  309. case ExpressionKind::IdentifierExpression: {
  310. auto& identifier = cast<IdentifierExpression>(expression);
  311. CARBON_ASSIGN_OR_RETURN(
  312. const auto value_node,
  313. enclosing_scope.Resolve(identifier.name(), identifier.source_loc()));
  314. identifier.set_value_node(value_node);
  315. return {value_node};
  316. }
  317. case ExpressionKind::DotSelfExpression: {
  318. auto& dot_self = cast<DotSelfExpression>(expression);
  319. CARBON_ASSIGN_OR_RETURN(
  320. const auto value_node,
  321. enclosing_scope.Resolve(".Self", dot_self.source_loc()));
  322. dot_self.set_self_binding(const_cast<GenericBinding*>(
  323. &cast<GenericBinding>(value_node.base())));
  324. break;
  325. }
  326. case ExpressionKind::IntrinsicExpression:
  327. CARBON_RETURN_IF_ERROR(ResolveNames(
  328. cast<IntrinsicExpression>(expression).args(), enclosing_scope));
  329. break;
  330. case ExpressionKind::IfExpression: {
  331. auto& if_expr = cast<IfExpression>(expression);
  332. CARBON_RETURN_IF_ERROR(
  333. ResolveNames(if_expr.condition(), enclosing_scope));
  334. CARBON_RETURN_IF_ERROR(
  335. ResolveNames(if_expr.then_expression(), enclosing_scope));
  336. CARBON_RETURN_IF_ERROR(
  337. ResolveNames(if_expr.else_expression(), enclosing_scope));
  338. break;
  339. }
  340. case ExpressionKind::WhereExpression: {
  341. auto& where = cast<WhereExpression>(expression);
  342. CARBON_RETURN_IF_ERROR(
  343. ResolveNames(where.self_binding().type(), enclosing_scope));
  344. // If we're already in a `.Self` context, remember it so that we can
  345. // reuse its value for the inner `.Self`.
  346. if (auto enclosing_dot_self =
  347. enclosing_scope.Resolve(".Self", where.source_loc());
  348. enclosing_dot_self.ok()) {
  349. where.set_enclosing_dot_self(
  350. &cast<GenericBinding>(enclosing_dot_self->base()));
  351. }
  352. // Introduce `.Self` into scope on the right of the `where` keyword.
  353. StaticScope where_scope(&enclosing_scope);
  354. CARBON_RETURN_IF_ERROR(where_scope.Add(".Self", &where.self_binding()));
  355. for (Nonnull<WhereClause*> clause : where.clauses()) {
  356. CARBON_RETURN_IF_ERROR(ResolveNames(*clause, where_scope));
  357. }
  358. break;
  359. }
  360. case ExpressionKind::ArrayTypeLiteral: {
  361. auto& array_literal = cast<ArrayTypeLiteral>(expression);
  362. CARBON_RETURN_IF_ERROR(ResolveNames(
  363. array_literal.element_type_expression(), enclosing_scope));
  364. CARBON_RETURN_IF_ERROR(
  365. ResolveNames(array_literal.size_expression(), enclosing_scope));
  366. break;
  367. }
  368. case ExpressionKind::BoolTypeLiteral:
  369. case ExpressionKind::BoolLiteral:
  370. case ExpressionKind::IntTypeLiteral:
  371. case ExpressionKind::ContinuationTypeLiteral:
  372. case ExpressionKind::IntLiteral:
  373. case ExpressionKind::StringLiteral:
  374. case ExpressionKind::StringTypeLiteral:
  375. case ExpressionKind::TypeTypeLiteral:
  376. break;
  377. case ExpressionKind::ValueLiteral:
  378. case ExpressionKind::BuiltinConvertExpression:
  379. case ExpressionKind::BaseAccessExpression:
  380. CARBON_FATAL() << "should not exist before type checking";
  381. case ExpressionKind::UnimplementedExpression:
  382. return ProgramError(expression.source_loc()) << "Unimplemented";
  383. }
  384. return {std::nullopt};
  385. }
  386. auto NameResolver::ResolveNames(WhereClause& clause,
  387. const StaticScope& enclosing_scope)
  388. -> ErrorOr<Success> {
  389. switch (clause.kind()) {
  390. case WhereClauseKind::IsWhereClause: {
  391. auto& is_clause = cast<IsWhereClause>(clause);
  392. CARBON_RETURN_IF_ERROR(ResolveNames(is_clause.type(), enclosing_scope));
  393. CARBON_RETURN_IF_ERROR(
  394. ResolveNames(is_clause.constraint(), enclosing_scope));
  395. break;
  396. }
  397. case WhereClauseKind::EqualsWhereClause: {
  398. auto& equals_clause = cast<EqualsWhereClause>(clause);
  399. CARBON_RETURN_IF_ERROR(
  400. ResolveNames(equals_clause.lhs(), enclosing_scope));
  401. CARBON_RETURN_IF_ERROR(
  402. ResolveNames(equals_clause.rhs(), enclosing_scope));
  403. break;
  404. }
  405. case WhereClauseKind::RewriteWhereClause: {
  406. auto& rewrite_clause = cast<RewriteWhereClause>(clause);
  407. CARBON_RETURN_IF_ERROR(
  408. ResolveNames(rewrite_clause.replacement(), enclosing_scope));
  409. break;
  410. }
  411. }
  412. return Success();
  413. }
  414. auto NameResolver::ResolveNames(Pattern& pattern, StaticScope& enclosing_scope)
  415. -> ErrorOr<Success> {
  416. switch (pattern.kind()) {
  417. case PatternKind::BindingPattern: {
  418. auto& binding = cast<BindingPattern>(pattern);
  419. CARBON_RETURN_IF_ERROR(ResolveNames(binding.type(), enclosing_scope));
  420. if (binding.name() != AnonymousName) {
  421. CARBON_RETURN_IF_ERROR(enclosing_scope.Add(binding.name(), &binding));
  422. }
  423. break;
  424. }
  425. case PatternKind::GenericBinding: {
  426. auto& binding = cast<GenericBinding>(pattern);
  427. // `.Self` is in scope in the context of the type.
  428. StaticScope self_scope(&enclosing_scope);
  429. CARBON_RETURN_IF_ERROR(self_scope.Add(".Self", &binding));
  430. CARBON_RETURN_IF_ERROR(ResolveNames(binding.type(), self_scope));
  431. if (binding.name() != AnonymousName) {
  432. CARBON_RETURN_IF_ERROR(enclosing_scope.Add(binding.name(), &binding));
  433. }
  434. break;
  435. }
  436. case PatternKind::TuplePattern:
  437. for (Nonnull<Pattern*> field : cast<TuplePattern>(pattern).fields()) {
  438. CARBON_RETURN_IF_ERROR(ResolveNames(*field, enclosing_scope));
  439. }
  440. break;
  441. case PatternKind::AlternativePattern: {
  442. auto& alternative = cast<AlternativePattern>(pattern);
  443. CARBON_RETURN_IF_ERROR(
  444. ResolveNames(alternative.choice_type(), enclosing_scope));
  445. CARBON_RETURN_IF_ERROR(
  446. ResolveNames(alternative.arguments(), enclosing_scope));
  447. break;
  448. }
  449. case PatternKind::ExpressionPattern:
  450. CARBON_RETURN_IF_ERROR(ResolveNames(
  451. cast<ExpressionPattern>(pattern).expression(), enclosing_scope));
  452. break;
  453. case PatternKind::AutoPattern:
  454. break;
  455. case PatternKind::VarPattern:
  456. CARBON_RETURN_IF_ERROR(
  457. ResolveNames(cast<VarPattern>(pattern).pattern(), enclosing_scope));
  458. break;
  459. case PatternKind::AddrPattern:
  460. CARBON_RETURN_IF_ERROR(
  461. ResolveNames(cast<AddrPattern>(pattern).binding(), enclosing_scope));
  462. break;
  463. }
  464. return Success();
  465. }
  466. auto NameResolver::ResolveNames(Statement& statement,
  467. StaticScope& enclosing_scope)
  468. -> ErrorOr<Success> {
  469. switch (statement.kind()) {
  470. case StatementKind::ExpressionStatement:
  471. CARBON_RETURN_IF_ERROR(ResolveNames(
  472. cast<ExpressionStatement>(statement).expression(), enclosing_scope));
  473. break;
  474. case StatementKind::Assign: {
  475. auto& assign = cast<Assign>(statement);
  476. CARBON_RETURN_IF_ERROR(ResolveNames(assign.lhs(), enclosing_scope));
  477. CARBON_RETURN_IF_ERROR(ResolveNames(assign.rhs(), enclosing_scope));
  478. break;
  479. }
  480. case StatementKind::IncrementDecrement: {
  481. auto& inc_dec = cast<IncrementDecrement>(statement);
  482. CARBON_RETURN_IF_ERROR(ResolveNames(inc_dec.argument(), enclosing_scope));
  483. break;
  484. }
  485. case StatementKind::VariableDefinition: {
  486. auto& def = cast<VariableDefinition>(statement);
  487. if (def.has_init()) {
  488. CARBON_RETURN_IF_ERROR(ResolveNames(def.init(), enclosing_scope));
  489. }
  490. CARBON_RETURN_IF_ERROR(ResolveNames(def.pattern(), enclosing_scope));
  491. if (def.is_returned()) {
  492. CARBON_CHECK(def.pattern().kind() == PatternKind::BindingPattern)
  493. << def.pattern().source_loc()
  494. << "returned var definition can only be a binding pattern";
  495. CARBON_RETURN_IF_ERROR(enclosing_scope.AddReturnedVar(
  496. ValueNodeView(&cast<BindingPattern>(def.pattern()))));
  497. }
  498. break;
  499. }
  500. case StatementKind::If: {
  501. auto& if_stmt = cast<If>(statement);
  502. CARBON_RETURN_IF_ERROR(
  503. ResolveNames(if_stmt.condition(), enclosing_scope));
  504. CARBON_RETURN_IF_ERROR(
  505. ResolveNames(if_stmt.then_block(), enclosing_scope));
  506. if (if_stmt.else_block().has_value()) {
  507. CARBON_RETURN_IF_ERROR(
  508. ResolveNames(**if_stmt.else_block(), enclosing_scope));
  509. }
  510. break;
  511. }
  512. case StatementKind::ReturnVar: {
  513. auto& ret_var_stmt = cast<ReturnVar>(statement);
  514. std::optional<ValueNodeView> returned_var_def_view =
  515. enclosing_scope.ResolveReturned();
  516. if (!returned_var_def_view.has_value()) {
  517. return ProgramError(ret_var_stmt.source_loc())
  518. << "`return var` is not allowed without a returned var defined "
  519. "in scope.";
  520. }
  521. ret_var_stmt.set_value_node(*returned_var_def_view);
  522. break;
  523. }
  524. case StatementKind::ReturnExpression: {
  525. auto& ret_exp_stmt = cast<ReturnExpression>(statement);
  526. std::optional<ValueNodeView> returned_var_def_view =
  527. enclosing_scope.ResolveReturned();
  528. if (returned_var_def_view.has_value()) {
  529. return ProgramError(ret_exp_stmt.source_loc())
  530. << "`return <expression>` is not allowed with a returned var "
  531. "defined in scope: "
  532. << returned_var_def_view->base().source_loc();
  533. }
  534. CARBON_RETURN_IF_ERROR(
  535. ResolveNames(ret_exp_stmt.expression(), enclosing_scope));
  536. break;
  537. }
  538. case StatementKind::Block: {
  539. auto& block = cast<Block>(statement);
  540. StaticScope block_scope(&enclosing_scope);
  541. for (Nonnull<Statement*> sub_statement : block.statements()) {
  542. CARBON_RETURN_IF_ERROR(ResolveNames(*sub_statement, block_scope));
  543. }
  544. break;
  545. }
  546. case StatementKind::While: {
  547. auto& while_stmt = cast<While>(statement);
  548. CARBON_RETURN_IF_ERROR(
  549. ResolveNames(while_stmt.condition(), enclosing_scope));
  550. CARBON_RETURN_IF_ERROR(ResolveNames(while_stmt.body(), enclosing_scope));
  551. break;
  552. }
  553. case StatementKind::For: {
  554. StaticScope statement_scope(&enclosing_scope);
  555. auto& for_stmt = cast<For>(statement);
  556. CARBON_RETURN_IF_ERROR(
  557. ResolveNames(for_stmt.loop_target(), statement_scope));
  558. CARBON_RETURN_IF_ERROR(
  559. ResolveNames(for_stmt.variable_declaration(), statement_scope));
  560. CARBON_RETURN_IF_ERROR(ResolveNames(for_stmt.body(), statement_scope));
  561. break;
  562. }
  563. case StatementKind::Match: {
  564. auto& match = cast<Match>(statement);
  565. CARBON_RETURN_IF_ERROR(ResolveNames(match.expression(), enclosing_scope));
  566. for (Match::Clause& clause : match.clauses()) {
  567. StaticScope clause_scope(&enclosing_scope);
  568. CARBON_RETURN_IF_ERROR(ResolveNames(clause.pattern(), clause_scope));
  569. CARBON_RETURN_IF_ERROR(ResolveNames(clause.statement(), clause_scope));
  570. }
  571. break;
  572. }
  573. case StatementKind::Continuation: {
  574. auto& continuation = cast<Continuation>(statement);
  575. CARBON_RETURN_IF_ERROR(
  576. enclosing_scope.Add(continuation.name(), &continuation,
  577. StaticScope::NameStatus::DeclaredButNotUsable));
  578. StaticScope continuation_scope(&enclosing_scope);
  579. CARBON_RETURN_IF_ERROR(ResolveNames(cast<Continuation>(statement).body(),
  580. continuation_scope));
  581. enclosing_scope.MarkUsable(continuation.name());
  582. break;
  583. }
  584. case StatementKind::Run:
  585. CARBON_RETURN_IF_ERROR(
  586. ResolveNames(cast<Run>(statement).argument(), enclosing_scope));
  587. break;
  588. case StatementKind::Await:
  589. case StatementKind::Break:
  590. case StatementKind::Continue:
  591. break;
  592. }
  593. return Success();
  594. }
  595. auto NameResolver::ResolveMemberNames(
  596. llvm::ArrayRef<Nonnull<Declaration*>> members, StaticScope& scope,
  597. ResolveFunctionBodies bodies) -> ErrorOr<Success> {
  598. for (Nonnull<Declaration*> member : members) {
  599. CARBON_RETURN_IF_ERROR(AddExposedNames(*member, scope));
  600. }
  601. if (bodies != ResolveFunctionBodies::Immediately) {
  602. for (Nonnull<Declaration*> member : members) {
  603. CARBON_RETURN_IF_ERROR(
  604. ResolveNames(*member, scope, ResolveFunctionBodies::Skip));
  605. }
  606. }
  607. if (bodies != ResolveFunctionBodies::Skip) {
  608. for (Nonnull<Declaration*> member : members) {
  609. CARBON_RETURN_IF_ERROR(
  610. ResolveNames(*member, scope, ResolveFunctionBodies::Immediately));
  611. }
  612. }
  613. return Success();
  614. }
  615. auto NameResolver::ResolveNames(Declaration& declaration,
  616. StaticScope& enclosing_scope,
  617. ResolveFunctionBodies bodies)
  618. -> ErrorOr<Success> {
  619. switch (declaration.kind()) {
  620. case DeclarationKind::NamespaceDeclaration: {
  621. auto& namespace_decl = cast<NamespaceDeclaration>(declaration);
  622. CARBON_ASSIGN_OR_RETURN(
  623. Nonnull<StaticScope*> scope,
  624. ResolveQualifier(namespace_decl.name(), enclosing_scope));
  625. scope->MarkUsable(namespace_decl.name().inner_name());
  626. break;
  627. }
  628. case DeclarationKind::InterfaceDeclaration:
  629. case DeclarationKind::ConstraintDeclaration: {
  630. auto& iface = cast<ConstraintTypeDeclaration>(declaration);
  631. CARBON_ASSIGN_OR_RETURN(Nonnull<StaticScope*> scope,
  632. ResolveQualifier(iface.name(), enclosing_scope));
  633. StaticScope iface_scope(scope);
  634. scope->MarkDeclared(iface.name().inner_name());
  635. if (iface.params().has_value()) {
  636. CARBON_RETURN_IF_ERROR(ResolveNames(**iface.params(), iface_scope));
  637. }
  638. scope->MarkUsable(iface.name().inner_name());
  639. // Don't resolve names in the type of the self binding. The
  640. // ConstraintTypeDeclaration constructor already did that.
  641. CARBON_RETURN_IF_ERROR(iface_scope.Add("Self", iface.self()));
  642. CARBON_RETURN_IF_ERROR(
  643. ResolveMemberNames(iface.members(), iface_scope, bodies));
  644. break;
  645. }
  646. case DeclarationKind::ImplDeclaration: {
  647. auto& impl = cast<ImplDeclaration>(declaration);
  648. StaticScope impl_scope(&enclosing_scope);
  649. for (Nonnull<GenericBinding*> binding : impl.deduced_parameters()) {
  650. CARBON_RETURN_IF_ERROR(ResolveNames(binding->type(), impl_scope));
  651. CARBON_RETURN_IF_ERROR(impl_scope.Add(binding->name(), binding));
  652. }
  653. CARBON_RETURN_IF_ERROR(ResolveNames(*impl.impl_type(), impl_scope));
  654. // Only add `Self` to the impl_scope if it is not already in the enclosing
  655. // scope. Add `Self` after we resolve names for the impl_type, so you
  656. // can't write something like `impl Vector(Self) as ...`. Add `Self`
  657. // before resolving names in the interface, so you can write something
  658. // like `impl VeryLongTypeName as AddWith(Self)`
  659. if (!enclosing_scope.Resolve("Self", impl.source_loc()).ok()) {
  660. CARBON_RETURN_IF_ERROR(AddExposedNames(*impl.self(), impl_scope));
  661. }
  662. CARBON_RETURN_IF_ERROR(ResolveNames(impl.interface(), impl_scope));
  663. CARBON_RETURN_IF_ERROR(
  664. ResolveMemberNames(impl.members(), impl_scope, bodies));
  665. break;
  666. }
  667. case DeclarationKind::MatchFirstDeclaration: {
  668. // A `match_first` declaration does not introduce a scope.
  669. for (auto* impl : cast<MatchFirstDeclaration>(declaration).impls()) {
  670. CARBON_RETURN_IF_ERROR(ResolveNames(*impl, enclosing_scope, bodies));
  671. }
  672. break;
  673. }
  674. case DeclarationKind::DestructorDeclaration:
  675. case DeclarationKind::FunctionDeclaration: {
  676. auto& function = cast<CallableDeclaration>(declaration);
  677. // TODO: Destructors should track their qualified name.
  678. const DeclaredName& name =
  679. isa<FunctionDeclaration>(declaration)
  680. ? cast<FunctionDeclaration>(declaration).name()
  681. : DeclaredName(function.source_loc(), "destructor");
  682. CARBON_ASSIGN_OR_RETURN(Nonnull<StaticScope*> scope,
  683. ResolveQualifier(name, enclosing_scope));
  684. StaticScope function_scope(scope);
  685. scope->MarkDeclared(name.inner_name());
  686. for (Nonnull<GenericBinding*> binding : function.deduced_parameters()) {
  687. CARBON_RETURN_IF_ERROR(ResolveNames(*binding, function_scope));
  688. }
  689. if (function.is_method()) {
  690. CARBON_RETURN_IF_ERROR(
  691. ResolveNames(function.self_pattern(), function_scope));
  692. }
  693. CARBON_RETURN_IF_ERROR(
  694. ResolveNames(function.param_pattern(), function_scope));
  695. if (function.return_term().type_expression().has_value()) {
  696. CARBON_RETURN_IF_ERROR(ResolveNames(
  697. **function.return_term().type_expression(), function_scope));
  698. }
  699. scope->MarkUsable(name.inner_name());
  700. if (function.body().has_value() &&
  701. bodies != ResolveFunctionBodies::Skip) {
  702. CARBON_RETURN_IF_ERROR(ResolveNames(**function.body(), function_scope));
  703. }
  704. break;
  705. }
  706. case DeclarationKind::ClassDeclaration: {
  707. auto& class_decl = cast<ClassDeclaration>(declaration);
  708. CARBON_ASSIGN_OR_RETURN(
  709. Nonnull<StaticScope*> scope,
  710. ResolveQualifier(class_decl.name(), enclosing_scope));
  711. StaticScope class_scope(scope);
  712. scope->MarkDeclared(class_decl.name().inner_name());
  713. if (class_decl.base_expr().has_value()) {
  714. CARBON_RETURN_IF_ERROR(
  715. ResolveNames(**class_decl.base_expr(), class_scope));
  716. }
  717. if (class_decl.type_params().has_value()) {
  718. CARBON_RETURN_IF_ERROR(
  719. ResolveNames(**class_decl.type_params(), class_scope));
  720. }
  721. scope->MarkUsable(class_decl.name().inner_name());
  722. CARBON_RETURN_IF_ERROR(AddExposedNames(*class_decl.self(), class_scope));
  723. CARBON_RETURN_IF_ERROR(
  724. ResolveMemberNames(class_decl.members(), class_scope, bodies));
  725. break;
  726. }
  727. case DeclarationKind::MixinDeclaration: {
  728. auto& mixin_decl = cast<MixinDeclaration>(declaration);
  729. CARBON_ASSIGN_OR_RETURN(
  730. Nonnull<StaticScope*> scope,
  731. ResolveQualifier(mixin_decl.name(), enclosing_scope));
  732. StaticScope mixin_scope(scope);
  733. scope->MarkDeclared(mixin_decl.name().inner_name());
  734. if (mixin_decl.params().has_value()) {
  735. CARBON_RETURN_IF_ERROR(
  736. ResolveNames(**mixin_decl.params(), mixin_scope));
  737. }
  738. scope->MarkUsable(mixin_decl.name().inner_name());
  739. CARBON_RETURN_IF_ERROR(mixin_scope.Add("Self", mixin_decl.self()));
  740. CARBON_RETURN_IF_ERROR(
  741. ResolveMemberNames(mixin_decl.members(), mixin_scope, bodies));
  742. break;
  743. }
  744. case DeclarationKind::MixDeclaration: {
  745. auto& mix_decl = cast<MixDeclaration>(declaration);
  746. CARBON_RETURN_IF_ERROR(ResolveNames(mix_decl.mixin(), enclosing_scope));
  747. break;
  748. }
  749. case DeclarationKind::ChoiceDeclaration: {
  750. auto& choice = cast<ChoiceDeclaration>(declaration);
  751. CARBON_ASSIGN_OR_RETURN(Nonnull<StaticScope*> scope,
  752. ResolveQualifier(choice.name(), enclosing_scope));
  753. StaticScope choice_scope(scope);
  754. scope->MarkDeclared(choice.name().inner_name());
  755. if (choice.type_params().has_value()) {
  756. CARBON_RETURN_IF_ERROR(
  757. ResolveNames(**choice.type_params(), choice_scope));
  758. }
  759. // Alternative names are never used unqualified, so we don't need to
  760. // add the alternatives to a scope, or introduce a new scope; we only
  761. // need to check for duplicates.
  762. std::set<std::string_view> alternative_names;
  763. for (Nonnull<AlternativeSignature*> alternative : choice.alternatives()) {
  764. if (auto params = alternative->parameters()) {
  765. CARBON_RETURN_IF_ERROR(ResolveNames(**params, choice_scope));
  766. }
  767. if (!alternative_names.insert(alternative->name()).second) {
  768. return ProgramError(alternative->source_loc())
  769. << "Duplicate name `" << alternative->name()
  770. << "` in choice type";
  771. }
  772. }
  773. scope->MarkUsable(choice.name().inner_name());
  774. break;
  775. }
  776. case DeclarationKind::VariableDeclaration: {
  777. auto& var = cast<VariableDeclaration>(declaration);
  778. CARBON_RETURN_IF_ERROR(ResolveNames(var.binding(), enclosing_scope));
  779. if (var.has_initializer()) {
  780. CARBON_RETURN_IF_ERROR(
  781. ResolveNames(var.initializer(), enclosing_scope));
  782. }
  783. break;
  784. }
  785. case DeclarationKind::InterfaceExtendsDeclaration: {
  786. auto& extends = cast<InterfaceExtendsDeclaration>(declaration);
  787. CARBON_RETURN_IF_ERROR(ResolveNames(*extends.base(), enclosing_scope));
  788. break;
  789. }
  790. case DeclarationKind::InterfaceImplDeclaration: {
  791. auto& impl = cast<InterfaceImplDeclaration>(declaration);
  792. CARBON_RETURN_IF_ERROR(ResolveNames(*impl.impl_type(), enclosing_scope));
  793. CARBON_RETURN_IF_ERROR(ResolveNames(*impl.constraint(), enclosing_scope));
  794. break;
  795. }
  796. case DeclarationKind::AssociatedConstantDeclaration: {
  797. auto& let = cast<AssociatedConstantDeclaration>(declaration);
  798. StaticScope constant_scope(&enclosing_scope);
  799. CARBON_RETURN_IF_ERROR(ResolveNames(let.binding(), constant_scope));
  800. break;
  801. }
  802. case DeclarationKind::SelfDeclaration: {
  803. CARBON_FATAL() << "Unreachable: resolving names for `Self` declaration";
  804. }
  805. case DeclarationKind::AliasDeclaration: {
  806. auto& alias = cast<AliasDeclaration>(declaration);
  807. CARBON_ASSIGN_OR_RETURN(Nonnull<StaticScope*> scope,
  808. ResolveQualifier(alias.name(), enclosing_scope));
  809. scope->MarkDeclared(alias.name().inner_name());
  810. CARBON_RETURN_IF_ERROR(ResolveNames(alias.target(), *scope));
  811. scope->MarkUsable(alias.name().inner_name());
  812. break;
  813. }
  814. }
  815. return Success();
  816. }
  817. auto ResolveNames(AST& ast) -> ErrorOr<Success> {
  818. NameResolver resolver;
  819. StaticScope file_scope;
  820. for (auto* declaration : ast.declarations) {
  821. CARBON_RETURN_IF_ERROR(resolver.AddExposedNames(
  822. *declaration, file_scope, /*allow_qualified_names=*/true));
  823. }
  824. for (auto* declaration : ast.declarations) {
  825. CARBON_RETURN_IF_ERROR(resolver.ResolveNames(
  826. *declaration, file_scope,
  827. NameResolver::ResolveFunctionBodies::AfterDeclarations));
  828. }
  829. CARBON_RETURN_IF_ERROR(resolver.ResolveNames(**ast.main_call, file_scope));
  830. return Success();
  831. }
  832. } // namespace Carbon