resolve_names.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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::InterfaceExtendDeclaration:
  245. case DeclarationKind::InterfaceRequireDeclaration:
  246. case DeclarationKind::ExtendBaseDeclaration: {
  247. // These declarations don't have a name to expose.
  248. break;
  249. }
  250. }
  251. return Success();
  252. }
  253. auto NameResolver::ResolveNames(Expression& expression,
  254. const StaticScope& enclosing_scope)
  255. -> ErrorOr<std::optional<ValueNodeView>> {
  256. return RunWithExtraStack(
  257. [&]() { return ResolveNamesImpl(expression, enclosing_scope); });
  258. }
  259. auto NameResolver::ResolveNamesImpl(Expression& expression,
  260. const StaticScope& enclosing_scope)
  261. -> ErrorOr<std::optional<ValueNodeView>> {
  262. switch (expression.kind()) {
  263. case ExpressionKind::CallExpression: {
  264. auto& call = cast<CallExpression>(expression);
  265. CARBON_RETURN_IF_ERROR(ResolveNames(call.function(), enclosing_scope));
  266. CARBON_RETURN_IF_ERROR(ResolveNames(call.argument(), enclosing_scope));
  267. break;
  268. }
  269. case ExpressionKind::FunctionTypeLiteral: {
  270. auto& fun_type = cast<FunctionTypeLiteral>(expression);
  271. CARBON_RETURN_IF_ERROR(
  272. ResolveNames(fun_type.parameter(), enclosing_scope));
  273. CARBON_RETURN_IF_ERROR(
  274. ResolveNames(fun_type.return_type(), enclosing_scope));
  275. break;
  276. }
  277. case ExpressionKind::SimpleMemberAccessExpression: {
  278. // If the left-hand side of the `.` is a namespace or alias to namespace,
  279. // resolve the name.
  280. auto& access = cast<SimpleMemberAccessExpression>(expression);
  281. CARBON_ASSIGN_OR_RETURN(std::optional<ValueNodeView> scope,
  282. ResolveNames(access.object(), enclosing_scope));
  283. if (!scope) {
  284. break;
  285. }
  286. Nonnull<const AstNode*> base = &scope->base();
  287. // recursively resolve aliases.
  288. while (const auto* alias = dyn_cast<AliasDeclaration>(base)) {
  289. if (auto resolved = alias->resolved_declaration()) {
  290. base = *resolved;
  291. } else {
  292. break;
  293. }
  294. }
  295. if (const auto* namespace_decl = dyn_cast<NamespaceDeclaration>(base)) {
  296. auto ns_it = namespace_scopes_.find(namespace_decl);
  297. CARBON_CHECK(ns_it != namespace_scopes_.end())
  298. << "name resolved to undeclared namespace";
  299. CARBON_ASSIGN_OR_RETURN(
  300. const auto value_node,
  301. ns_it->second.ResolveHere(scope, access.member_name(),
  302. access.source_loc(),
  303. /*allow_undeclared=*/false));
  304. access.set_value_node(value_node);
  305. return {value_node};
  306. }
  307. break;
  308. }
  309. case ExpressionKind::CompoundMemberAccessExpression: {
  310. auto& access = cast<CompoundMemberAccessExpression>(expression);
  311. CARBON_RETURN_IF_ERROR(ResolveNames(access.object(), enclosing_scope));
  312. CARBON_RETURN_IF_ERROR(ResolveNames(access.path(), enclosing_scope));
  313. break;
  314. }
  315. case ExpressionKind::IndexExpression: {
  316. auto& index = cast<IndexExpression>(expression);
  317. CARBON_RETURN_IF_ERROR(ResolveNames(index.object(), enclosing_scope));
  318. CARBON_RETURN_IF_ERROR(ResolveNames(index.offset(), enclosing_scope));
  319. break;
  320. }
  321. case ExpressionKind::OperatorExpression:
  322. for (Nonnull<Expression*> operand :
  323. cast<OperatorExpression>(expression).arguments()) {
  324. CARBON_RETURN_IF_ERROR(ResolveNames(*operand, enclosing_scope));
  325. }
  326. break;
  327. case ExpressionKind::TupleLiteral:
  328. for (Nonnull<Expression*> field :
  329. cast<TupleLiteral>(expression).fields()) {
  330. CARBON_RETURN_IF_ERROR(ResolveNames(*field, enclosing_scope));
  331. }
  332. break;
  333. case ExpressionKind::StructLiteral: {
  334. std::set<std::string_view> member_names;
  335. for (FieldInitializer& init : cast<StructLiteral>(expression).fields()) {
  336. CARBON_RETURN_IF_ERROR(
  337. ResolveNames(init.expression(), enclosing_scope));
  338. if (!member_names.insert(init.name()).second) {
  339. return ProgramError(init.expression().source_loc())
  340. << "Duplicate name `" << init.name() << "` in struct literal";
  341. }
  342. }
  343. break;
  344. }
  345. case ExpressionKind::StructTypeLiteral: {
  346. std::set<std::string_view> member_names;
  347. for (FieldInitializer& init :
  348. cast<StructTypeLiteral>(expression).fields()) {
  349. CARBON_RETURN_IF_ERROR(
  350. ResolveNames(init.expression(), enclosing_scope));
  351. if (!member_names.insert(init.name()).second) {
  352. return ProgramError(init.expression().source_loc())
  353. << "Duplicate name `" << init.name()
  354. << "` in struct type literal";
  355. }
  356. }
  357. break;
  358. }
  359. case ExpressionKind::IdentifierExpression: {
  360. auto& identifier = cast<IdentifierExpression>(expression);
  361. CARBON_ASSIGN_OR_RETURN(
  362. const auto value_node,
  363. enclosing_scope.Resolve(identifier.name(), identifier.source_loc()));
  364. identifier.set_value_node(value_node);
  365. return {value_node};
  366. }
  367. case ExpressionKind::DotSelfExpression: {
  368. auto& dot_self = cast<DotSelfExpression>(expression);
  369. CARBON_ASSIGN_OR_RETURN(
  370. const auto value_node,
  371. enclosing_scope.Resolve(".Self", dot_self.source_loc()));
  372. dot_self.set_self_binding(const_cast<GenericBinding*>(
  373. &cast<GenericBinding>(value_node.base())));
  374. break;
  375. }
  376. case ExpressionKind::IntrinsicExpression:
  377. CARBON_RETURN_IF_ERROR(ResolveNames(
  378. cast<IntrinsicExpression>(expression).args(), enclosing_scope));
  379. break;
  380. case ExpressionKind::IfExpression: {
  381. auto& if_expr = cast<IfExpression>(expression);
  382. CARBON_RETURN_IF_ERROR(
  383. ResolveNames(if_expr.condition(), enclosing_scope));
  384. CARBON_RETURN_IF_ERROR(
  385. ResolveNames(if_expr.then_expression(), enclosing_scope));
  386. CARBON_RETURN_IF_ERROR(
  387. ResolveNames(if_expr.else_expression(), enclosing_scope));
  388. break;
  389. }
  390. case ExpressionKind::WhereExpression: {
  391. auto& where = cast<WhereExpression>(expression);
  392. CARBON_RETURN_IF_ERROR(
  393. ResolveNames(where.self_binding().type(), enclosing_scope));
  394. // If we're already in a `.Self` context, remember it so that we can
  395. // reuse its value for the inner `.Self`.
  396. if (auto enclosing_dot_self =
  397. enclosing_scope.Resolve(".Self", where.source_loc());
  398. enclosing_dot_self.ok()) {
  399. where.set_enclosing_dot_self(
  400. &cast<GenericBinding>(enclosing_dot_self->base()));
  401. }
  402. // Introduce `.Self` into scope on the right of the `where` keyword.
  403. StaticScope where_scope(&enclosing_scope);
  404. CARBON_RETURN_IF_ERROR(where_scope.Add(".Self", &where.self_binding()));
  405. for (Nonnull<WhereClause*> clause : where.clauses()) {
  406. CARBON_RETURN_IF_ERROR(ResolveNames(*clause, where_scope));
  407. }
  408. break;
  409. }
  410. case ExpressionKind::ArrayTypeLiteral: {
  411. auto& array_literal = cast<ArrayTypeLiteral>(expression);
  412. CARBON_RETURN_IF_ERROR(ResolveNames(
  413. array_literal.element_type_expression(), enclosing_scope));
  414. if (array_literal.has_size_expression()) {
  415. CARBON_RETURN_IF_ERROR(
  416. ResolveNames(array_literal.size_expression(), enclosing_scope));
  417. }
  418. break;
  419. }
  420. case ExpressionKind::BoolTypeLiteral:
  421. case ExpressionKind::BoolLiteral:
  422. case ExpressionKind::IntTypeLiteral:
  423. case ExpressionKind::IntLiteral:
  424. case ExpressionKind::StringLiteral:
  425. case ExpressionKind::StringTypeLiteral:
  426. case ExpressionKind::TypeTypeLiteral:
  427. break;
  428. case ExpressionKind::ValueLiteral:
  429. case ExpressionKind::BuiltinConvertExpression:
  430. case ExpressionKind::BaseAccessExpression:
  431. CARBON_FATAL() << "should not exist before type checking";
  432. case ExpressionKind::UnimplementedExpression:
  433. return ProgramError(expression.source_loc()) << "Unimplemented";
  434. }
  435. return {std::nullopt};
  436. }
  437. auto NameResolver::ResolveNames(WhereClause& clause,
  438. const StaticScope& enclosing_scope)
  439. -> ErrorOr<Success> {
  440. return RunWithExtraStack(
  441. [&]() { return ResolveNamesImpl(clause, enclosing_scope); });
  442. }
  443. auto NameResolver::ResolveNamesImpl(WhereClause& clause,
  444. const StaticScope& enclosing_scope)
  445. -> ErrorOr<Success> {
  446. switch (clause.kind()) {
  447. case WhereClauseKind::ImplsWhereClause: {
  448. auto& impls_clause = cast<ImplsWhereClause>(clause);
  449. CARBON_RETURN_IF_ERROR(
  450. ResolveNames(impls_clause.type(), enclosing_scope));
  451. CARBON_RETURN_IF_ERROR(
  452. ResolveNames(impls_clause.constraint(), enclosing_scope));
  453. break;
  454. }
  455. case WhereClauseKind::EqualsWhereClause: {
  456. auto& equals_clause = cast<EqualsWhereClause>(clause);
  457. CARBON_RETURN_IF_ERROR(
  458. ResolveNames(equals_clause.lhs(), enclosing_scope));
  459. CARBON_RETURN_IF_ERROR(
  460. ResolveNames(equals_clause.rhs(), enclosing_scope));
  461. break;
  462. }
  463. case WhereClauseKind::RewriteWhereClause: {
  464. auto& rewrite_clause = cast<RewriteWhereClause>(clause);
  465. CARBON_RETURN_IF_ERROR(
  466. ResolveNames(rewrite_clause.replacement(), enclosing_scope));
  467. break;
  468. }
  469. }
  470. return Success();
  471. }
  472. auto NameResolver::ResolveNames(Pattern& pattern, StaticScope& enclosing_scope)
  473. -> ErrorOr<Success> {
  474. return RunWithExtraStack(
  475. [&]() { return ResolveNamesImpl(pattern, enclosing_scope); });
  476. }
  477. auto NameResolver::ResolveNamesImpl(Pattern& pattern,
  478. StaticScope& enclosing_scope)
  479. -> ErrorOr<Success> {
  480. switch (pattern.kind()) {
  481. case PatternKind::BindingPattern: {
  482. auto& binding = cast<BindingPattern>(pattern);
  483. CARBON_RETURN_IF_ERROR(ResolveNames(binding.type(), enclosing_scope));
  484. if (binding.name() != AnonymousName) {
  485. CARBON_RETURN_IF_ERROR(enclosing_scope.Add(binding.name(), &binding));
  486. }
  487. break;
  488. }
  489. case PatternKind::GenericBinding: {
  490. auto& binding = cast<GenericBinding>(pattern);
  491. // `.Self` is in scope in the context of the type.
  492. StaticScope self_scope(&enclosing_scope);
  493. CARBON_RETURN_IF_ERROR(self_scope.Add(".Self", &binding));
  494. CARBON_RETURN_IF_ERROR(ResolveNames(binding.type(), self_scope));
  495. if (binding.name() != AnonymousName) {
  496. CARBON_RETURN_IF_ERROR(enclosing_scope.Add(binding.name(), &binding));
  497. }
  498. break;
  499. }
  500. case PatternKind::TuplePattern:
  501. for (Nonnull<Pattern*> field : cast<TuplePattern>(pattern).fields()) {
  502. CARBON_RETURN_IF_ERROR(ResolveNames(*field, enclosing_scope));
  503. }
  504. break;
  505. case PatternKind::AlternativePattern: {
  506. auto& alternative = cast<AlternativePattern>(pattern);
  507. CARBON_RETURN_IF_ERROR(
  508. ResolveNames(alternative.choice_type(), enclosing_scope));
  509. CARBON_RETURN_IF_ERROR(
  510. ResolveNames(alternative.arguments(), enclosing_scope));
  511. break;
  512. }
  513. case PatternKind::ExpressionPattern:
  514. CARBON_RETURN_IF_ERROR(ResolveNames(
  515. cast<ExpressionPattern>(pattern).expression(), enclosing_scope));
  516. break;
  517. case PatternKind::AutoPattern:
  518. break;
  519. case PatternKind::VarPattern:
  520. CARBON_RETURN_IF_ERROR(
  521. ResolveNames(cast<VarPattern>(pattern).pattern(), enclosing_scope));
  522. break;
  523. case PatternKind::AddrPattern:
  524. CARBON_RETURN_IF_ERROR(
  525. ResolveNames(cast<AddrPattern>(pattern).binding(), enclosing_scope));
  526. break;
  527. }
  528. return Success();
  529. }
  530. auto NameResolver::ResolveNames(Statement& statement,
  531. StaticScope& enclosing_scope)
  532. -> ErrorOr<Success> {
  533. return RunWithExtraStack(
  534. [&]() { return ResolveNamesImpl(statement, enclosing_scope); });
  535. }
  536. auto NameResolver::ResolveNamesImpl(Statement& statement,
  537. StaticScope& enclosing_scope)
  538. -> ErrorOr<Success> {
  539. switch (statement.kind()) {
  540. case StatementKind::ExpressionStatement:
  541. CARBON_RETURN_IF_ERROR(ResolveNames(
  542. cast<ExpressionStatement>(statement).expression(), enclosing_scope));
  543. break;
  544. case StatementKind::Assign: {
  545. auto& assign = cast<Assign>(statement);
  546. CARBON_RETURN_IF_ERROR(ResolveNames(assign.lhs(), enclosing_scope));
  547. CARBON_RETURN_IF_ERROR(ResolveNames(assign.rhs(), enclosing_scope));
  548. break;
  549. }
  550. case StatementKind::IncrementDecrement: {
  551. auto& inc_dec = cast<IncrementDecrement>(statement);
  552. CARBON_RETURN_IF_ERROR(ResolveNames(inc_dec.argument(), enclosing_scope));
  553. break;
  554. }
  555. case StatementKind::VariableDefinition: {
  556. auto& def = cast<VariableDefinition>(statement);
  557. if (def.has_init()) {
  558. CARBON_RETURN_IF_ERROR(ResolveNames(def.init(), enclosing_scope));
  559. }
  560. CARBON_RETURN_IF_ERROR(ResolveNames(def.pattern(), enclosing_scope));
  561. if (def.is_returned()) {
  562. CARBON_CHECK(def.pattern().kind() == PatternKind::BindingPattern)
  563. << def.pattern().source_loc()
  564. << "returned var definition can only be a binding pattern";
  565. CARBON_RETURN_IF_ERROR(enclosing_scope.AddReturnedVar(
  566. ValueNodeView(&cast<BindingPattern>(def.pattern()))));
  567. }
  568. break;
  569. }
  570. case StatementKind::If: {
  571. auto& if_stmt = cast<If>(statement);
  572. CARBON_RETURN_IF_ERROR(
  573. ResolveNames(if_stmt.condition(), enclosing_scope));
  574. CARBON_RETURN_IF_ERROR(
  575. ResolveNames(if_stmt.then_block(), enclosing_scope));
  576. if (auto else_block = if_stmt.else_block()) {
  577. CARBON_RETURN_IF_ERROR(ResolveNames(**else_block, enclosing_scope));
  578. }
  579. break;
  580. }
  581. case StatementKind::ReturnVar: {
  582. auto& ret_var_stmt = cast<ReturnVar>(statement);
  583. std::optional<ValueNodeView> returned_var_def_view =
  584. enclosing_scope.ResolveReturned();
  585. if (!returned_var_def_view.has_value()) {
  586. return ProgramError(ret_var_stmt.source_loc())
  587. << "`return var` is not allowed without a returned var defined "
  588. "in scope.";
  589. }
  590. ret_var_stmt.set_value_node(*returned_var_def_view);
  591. break;
  592. }
  593. case StatementKind::ReturnExpression: {
  594. auto& ret_exp_stmt = cast<ReturnExpression>(statement);
  595. std::optional<ValueNodeView> returned_var_def_view =
  596. enclosing_scope.ResolveReturned();
  597. if (returned_var_def_view.has_value()) {
  598. return ProgramError(ret_exp_stmt.source_loc())
  599. << "`return <expression>` is not allowed with a returned var "
  600. "defined in scope: "
  601. << returned_var_def_view->base().source_loc();
  602. }
  603. CARBON_RETURN_IF_ERROR(
  604. ResolveNames(ret_exp_stmt.expression(), enclosing_scope));
  605. break;
  606. }
  607. case StatementKind::Block: {
  608. auto& block = cast<Block>(statement);
  609. StaticScope block_scope(&enclosing_scope);
  610. for (Nonnull<Statement*> sub_statement : block.statements()) {
  611. CARBON_RETURN_IF_ERROR(ResolveNames(*sub_statement, block_scope));
  612. }
  613. break;
  614. }
  615. case StatementKind::While: {
  616. auto& while_stmt = cast<While>(statement);
  617. CARBON_RETURN_IF_ERROR(
  618. ResolveNames(while_stmt.condition(), enclosing_scope));
  619. CARBON_RETURN_IF_ERROR(ResolveNames(while_stmt.body(), enclosing_scope));
  620. break;
  621. }
  622. case StatementKind::For: {
  623. StaticScope statement_scope(&enclosing_scope);
  624. auto& for_stmt = cast<For>(statement);
  625. CARBON_RETURN_IF_ERROR(
  626. ResolveNames(for_stmt.loop_target(), statement_scope));
  627. CARBON_RETURN_IF_ERROR(
  628. ResolveNames(for_stmt.variable_declaration(), statement_scope));
  629. CARBON_RETURN_IF_ERROR(ResolveNames(for_stmt.body(), statement_scope));
  630. break;
  631. }
  632. case StatementKind::Match: {
  633. auto& match = cast<Match>(statement);
  634. CARBON_RETURN_IF_ERROR(ResolveNames(match.expression(), enclosing_scope));
  635. for (Match::Clause& clause : match.clauses()) {
  636. StaticScope clause_scope(&enclosing_scope);
  637. CARBON_RETURN_IF_ERROR(ResolveNames(clause.pattern(), clause_scope));
  638. CARBON_RETURN_IF_ERROR(ResolveNames(clause.statement(), clause_scope));
  639. }
  640. break;
  641. }
  642. case StatementKind::Break:
  643. case StatementKind::Continue:
  644. break;
  645. }
  646. return Success();
  647. }
  648. auto NameResolver::ResolveMemberNames(
  649. llvm::ArrayRef<Nonnull<Declaration*>> members, StaticScope& scope,
  650. ResolveFunctionBodies bodies) -> ErrorOr<Success> {
  651. for (Nonnull<Declaration*> member : members) {
  652. CARBON_RETURN_IF_ERROR(AddExposedNames(*member, scope));
  653. }
  654. if (bodies != ResolveFunctionBodies::Immediately) {
  655. for (Nonnull<Declaration*> member : members) {
  656. CARBON_RETURN_IF_ERROR(
  657. ResolveNames(*member, scope, ResolveFunctionBodies::Skip));
  658. }
  659. }
  660. if (bodies != ResolveFunctionBodies::Skip) {
  661. for (Nonnull<Declaration*> member : members) {
  662. CARBON_RETURN_IF_ERROR(
  663. ResolveNames(*member, scope, ResolveFunctionBodies::Immediately));
  664. }
  665. }
  666. return Success();
  667. }
  668. auto NameResolver::ResolveNames(Declaration& declaration,
  669. StaticScope& enclosing_scope,
  670. ResolveFunctionBodies bodies)
  671. -> ErrorOr<Success> {
  672. return RunWithExtraStack(
  673. [&]() { return ResolveNamesImpl(declaration, enclosing_scope, bodies); });
  674. }
  675. auto NameResolver::ResolveNamesImpl(Declaration& declaration,
  676. StaticScope& enclosing_scope,
  677. ResolveFunctionBodies bodies)
  678. -> ErrorOr<Success> {
  679. switch (declaration.kind()) {
  680. case DeclarationKind::NamespaceDeclaration: {
  681. auto& namespace_decl = cast<NamespaceDeclaration>(declaration);
  682. CARBON_ASSIGN_OR_RETURN(
  683. Nonnull<StaticScope*> scope,
  684. ResolveQualifier(namespace_decl.name(), enclosing_scope));
  685. scope->MarkUsable(namespace_decl.name().inner_name());
  686. break;
  687. }
  688. case DeclarationKind::InterfaceDeclaration:
  689. case DeclarationKind::ConstraintDeclaration: {
  690. auto& iface = cast<ConstraintTypeDeclaration>(declaration);
  691. CARBON_ASSIGN_OR_RETURN(Nonnull<StaticScope*> scope,
  692. ResolveQualifier(iface.name(), enclosing_scope));
  693. StaticScope iface_scope(scope);
  694. scope->MarkDeclared(iface.name().inner_name());
  695. if (auto params = iface.params()) {
  696. CARBON_RETURN_IF_ERROR(ResolveNames(**params, iface_scope));
  697. }
  698. scope->MarkUsable(iface.name().inner_name());
  699. // Don't resolve names in the type of the self binding. The
  700. // ConstraintTypeDeclaration constructor already did that.
  701. CARBON_RETURN_IF_ERROR(iface_scope.Add("Self", iface.self()));
  702. CARBON_RETURN_IF_ERROR(
  703. ResolveMemberNames(iface.members(), iface_scope, bodies));
  704. break;
  705. }
  706. case DeclarationKind::ImplDeclaration: {
  707. auto& impl = cast<ImplDeclaration>(declaration);
  708. StaticScope impl_scope(&enclosing_scope);
  709. for (Nonnull<GenericBinding*> binding : impl.deduced_parameters()) {
  710. CARBON_RETURN_IF_ERROR(ResolveNames(binding->type(), impl_scope));
  711. CARBON_RETURN_IF_ERROR(impl_scope.Add(binding->name(), binding));
  712. }
  713. CARBON_RETURN_IF_ERROR(ResolveNames(*impl.impl_type(), impl_scope));
  714. // Only add `Self` to the impl_scope if it is not already in the enclosing
  715. // scope. Add `Self` after we resolve names for the impl_type, so you
  716. // can't write something like `impl Vector(Self) as ...`. Add `Self`
  717. // before resolving names in the interface, so you can write something
  718. // like `impl VeryLongTypeName as AddWith(Self)`
  719. if (!enclosing_scope.Resolve("Self", impl.source_loc()).ok()) {
  720. CARBON_RETURN_IF_ERROR(AddExposedNames(*impl.self(), impl_scope));
  721. }
  722. CARBON_RETURN_IF_ERROR(ResolveNames(impl.interface(), impl_scope));
  723. CARBON_RETURN_IF_ERROR(
  724. ResolveMemberNames(impl.members(), impl_scope, bodies));
  725. break;
  726. }
  727. case DeclarationKind::MatchFirstDeclaration: {
  728. // A `match_first` declaration does not introduce a scope.
  729. for (auto* impl :
  730. cast<MatchFirstDeclaration>(declaration).impl_declarations()) {
  731. CARBON_RETURN_IF_ERROR(ResolveNames(*impl, enclosing_scope, bodies));
  732. }
  733. break;
  734. }
  735. case DeclarationKind::DestructorDeclaration:
  736. case DeclarationKind::FunctionDeclaration: {
  737. auto& function = cast<CallableDeclaration>(declaration);
  738. // TODO: Destructors should track their qualified name.
  739. const DeclaredName& name =
  740. isa<FunctionDeclaration>(declaration)
  741. ? cast<FunctionDeclaration>(declaration).name()
  742. : DeclaredName(function.source_loc(), "destructor");
  743. CARBON_ASSIGN_OR_RETURN(Nonnull<StaticScope*> scope,
  744. ResolveQualifier(name, enclosing_scope));
  745. StaticScope function_scope(scope);
  746. scope->MarkDeclared(name.inner_name());
  747. for (Nonnull<GenericBinding*> binding : function.deduced_parameters()) {
  748. CARBON_RETURN_IF_ERROR(ResolveNames(*binding, function_scope));
  749. }
  750. if (function.is_method()) {
  751. CARBON_RETURN_IF_ERROR(
  752. ResolveNames(function.self_pattern(), function_scope));
  753. }
  754. CARBON_RETURN_IF_ERROR(
  755. ResolveNames(function.param_pattern(), function_scope));
  756. if (auto return_type_expr = function.return_term().type_expression()) {
  757. CARBON_RETURN_IF_ERROR(
  758. ResolveNames(**return_type_expr, function_scope));
  759. }
  760. scope->MarkUsable(name.inner_name());
  761. if (auto body = function.body();
  762. body.has_value() && bodies != ResolveFunctionBodies::Skip) {
  763. CARBON_RETURN_IF_ERROR(ResolveNames(**body, function_scope));
  764. }
  765. break;
  766. }
  767. case DeclarationKind::ClassDeclaration: {
  768. auto& class_decl = cast<ClassDeclaration>(declaration);
  769. CARBON_ASSIGN_OR_RETURN(
  770. Nonnull<StaticScope*> scope,
  771. ResolveQualifier(class_decl.name(), enclosing_scope));
  772. StaticScope class_scope(scope);
  773. scope->MarkDeclared(class_decl.name().inner_name());
  774. if (auto type_params = class_decl.type_params()) {
  775. CARBON_RETURN_IF_ERROR(ResolveNames(**type_params, class_scope));
  776. }
  777. scope->MarkUsable(class_decl.name().inner_name());
  778. CARBON_RETURN_IF_ERROR(AddExposedNames(*class_decl.self(), class_scope));
  779. CARBON_RETURN_IF_ERROR(
  780. ResolveMemberNames(class_decl.members(), class_scope, bodies));
  781. break;
  782. }
  783. case DeclarationKind::ExtendBaseDeclaration: {
  784. auto& extend_base_decl = cast<ExtendBaseDeclaration>(declaration);
  785. CARBON_RETURN_IF_ERROR(
  786. ResolveNames(*extend_base_decl.base_class(), enclosing_scope));
  787. break;
  788. }
  789. case DeclarationKind::MixinDeclaration: {
  790. auto& mixin_decl = cast<MixinDeclaration>(declaration);
  791. CARBON_ASSIGN_OR_RETURN(
  792. Nonnull<StaticScope*> scope,
  793. ResolveQualifier(mixin_decl.name(), enclosing_scope));
  794. StaticScope mixin_scope(scope);
  795. scope->MarkDeclared(mixin_decl.name().inner_name());
  796. if (auto params = mixin_decl.params()) {
  797. CARBON_RETURN_IF_ERROR(ResolveNames(**params, mixin_scope));
  798. }
  799. scope->MarkUsable(mixin_decl.name().inner_name());
  800. CARBON_RETURN_IF_ERROR(mixin_scope.Add("Self", mixin_decl.self()));
  801. CARBON_RETURN_IF_ERROR(
  802. ResolveMemberNames(mixin_decl.members(), mixin_scope, bodies));
  803. break;
  804. }
  805. case DeclarationKind::MixDeclaration: {
  806. auto& mix_decl = cast<MixDeclaration>(declaration);
  807. CARBON_RETURN_IF_ERROR(ResolveNames(mix_decl.mixin(), enclosing_scope));
  808. break;
  809. }
  810. case DeclarationKind::ChoiceDeclaration: {
  811. auto& choice = cast<ChoiceDeclaration>(declaration);
  812. CARBON_ASSIGN_OR_RETURN(Nonnull<StaticScope*> scope,
  813. ResolveQualifier(choice.name(), enclosing_scope));
  814. StaticScope choice_scope(scope);
  815. scope->MarkDeclared(choice.name().inner_name());
  816. if (auto type_params = choice.type_params()) {
  817. CARBON_RETURN_IF_ERROR(ResolveNames(**type_params, choice_scope));
  818. }
  819. // Alternative names are never used unqualified, so we don't need to
  820. // add the alternatives to a scope, or introduce a new scope; we only
  821. // need to check for duplicates.
  822. std::set<std::string_view> alternative_names;
  823. for (Nonnull<AlternativeSignature*> alternative : choice.alternatives()) {
  824. if (auto params = alternative->parameters()) {
  825. CARBON_RETURN_IF_ERROR(ResolveNames(**params, choice_scope));
  826. }
  827. if (!alternative_names.insert(alternative->name()).second) {
  828. return ProgramError(alternative->source_loc())
  829. << "Duplicate name `" << alternative->name()
  830. << "` in choice type";
  831. }
  832. }
  833. scope->MarkUsable(choice.name().inner_name());
  834. break;
  835. }
  836. case DeclarationKind::VariableDeclaration: {
  837. auto& var = cast<VariableDeclaration>(declaration);
  838. CARBON_RETURN_IF_ERROR(ResolveNames(var.binding(), enclosing_scope));
  839. if (var.has_initializer()) {
  840. CARBON_RETURN_IF_ERROR(
  841. ResolveNames(var.initializer(), enclosing_scope));
  842. }
  843. break;
  844. }
  845. case DeclarationKind::InterfaceExtendDeclaration: {
  846. auto& extends = cast<InterfaceExtendDeclaration>(declaration);
  847. CARBON_RETURN_IF_ERROR(ResolveNames(*extends.base(), enclosing_scope));
  848. break;
  849. }
  850. case DeclarationKind::InterfaceRequireDeclaration: {
  851. auto& require = cast<InterfaceRequireDeclaration>(declaration);
  852. CARBON_RETURN_IF_ERROR(
  853. ResolveNames(*require.impl_type(), enclosing_scope));
  854. CARBON_RETURN_IF_ERROR(
  855. ResolveNames(*require.constraint(), enclosing_scope));
  856. break;
  857. }
  858. case DeclarationKind::AssociatedConstantDeclaration: {
  859. auto& let = cast<AssociatedConstantDeclaration>(declaration);
  860. StaticScope constant_scope(&enclosing_scope);
  861. enclosing_scope.MarkDeclared(let.binding().name());
  862. CARBON_RETURN_IF_ERROR(ResolveNames(let.binding(), constant_scope));
  863. enclosing_scope.MarkUsable(let.binding().name());
  864. break;
  865. }
  866. case DeclarationKind::SelfDeclaration: {
  867. CARBON_FATAL() << "Unreachable: resolving names for `Self` declaration";
  868. }
  869. case DeclarationKind::AliasDeclaration: {
  870. auto& alias = cast<AliasDeclaration>(declaration);
  871. CARBON_ASSIGN_OR_RETURN(Nonnull<StaticScope*> scope,
  872. ResolveQualifier(alias.name(), enclosing_scope));
  873. scope->MarkDeclared(alias.name().inner_name());
  874. CARBON_ASSIGN_OR_RETURN(auto target,
  875. ResolveNames(alias.target(), *scope));
  876. if (target && isa<Declaration>(target->base())) {
  877. if (auto resolved_declaration = alias.resolved_declaration()) {
  878. // Skip if the declaration is already resolved in a previous name
  879. // resolution phase.
  880. CARBON_CHECK(*resolved_declaration == &target->base());
  881. } else {
  882. alias.set_resolved_declaration(&cast<Declaration>(target->base()));
  883. }
  884. }
  885. scope->MarkUsable(alias.name().inner_name());
  886. break;
  887. }
  888. }
  889. return Success();
  890. }
  891. auto ResolveNames(AST& ast) -> ErrorOr<Success> {
  892. return RunWithExtraStack([&]() -> ErrorOr<Success> {
  893. NameResolver resolver;
  894. StaticScope file_scope;
  895. for (auto* declaration : ast.declarations) {
  896. CARBON_RETURN_IF_ERROR(resolver.AddExposedNames(
  897. *declaration, file_scope, /*allow_qualified_names=*/true));
  898. }
  899. for (auto* declaration : ast.declarations) {
  900. CARBON_RETURN_IF_ERROR(resolver.ResolveNames(
  901. *declaration, file_scope,
  902. NameResolver::ResolveFunctionBodies::AfterDeclarations));
  903. }
  904. CARBON_RETURN_IF_ERROR(resolver.ResolveNames(**ast.main_call, file_scope));
  905. return Success();
  906. });
  907. }
  908. } // namespace Carbon