resolve_names.cpp 18 KB

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