resolve_names.cpp 40 KB

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