resolve_names.cpp 39 KB

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