ReferenceResolvingPass.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright (c) 2023, Dan Klishch <danilklishch@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/HashMap.h>
  7. #include "AST/AST.h"
  8. #include "Compiler/Passes/ReferenceResolvingPass.h"
  9. #include "Function.h"
  10. namespace JSSpecCompiler {
  11. void ReferenceResolvingPass::process_function()
  12. {
  13. for (auto argument : m_function->m_arguments)
  14. m_function->m_local_variables.set(argument.name, make_ref_counted<NamedVariableDeclaration>(argument.name));
  15. GenericASTPass::process_function();
  16. }
  17. RecursionDecision ReferenceResolvingPass::on_entry(Tree tree)
  18. {
  19. if (auto binary_operation = as<BinaryOperation>(tree); binary_operation) {
  20. if (binary_operation->m_operation != BinaryOperator::Declaration)
  21. return RecursionDecision::Recurse;
  22. binary_operation->m_operation = BinaryOperator::Assignment;
  23. if (auto variable_name = as<UnresolvedReference>(binary_operation->m_left); variable_name) {
  24. auto name = variable_name->m_name;
  25. if (!m_function->m_local_variables.contains(name))
  26. m_function->m_local_variables.set(name, make_ref_counted<NamedVariableDeclaration>(name));
  27. }
  28. }
  29. return RecursionDecision::Recurse;
  30. }
  31. void ReferenceResolvingPass::on_leave(Tree tree)
  32. {
  33. if (auto reference = as<UnresolvedReference>(tree); reference) {
  34. auto name = reference->m_name;
  35. if (name.starts_with("[["sv) && name.ends_with("]]"sv)) {
  36. replace_current_node_with(make_ref_counted<SlotName>(name.substring_view(2, name.length() - 4)));
  37. return;
  38. }
  39. if (auto it = m_function->m_local_variables.find(name); it != m_function->m_local_variables.end()) {
  40. replace_current_node_with(make_ref_counted<Variable>(it->value));
  41. return;
  42. }
  43. if (auto function = m_translation_unit->find_declaration_by_name(name)) {
  44. replace_current_node_with(make_ref_counted<FunctionPointer>(function));
  45. return;
  46. }
  47. }
  48. }
  49. }