resolve_names.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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/Support/Casting.h"
  12. #include "llvm/Support/Error.h"
  13. using llvm::cast;
  14. namespace Carbon {
  15. // Adds the names exposed by the given AST node to enclosing_scope.
  16. static auto AddExposedNames(const Declaration& declaration,
  17. StaticScope& enclosing_scope) -> ErrorOr<Success>;
  18. static auto AddExposedNames(const Declaration& declaration,
  19. StaticScope& enclosing_scope) -> ErrorOr<Success> {
  20. switch (declaration.kind()) {
  21. case DeclarationKind::InterfaceDeclaration: {
  22. auto& iface_decl = cast<InterfaceDeclaration>(declaration);
  23. CARBON_RETURN_IF_ERROR(
  24. enclosing_scope.Add(iface_decl.name(), &iface_decl));
  25. break;
  26. }
  27. case DeclarationKind::ImplDeclaration: {
  28. // Nothing to do here
  29. break;
  30. }
  31. case DeclarationKind::FunctionDeclaration: {
  32. auto& func = cast<FunctionDeclaration>(declaration);
  33. CARBON_RETURN_IF_ERROR(enclosing_scope.Add(func.name(), &func));
  34. break;
  35. }
  36. case DeclarationKind::ClassDeclaration: {
  37. auto& class_decl = cast<ClassDeclaration>(declaration);
  38. CARBON_RETURN_IF_ERROR(
  39. enclosing_scope.Add(class_decl.name(), &class_decl));
  40. break;
  41. }
  42. case DeclarationKind::ChoiceDeclaration: {
  43. // Choice name is added to the scope after the choice's alternatives.
  44. // See https://github.com/carbon-language/carbon-lang/issues/1248.
  45. break;
  46. }
  47. case DeclarationKind::VariableDeclaration: {
  48. auto& var = cast<VariableDeclaration>(declaration);
  49. if (var.binding().name() != AnonymousName) {
  50. CARBON_RETURN_IF_ERROR(
  51. enclosing_scope.Add(var.binding().name(), &var.binding()));
  52. }
  53. break;
  54. }
  55. case DeclarationKind::SelfDeclaration: {
  56. auto& self = cast<SelfDeclaration>(declaration);
  57. CARBON_RETURN_IF_ERROR(enclosing_scope.Add("Self", &self));
  58. break;
  59. }
  60. case DeclarationKind::AliasDeclaration: {
  61. auto& alias = cast<AliasDeclaration>(declaration);
  62. CARBON_RETURN_IF_ERROR(enclosing_scope.Add(alias.name(), &alias));
  63. break;
  64. }
  65. }
  66. return Success();
  67. }
  68. // Traverses the sub-AST rooted at the given node, resolving all names within
  69. // it using enclosing_scope, and updating enclosing_scope to add names to
  70. // it as they become available. In scopes where names are only visible below
  71. // their point of declaration (such as block scopes in C++), this is implemented
  72. // as a single pass, recursively calling ResolveNames on the elements of the
  73. // scope in order. In scopes where names are also visible above their point of
  74. // declaration (such as class scopes in C++), this requires two passes: first
  75. // calling AddExposedNames on each element of the scope to populate a
  76. // StaticScope, and then calling ResolveNames on each element, passing it the
  77. // already-populated StaticScope.
  78. static auto ResolveNames(Expression& expression,
  79. const StaticScope& enclosing_scope)
  80. -> ErrorOr<Success>;
  81. static auto ResolveNames(Pattern& pattern, StaticScope& enclosing_scope)
  82. -> ErrorOr<Success>;
  83. static auto ResolveNames(Statement& statement, StaticScope& enclosing_scope)
  84. -> ErrorOr<Success>;
  85. static auto ResolveNames(Declaration& declaration, StaticScope& enclosing_scope)
  86. -> ErrorOr<Success>;
  87. static auto ResolveNames(Expression& expression,
  88. const StaticScope& enclosing_scope)
  89. -> ErrorOr<Success> {
  90. switch (expression.kind()) {
  91. case ExpressionKind::CallExpression: {
  92. auto& call = cast<CallExpression>(expression);
  93. CARBON_RETURN_IF_ERROR(ResolveNames(call.function(), enclosing_scope));
  94. CARBON_RETURN_IF_ERROR(ResolveNames(call.argument(), enclosing_scope));
  95. break;
  96. }
  97. case ExpressionKind::FunctionTypeLiteral: {
  98. auto& fun_type = cast<FunctionTypeLiteral>(expression);
  99. CARBON_RETURN_IF_ERROR(
  100. ResolveNames(fun_type.parameter(), enclosing_scope));
  101. CARBON_RETURN_IF_ERROR(
  102. ResolveNames(fun_type.return_type(), enclosing_scope));
  103. break;
  104. }
  105. case ExpressionKind::SimpleMemberAccessExpression:
  106. CARBON_RETURN_IF_ERROR(
  107. ResolveNames(cast<SimpleMemberAccessExpression>(expression).object(),
  108. enclosing_scope));
  109. break;
  110. case ExpressionKind::CompoundMemberAccessExpression: {
  111. auto& access = cast<CompoundMemberAccessExpression>(expression);
  112. CARBON_RETURN_IF_ERROR(ResolveNames(access.object(), enclosing_scope));
  113. CARBON_RETURN_IF_ERROR(ResolveNames(access.path(), enclosing_scope));
  114. break;
  115. }
  116. case ExpressionKind::IndexExpression: {
  117. auto& index = cast<IndexExpression>(expression);
  118. CARBON_RETURN_IF_ERROR(ResolveNames(index.object(), enclosing_scope));
  119. CARBON_RETURN_IF_ERROR(ResolveNames(index.offset(), enclosing_scope));
  120. break;
  121. }
  122. case ExpressionKind::PrimitiveOperatorExpression:
  123. for (Nonnull<Expression*> operand :
  124. cast<PrimitiveOperatorExpression>(expression).arguments()) {
  125. CARBON_RETURN_IF_ERROR(ResolveNames(*operand, enclosing_scope));
  126. }
  127. break;
  128. case ExpressionKind::TupleLiteral:
  129. for (Nonnull<Expression*> field :
  130. cast<TupleLiteral>(expression).fields()) {
  131. CARBON_RETURN_IF_ERROR(ResolveNames(*field, enclosing_scope));
  132. }
  133. break;
  134. case ExpressionKind::StructLiteral:
  135. for (FieldInitializer& init : cast<StructLiteral>(expression).fields()) {
  136. CARBON_RETURN_IF_ERROR(
  137. ResolveNames(init.expression(), enclosing_scope));
  138. }
  139. break;
  140. case ExpressionKind::StructTypeLiteral:
  141. for (FieldInitializer& init :
  142. cast<StructTypeLiteral>(expression).fields()) {
  143. CARBON_RETURN_IF_ERROR(
  144. ResolveNames(init.expression(), enclosing_scope));
  145. }
  146. break;
  147. case ExpressionKind::IdentifierExpression: {
  148. auto& identifier = cast<IdentifierExpression>(expression);
  149. CARBON_ASSIGN_OR_RETURN(
  150. const auto value_node,
  151. enclosing_scope.Resolve(identifier.name(), identifier.source_loc()));
  152. identifier.set_value_node(value_node);
  153. break;
  154. }
  155. case ExpressionKind::IntrinsicExpression:
  156. CARBON_RETURN_IF_ERROR(ResolveNames(
  157. cast<IntrinsicExpression>(expression).args(), enclosing_scope));
  158. break;
  159. case ExpressionKind::IfExpression: {
  160. auto& if_expr = cast<IfExpression>(expression);
  161. CARBON_RETURN_IF_ERROR(
  162. ResolveNames(if_expr.condition(), enclosing_scope));
  163. CARBON_RETURN_IF_ERROR(
  164. ResolveNames(if_expr.then_expression(), enclosing_scope));
  165. CARBON_RETURN_IF_ERROR(
  166. ResolveNames(if_expr.else_expression(), enclosing_scope));
  167. break;
  168. }
  169. case ExpressionKind::ArrayTypeLiteral: {
  170. auto& array_literal = cast<ArrayTypeLiteral>(expression);
  171. CARBON_RETURN_IF_ERROR(ResolveNames(
  172. array_literal.element_type_expression(), enclosing_scope));
  173. CARBON_RETURN_IF_ERROR(
  174. ResolveNames(array_literal.size_expression(), enclosing_scope));
  175. break;
  176. }
  177. case ExpressionKind::BoolTypeLiteral:
  178. case ExpressionKind::BoolLiteral:
  179. case ExpressionKind::IntTypeLiteral:
  180. case ExpressionKind::ContinuationTypeLiteral:
  181. case ExpressionKind::IntLiteral:
  182. case ExpressionKind::StringLiteral:
  183. case ExpressionKind::StringTypeLiteral:
  184. case ExpressionKind::TypeTypeLiteral:
  185. case ExpressionKind::ValueLiteral:
  186. break;
  187. case ExpressionKind::InstantiateImpl: // created after name resolution
  188. case ExpressionKind::UnimplementedExpression:
  189. return CompilationError(expression.source_loc()) << "Unimplemented";
  190. }
  191. return Success();
  192. }
  193. static auto ResolveNames(Pattern& pattern, StaticScope& enclosing_scope)
  194. -> ErrorOr<Success> {
  195. switch (pattern.kind()) {
  196. case PatternKind::BindingPattern: {
  197. auto& binding = cast<BindingPattern>(pattern);
  198. CARBON_RETURN_IF_ERROR(ResolveNames(binding.type(), enclosing_scope));
  199. if (binding.name() != AnonymousName) {
  200. CARBON_RETURN_IF_ERROR(enclosing_scope.Add(binding.name(), &binding));
  201. }
  202. break;
  203. }
  204. case PatternKind::GenericBinding: {
  205. auto& binding = cast<GenericBinding>(pattern);
  206. CARBON_RETURN_IF_ERROR(ResolveNames(binding.type(), enclosing_scope));
  207. if (binding.name() != AnonymousName) {
  208. CARBON_RETURN_IF_ERROR(enclosing_scope.Add(binding.name(), &binding));
  209. }
  210. break;
  211. }
  212. case PatternKind::TuplePattern:
  213. for (Nonnull<Pattern*> field : cast<TuplePattern>(pattern).fields()) {
  214. CARBON_RETURN_IF_ERROR(ResolveNames(*field, enclosing_scope));
  215. }
  216. break;
  217. case PatternKind::AlternativePattern: {
  218. auto& alternative = cast<AlternativePattern>(pattern);
  219. CARBON_RETURN_IF_ERROR(
  220. ResolveNames(alternative.choice_type(), enclosing_scope));
  221. CARBON_RETURN_IF_ERROR(
  222. ResolveNames(alternative.arguments(), enclosing_scope));
  223. break;
  224. }
  225. case PatternKind::ExpressionPattern:
  226. CARBON_RETURN_IF_ERROR(ResolveNames(
  227. cast<ExpressionPattern>(pattern).expression(), enclosing_scope));
  228. break;
  229. case PatternKind::AutoPattern:
  230. break;
  231. case PatternKind::VarPattern:
  232. CARBON_RETURN_IF_ERROR(
  233. ResolveNames(cast<VarPattern>(pattern).pattern(), enclosing_scope));
  234. break;
  235. }
  236. return Success();
  237. }
  238. static auto ResolveNames(Statement& statement, StaticScope& enclosing_scope)
  239. -> ErrorOr<Success> {
  240. switch (statement.kind()) {
  241. case StatementKind::ExpressionStatement:
  242. CARBON_RETURN_IF_ERROR(ResolveNames(
  243. cast<ExpressionStatement>(statement).expression(), enclosing_scope));
  244. break;
  245. case StatementKind::Assign: {
  246. auto& assign = cast<Assign>(statement);
  247. CARBON_RETURN_IF_ERROR(ResolveNames(assign.lhs(), enclosing_scope));
  248. CARBON_RETURN_IF_ERROR(ResolveNames(assign.rhs(), enclosing_scope));
  249. break;
  250. }
  251. case StatementKind::VariableDefinition: {
  252. auto& def = cast<VariableDefinition>(statement);
  253. CARBON_RETURN_IF_ERROR(ResolveNames(def.init(), enclosing_scope));
  254. CARBON_RETURN_IF_ERROR(ResolveNames(def.pattern(), enclosing_scope));
  255. break;
  256. }
  257. case StatementKind::If: {
  258. auto& if_stmt = cast<If>(statement);
  259. CARBON_RETURN_IF_ERROR(
  260. ResolveNames(if_stmt.condition(), enclosing_scope));
  261. CARBON_RETURN_IF_ERROR(
  262. ResolveNames(if_stmt.then_block(), enclosing_scope));
  263. if (if_stmt.else_block().has_value()) {
  264. CARBON_RETURN_IF_ERROR(
  265. ResolveNames(**if_stmt.else_block(), enclosing_scope));
  266. }
  267. break;
  268. }
  269. case StatementKind::Return:
  270. CARBON_RETURN_IF_ERROR(
  271. ResolveNames(cast<Return>(statement).expression(), enclosing_scope));
  272. break;
  273. case StatementKind::Block: {
  274. auto& block = cast<Block>(statement);
  275. StaticScope block_scope;
  276. block_scope.AddParent(&enclosing_scope);
  277. for (Nonnull<Statement*> sub_statement : block.statements()) {
  278. CARBON_RETURN_IF_ERROR(ResolveNames(*sub_statement, block_scope));
  279. }
  280. break;
  281. }
  282. case StatementKind::While: {
  283. auto& while_stmt = cast<While>(statement);
  284. CARBON_RETURN_IF_ERROR(
  285. ResolveNames(while_stmt.condition(), enclosing_scope));
  286. CARBON_RETURN_IF_ERROR(ResolveNames(while_stmt.body(), enclosing_scope));
  287. break;
  288. }
  289. case StatementKind::Match: {
  290. auto& match = cast<Match>(statement);
  291. CARBON_RETURN_IF_ERROR(ResolveNames(match.expression(), enclosing_scope));
  292. for (Match::Clause& clause : match.clauses()) {
  293. StaticScope clause_scope;
  294. clause_scope.AddParent(&enclosing_scope);
  295. CARBON_RETURN_IF_ERROR(ResolveNames(clause.pattern(), clause_scope));
  296. CARBON_RETURN_IF_ERROR(ResolveNames(clause.statement(), clause_scope));
  297. }
  298. break;
  299. }
  300. case StatementKind::Continuation: {
  301. StaticScope continuation_scope;
  302. continuation_scope.AddParent(&enclosing_scope);
  303. auto& continuation = cast<Continuation>(statement);
  304. CARBON_RETURN_IF_ERROR(
  305. ResolveNames(continuation.body(), continuation_scope));
  306. CARBON_RETURN_IF_ERROR(
  307. enclosing_scope.Add(continuation.name(), &continuation));
  308. break;
  309. }
  310. case StatementKind::Run:
  311. CARBON_RETURN_IF_ERROR(
  312. ResolveNames(cast<Run>(statement).argument(), enclosing_scope));
  313. break;
  314. case StatementKind::Await:
  315. case StatementKind::Break:
  316. case StatementKind::Continue:
  317. break;
  318. }
  319. return Success();
  320. }
  321. static auto ResolveNames(Declaration& declaration, StaticScope& enclosing_scope)
  322. -> ErrorOr<Success> {
  323. switch (declaration.kind()) {
  324. case DeclarationKind::InterfaceDeclaration: {
  325. auto& iface = cast<InterfaceDeclaration>(declaration);
  326. StaticScope iface_scope;
  327. iface_scope.AddParent(&enclosing_scope);
  328. if (iface.params().has_value()) {
  329. CARBON_RETURN_IF_ERROR(ResolveNames(**iface.params(), iface_scope));
  330. }
  331. CARBON_RETURN_IF_ERROR(iface_scope.Add("Self", iface.self()));
  332. for (Nonnull<Declaration*> member : iface.members()) {
  333. CARBON_RETURN_IF_ERROR(AddExposedNames(*member, iface_scope));
  334. }
  335. for (Nonnull<Declaration*> member : iface.members()) {
  336. CARBON_RETURN_IF_ERROR(ResolveNames(*member, iface_scope));
  337. }
  338. break;
  339. }
  340. case DeclarationKind::ImplDeclaration: {
  341. auto& impl = cast<ImplDeclaration>(declaration);
  342. StaticScope impl_scope;
  343. impl_scope.AddParent(&enclosing_scope);
  344. for (Nonnull<GenericBinding*> binding : impl.deduced_parameters()) {
  345. CARBON_RETURN_IF_ERROR(ResolveNames(binding->type(), impl_scope));
  346. CARBON_RETURN_IF_ERROR(impl_scope.Add(binding->name(), binding));
  347. }
  348. CARBON_RETURN_IF_ERROR(ResolveNames(*impl.impl_type(), impl_scope));
  349. // Only add `Self` to the impl_scope if it is not already in the enclosing
  350. // scope. Add `Self` after we resolve names for the impl_type, so you
  351. // can't write something like `impl Vector(Self) as ...`. Add `Self`
  352. // before resolving names in the interface, so you can write something
  353. // like `impl VeryLongTypeName as AddWith(Self)`
  354. if (!enclosing_scope.Resolve("Self", impl.source_loc()).ok()) {
  355. CARBON_RETURN_IF_ERROR(AddExposedNames(*impl.self(), impl_scope));
  356. }
  357. CARBON_RETURN_IF_ERROR(ResolveNames(impl.interface(), impl_scope));
  358. for (Nonnull<Declaration*> member : impl.members()) {
  359. CARBON_RETURN_IF_ERROR(AddExposedNames(*member, impl_scope));
  360. }
  361. for (Nonnull<Declaration*> member : impl.members()) {
  362. CARBON_RETURN_IF_ERROR(ResolveNames(*member, impl_scope));
  363. }
  364. break;
  365. }
  366. case DeclarationKind::FunctionDeclaration: {
  367. auto& function = cast<FunctionDeclaration>(declaration);
  368. StaticScope function_scope;
  369. function_scope.AddParent(&enclosing_scope);
  370. for (Nonnull<GenericBinding*> binding : function.deduced_parameters()) {
  371. CARBON_RETURN_IF_ERROR(ResolveNames(binding->type(), function_scope));
  372. CARBON_RETURN_IF_ERROR(function_scope.Add(binding->name(), binding));
  373. }
  374. if (function.is_method()) {
  375. CARBON_RETURN_IF_ERROR(
  376. ResolveNames(function.me_pattern(), function_scope));
  377. }
  378. CARBON_RETURN_IF_ERROR(
  379. ResolveNames(function.param_pattern(), function_scope));
  380. if (function.return_term().type_expression().has_value()) {
  381. CARBON_RETURN_IF_ERROR(ResolveNames(
  382. **function.return_term().type_expression(), function_scope));
  383. }
  384. if (function.body().has_value()) {
  385. CARBON_RETURN_IF_ERROR(ResolveNames(**function.body(), function_scope));
  386. }
  387. break;
  388. }
  389. case DeclarationKind::ClassDeclaration: {
  390. auto& class_decl = cast<ClassDeclaration>(declaration);
  391. StaticScope class_scope;
  392. class_scope.AddParent(&enclosing_scope);
  393. CARBON_RETURN_IF_ERROR(class_scope.Add(class_decl.name(), &class_decl));
  394. CARBON_RETURN_IF_ERROR(AddExposedNames(*class_decl.self(), class_scope));
  395. if (class_decl.type_params().has_value()) {
  396. CARBON_RETURN_IF_ERROR(
  397. ResolveNames(**class_decl.type_params(), class_scope));
  398. }
  399. // TODO: Disable unqualified access of members by other members for now.
  400. // Put it back later, but in a way that turns unqualified accesses
  401. // into qualified ones, so that generic classes and impls
  402. // behave the in the right way. -Jeremy
  403. // for (Nonnull<Declaration*> member : class_decl.members()) {
  404. // AddExposedNames(*member, class_scope);
  405. // }
  406. for (Nonnull<Declaration*> member : class_decl.members()) {
  407. CARBON_RETURN_IF_ERROR(ResolveNames(*member, class_scope));
  408. }
  409. break;
  410. }
  411. case DeclarationKind::ChoiceDeclaration: {
  412. auto& choice = cast<ChoiceDeclaration>(declaration);
  413. // Alternative names are never used unqualified, so we don't need to
  414. // add the alternatives to a scope, or introduce a new scope; we only
  415. // need to check for duplicates.
  416. std::set<std::string_view> alternative_names;
  417. for (Nonnull<AlternativeSignature*> alternative : choice.alternatives()) {
  418. CARBON_RETURN_IF_ERROR(
  419. ResolveNames(alternative->signature(), enclosing_scope));
  420. if (!alternative_names.insert(alternative->name()).second) {
  421. return CompilationError(alternative->source_loc())
  422. << "Duplicate name `" << alternative->name()
  423. << "` in choice type";
  424. }
  425. }
  426. CARBON_RETURN_IF_ERROR(enclosing_scope.Add(choice.name(), &choice));
  427. break;
  428. }
  429. case DeclarationKind::VariableDeclaration: {
  430. auto& var = cast<VariableDeclaration>(declaration);
  431. CARBON_RETURN_IF_ERROR(ResolveNames(var.binding(), enclosing_scope));
  432. if (var.has_initializer()) {
  433. CARBON_RETURN_IF_ERROR(
  434. ResolveNames(var.initializer(), enclosing_scope));
  435. }
  436. break;
  437. }
  438. case DeclarationKind::SelfDeclaration: {
  439. CARBON_FATAL() << "Unreachable: resolving names for `Self` declaration";
  440. }
  441. case DeclarationKind::AliasDeclaration: {
  442. CARBON_RETURN_IF_ERROR(ResolveNames(
  443. cast<AliasDeclaration>(declaration).target(), enclosing_scope));
  444. break;
  445. }
  446. }
  447. return Success();
  448. }
  449. auto ResolveNames(AST& ast) -> ErrorOr<Success> {
  450. StaticScope file_scope;
  451. for (auto declaration : ast.declarations) {
  452. CARBON_RETURN_IF_ERROR(AddExposedNames(*declaration, file_scope));
  453. }
  454. for (auto declaration : ast.declarations) {
  455. CARBON_RETURN_IF_ERROR(ResolveNames(*declaration, file_scope));
  456. }
  457. return ResolveNames(**ast.main_call, file_scope);
  458. }
  459. } // namespace Carbon