resolve_names.cpp 19 KB

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