resolve_names.cpp 36 KB

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