From 641d7a3a855794dc7f16b15e49d8165c88b19a01 Mon Sep 17 00:00:00 2001 From: Lexy Plateau Date: Thu, 17 Sep 2026 16:02:35 +0200 Subject: [PATCH 1/8] feat(import solver): track what packages are available (when imported directly and indirectly) to a given package --- include/Ark/Compiler/AST/Import.hpp | 9 ++ include/Ark/Compiler/AST/Namespace.hpp | 7 ++ .../NameResolution/NameResolutionPass.hpp | 9 +- include/Ark/Compiler/Package/ImportSolver.hpp | 16 ++- src/arkreactor/Compiler/Macros/Processor.cpp | 2 +- .../NameResolution/NameResolutionPass.cpp | 18 +++ .../Compiler/Package/ImportSolver.cpp | 107 ++++++++++++------ src/arkreactor/Compiler/Welder.cpp | 2 + 8 files changed, 132 insertions(+), 38 deletions(-) diff --git a/include/Ark/Compiler/AST/Import.hpp b/include/Ark/Compiler/AST/Import.hpp index 532bbae7..43bbc24f 100644 --- a/include/Ark/Compiler/AST/Import.hpp +++ b/include/Ark/Compiler/AST/Import.hpp @@ -88,6 +88,15 @@ namespace Ark::internal return with_prefix && symbols.empty(); } }; + + [[nodiscard]] inline bool operator==(const Import& lhs, const Import& rhs) + { + return lhs.prefix == rhs.prefix && + lhs.package == rhs.package && + lhs.with_prefix == rhs.with_prefix && + lhs.is_glob == rhs.is_glob && + lhs.symbols == rhs.symbols; + } } #endif diff --git a/include/Ark/Compiler/AST/Namespace.hpp b/include/Ark/Compiler/AST/Namespace.hpp index 3e039f68..9920a367 100644 --- a/include/Ark/Compiler/AST/Namespace.hpp +++ b/include/Ark/Compiler/AST/Namespace.hpp @@ -5,6 +5,8 @@ #include #include +#include + namespace Ark::internal { class Node; @@ -12,9 +14,14 @@ namespace Ark::internal struct Namespace { std::string name; + + // todo: not really important to keep? bool is_glob; // (import package:*) bool with_prefix; // (import package) std::vector symbols; // (import package :a :b) + + std::vector imports; + std::shared_ptr ast; }; diff --git a/include/Ark/Compiler/NameResolution/NameResolutionPass.hpp b/include/Ark/Compiler/NameResolution/NameResolutionPass.hpp index 0555e260..ab801efe 100644 --- a/include/Ark/Compiler/NameResolution/NameResolutionPass.hpp +++ b/include/Ark/Compiler/NameResolution/NameResolutionPass.hpp @@ -33,10 +33,17 @@ namespace Ark::internal */ explicit NameResolutionPass(unsigned debug, Statistics* stats_collector = nullptr); + /** + * @brief Configure the NameResolutionPass with the import list of the root package + * + * @param root_import_list + */ + void setup(const std::vector& root_import_list); + /** * @brief Start visiting the given AST, checking for mutability violation and unbound variables * - * @param ast AST to analyze + * @param ast AST to analyse */ void process(const Node& ast); diff --git a/include/Ark/Compiler/Package/ImportSolver.hpp b/include/Ark/Compiler/Package/ImportSolver.hpp index 50b3700e..810c576d 100644 --- a/include/Ark/Compiler/Package/ImportSolver.hpp +++ b/include/Ark/Compiler/Package/ImportSolver.hpp @@ -50,10 +50,13 @@ namespace Ark::internal [[nodiscard]] const Node& ast() const noexcept; + [[nodiscard]] const std::vector& rootImportList(); + private: struct ImportWithSource { std::filesystem::path file; + std::string package; Import import; }; @@ -64,23 +67,28 @@ namespace Ark::internal std::stack m_imports; std::unordered_map m_packages; ///< Package name to package AST & data mapping std::vector m_imported; ///< List of imports, in the order they were found and parsed + std::unordered_map> m_package_to_imports; + + void discoverAllPackages(); + + [[nodiscard]] static std::string importNodeToPackage(const Node& node); /** * @brief Visits the AST, looking for import nodes to replace with their parsed module version * @param ast + * @param current_namespace_package * @return */ - std::pair findAndReplaceImports(const Node& ast); + std::pair findAndReplaceImports(const Node& ast, const std::string& current_namespace_package); /** * @brief Parse a given file and returns a list of its imports. * The AST is parsed and stored in m_modules[import.prefix] * - * @param source path to the file containing the import - * @param import current import directive + * @param source details about the import * @return std::vector imports found in the processed file */ - std::vector parseImport(const std::filesystem::path& source, const Import& import); + std::vector parseImport(const ImportWithSource& source); /** * @brief Search for an import file, using the root file path diff --git a/src/arkreactor/Compiler/Macros/Processor.cpp b/src/arkreactor/Compiler/Macros/Processor.cpp index cda6f22e..54a2b004 100644 --- a/src/arkreactor/Compiler/Macros/Processor.cpp +++ b/src/arkreactor/Compiler/Macros/Processor.cpp @@ -187,7 +187,7 @@ namespace Ark::internal // must be in a list node. Then depth - 1 is safe as depth is at least 1. // Using a decreased value of depth ensures that macros are stored in the correct scope, // and not deleted when the namespace traversal ends. - processNode(namespace_ast, depth - 1, /* is_processing_namespace= */ true); + processNode(namespace_ast, depth > 0 ? depth - 1 : 0, /* is_processing_namespace= */ true); } } diff --git a/src/arkreactor/Compiler/NameResolution/NameResolutionPass.cpp b/src/arkreactor/Compiler/NameResolution/NameResolutionPass.cpp index 43ee59d1..76f66f37 100644 --- a/src/arkreactor/Compiler/NameResolution/NameResolutionPass.cpp +++ b/src/arkreactor/Compiler/NameResolution/NameResolutionPass.cpp @@ -4,6 +4,9 @@ #include #include +// todo: remove +#include + namespace Ark::internal { NameResolutionPass::NameResolutionPass(const unsigned debug, Statistics* stats_collector) : @@ -24,6 +27,21 @@ namespace Ark::internal m_language_symbols.emplace(Language::Apply); } + void NameResolutionPass::setup(const std::vector& root_import_list) + { + // todo: configure the m_scope_resolver with the root import list + m_logger.info("Configuring NameResolutionPass. Root is importing:"); + for (const Import& import : root_import_list) + { + if (import.is_glob) + m_logger.info(" - {} :*", import.toPackageString()); + else if (import.with_prefix) + m_logger.info(" - {}", import.toPackageString()); + else + m_logger.info(" - {} :{}", import.toPackageString(), fmt::join(import.symbols, " :")); + } + } + void NameResolutionPass::process(const Node& ast) { m_logger.traceStart("process"); diff --git a/src/arkreactor/Compiler/Package/ImportSolver.cpp b/src/arkreactor/Compiler/Package/ImportSolver.cpp index e3aa7c41..17841bdb 100644 --- a/src/arkreactor/Compiler/Package/ImportSolver.cpp +++ b/src/arkreactor/Compiler/Package/ImportSolver.cpp @@ -13,8 +13,7 @@ namespace Ark::internal ImportSolver::ImportSolver(const unsigned debug, const std::vector& libenv, Statistics* stats_collector) : Pass("ImportSolver", debug, stats_collector), m_debug_level(debug), - m_libenv(libenv), - m_ast() + m_libenv(libenv) {} ImportSolver& ImportSolver::setup(const std::filesystem::path& root, const std::vector& origin_imports) @@ -23,7 +22,7 @@ namespace Ark::internal m_root = is_directory(root) ? root : root.parent_path(); for (const auto& origin_import : std::ranges::reverse_view(origin_imports)) - m_imports.push({ root, origin_import }); + m_imports.push({ root, "", origin_import }); return *this; } @@ -34,8 +33,8 @@ namespace Ark::internal while (!m_imports.empty()) { - ImportWithSource source = m_imports.top(); - m_logger.debug("Importing {}", source.import.toPackageString()); + const ImportWithSource source = m_imports.top(); + m_logger.debug("Importing {} from '{}' (in package '{}')", source.import.toPackageString(), source.file.string(), source.package); // Remove the top element to process the other imports // It needs to be removed first because we might be adding @@ -43,8 +42,12 @@ namespace Ark::internal m_imports.pop(); const auto package = source.import.toPackageString(); + // register that the current file is importing another one, with its attributes (glob, prefix, symbols...) + m_package_to_imports[source.package].push_back(source.import); + if (m_packages.contains(package)) { + // todo: actually don't do that, we need to keep a source -> vec that's accurate // merge the definition, so that we can generate valid Full Qualified Names in the name & scope resolver m_packages[package].import.with_prefix |= source.import.with_prefix; m_packages[package].import.is_glob |= source.import.is_glob; @@ -53,21 +56,60 @@ namespace Ark::internal } else { - // NOTE: since the "file" (=root) argument doesn't change between all calls, we could get rid of it - std::vector temp = parseImport(source.file, source.import); + std::vector temp = parseImport(source); for (auto& additional_import : std::ranges::reverse_view(temp)) m_imports.push(additional_import); } } + m_logger.traceStart("discoverAllPackages"); + discoverAllPackages(); + addStat("ImportSolver.discoverAllPackages", m_logger.traceEnd()); + m_logger.traceStart("findAndReplaceImports"); - m_ast = findAndReplaceImports(origin_ast).first; + m_ast = findAndReplaceImports(origin_ast, /* current_namespace_package= */ "").first; addStat("ImportSolver.findAndReplaceImports", m_logger.traceEnd()); addStat("ImportSolver.process", m_logger.traceEnd()); } - std::pair ImportSolver::findAndReplaceImports(const Node& ast) + void ImportSolver::discoverAllPackages() + { + for (const std::string& package : std::ranges::views::keys(m_package_to_imports)) + { + std::vector import_list = m_package_to_imports[package]; + for (std::size_t i = 0; i < import_list.size(); ++i) + { + // if we try to add ourselves to the current import list, we'll end up in an infinite loop + if (import_list[i].toPackageString() == package) + continue; + + // todo: this might fail on unknown imports? + std::vector indirect_imports = m_package_to_imports[import_list[i].toPackageString()]; + std::erase_if(indirect_imports, [&import_list](const Import& import) -> bool { + return std::ranges::find(import_list, import) != import_list.end(); + }); + for (const Import& import : indirect_imports) + import_list.emplace_back(import); + } + + m_package_to_imports[package] = import_list; + } + } + + std::string ImportSolver::importNodeToPackage(const Node& node) + { + // compute the package string: foo.bar.egg + return std::accumulate( + std::next(node.constList().begin()), + node.constList().end(), + node.constList()[0].string(), + [](const std::string& acc, const Node& elem) -> std::string { + return acc + "." + elem.string(); + }); + } + + std::pair ImportSolver::findAndReplaceImports(const Node& ast, const std::string& current_namespace_package) { Node x = ast; if (x.nodeType() == NodeType::List) @@ -75,15 +117,7 @@ namespace Ark::internal if (x.constList().size() >= 2 && x.constList()[0].nodeType() == NodeType::Keyword && x.constList()[0].keyword() == Keyword::Import) { - // compute the package string: foo.bar.egg - const auto import_node = x.constList()[1].constList(); - const std::string package = std::accumulate( - std::next(import_node.begin()), - import_node.end(), - import_node[0].string(), - [](const std::string& acc, const Node& elem) -> std::string { - return acc + "." + elem.string(); - }); + const std::string package = importNodeToPackage(x.constList()[1]); // if it wasn't imported already, register it if (std::ranges::find(m_imported, package) == m_imported.end()) @@ -111,7 +145,8 @@ namespace Ark::internal .is_glob = import.is_glob, .with_prefix = import.with_prefix, .symbols = import.symbols, - .ast = std::make_shared(findAndReplaceImports(x).first) }); + .imports = m_package_to_imports[package], + .ast = std::make_shared(findAndReplaceImports(x, /* current_namespace_package= */ package).first) }); x.arkNamespace().ast->setPositionFrom(ast); } @@ -127,7 +162,7 @@ namespace Ark::internal { for (std::size_t i = 0; i < x.constList().size(); ++i) { - auto [node, is_import] = findAndReplaceImports(x.constList()[i]); + auto [node, is_import] = findAndReplaceImports(x.constList()[i], current_namespace_package); x.list()[i] = node; } } @@ -141,11 +176,18 @@ namespace Ark::internal return m_ast; } - std::vector ImportSolver::parseImport(const std::filesystem::path& source, const Import& import) + const std::vector& ImportSolver::rootImportList() { - m_logger.traceStart(fmt::format("parseImport {}", source.string())); + // even if we don't have registered any import for the root package, operator[] will create the key "", + // and we'll be able to return an empty import list, as expected + return m_package_to_imports[""]; + } + + std::vector ImportSolver::parseImport(const ImportWithSource& source) + { + m_logger.traceStart(fmt::format("parseImport {}", source.file.string())); - const auto path = findFile(source, import); + const auto path = findFile(source.file, source.import); if (path.extension() == ".arkm") // Nothing to import in case of modules { // Creating an import node that will stay there when visiting the AST and @@ -155,7 +197,7 @@ namespace Ark::internal auto package_node = Node(NodeType::List); std::ranges::transform( - import.package, + source.import.package, std::back_inserter(package_node.list()), [](const std::string& stem) { return Node(NodeType::String, stem); }); @@ -163,9 +205,9 @@ namespace Ark::internal // empty symbols list module_node.push_back(Node(NodeType::List)); - m_packages[import.toPackageString()] = Package { + m_packages[source.import.toPackageString()] = Package { module_node, - import, + source.import, true }; @@ -175,20 +217,21 @@ namespace Ark::internal Parser parser(m_debug_level); const std::string code = Utils::readFile(path.generic_string()); parser.process(path.string(), code); - m_packages[import.toPackageString()] = Package { + const std::vector& imports = parser.imports(); + + m_packages[source.import.toPackageString()] = Package { parser.ast(), - import, + source.import, false }; - addStat(fmt::format("ImportSolver.parseImport({})", import.toPackageString()), m_logger.traceEnd()); + addStat(fmt::format("ImportSolver.parseImport({})", source.import.toPackageString()), m_logger.traceEnd()); - auto imports = parser.imports(); std::vector output; std::ranges::transform( imports, - std::back_inserter(output), [&path](const Import& i) { - return ImportWithSource { path, i }; + std::back_inserter(output), [&path, &source](const Import& i) { + return ImportWithSource { path, source.import.toPackageString(), i }; }); return output; } diff --git a/src/arkreactor/Compiler/Welder.cpp b/src/arkreactor/Compiler/Welder.cpp index 8177382f..63092da1 100644 --- a/src/arkreactor/Compiler/Welder.cpp +++ b/src/arkreactor/Compiler/Welder.cpp @@ -213,6 +213,8 @@ namespace Ark if ((m_features & FeatureNameResolver) != 0) { + if ((m_features & FeatureImportSolver) != 0) + m_name_resolver.setup(m_import_solver.rootImportList()); m_name_resolver.process(m_computed_ast); m_computed_ast = m_name_resolver.ast(); } From feec539ffd1ad8516f685d64f716ede6f6b49319 Mon Sep 17 00:00:00 2001 From: Lexy Plateau Date: Mon, 16 Nov 2026 10:52:14 +0100 Subject: [PATCH 2/8] feat(tests): keep on going even when compilation fails --- tests/unittests/Suites/ExamplesSuite.cpp | 19 +++++++++------ tests/unittests/Suites/LangSuite.cpp | 31 ++++++++++++++---------- tests/unittests/Suites/RosettaSuite.cpp | 21 +++++++++------- tests/unittests/Suites/UngolfedSuite.cpp | 21 +++++++++------- 4 files changed, 54 insertions(+), 38 deletions(-) diff --git a/tests/unittests/Suites/ExamplesSuite.cpp b/tests/unittests/Suites/ExamplesSuite.cpp index f07c9f41..12db9870 100644 --- a/tests/unittests/Suites/ExamplesSuite.cpp +++ b/tests/unittests/Suites/ExamplesSuite.cpp @@ -23,20 +23,25 @@ ut::suite<"Examples"> examples_suite = [] { Ark::State state({ lib_path }); state.setArgs({}); + bool ok = false; + try { - const bool ok = mut(state).doFile(path); - expect(ok) << fatal << "compilation failed"; + ok = mut(state).doFile(path); + expect(ok) << "compilation failed"; } catch (const Ark::CodeError&) { - expect(false) << fatal << "encountered an exception while compiling"; + expect(false) << "encountered an exception while compiling"; } - Ark::VM vm(state); - should("return exit code 0") = [&] { - expect(mut(vm).run() == 0_i); - }; + if (ok) + { + Ark::VM vm(state); + should("return exit code 0") = [&] { + expect(mut(vm).run() == 0_i); + }; + } }; } }; diff --git a/tests/unittests/Suites/LangSuite.cpp b/tests/unittests/Suites/LangSuite.cpp index 0f1e4731..44e59a5d 100644 --- a/tests/unittests/Suites/LangSuite.cpp +++ b/tests/unittests/Suites/LangSuite.cpp @@ -11,27 +11,32 @@ void testResource(Ark::State& state, const bool is_res, const std::string& path, { using namespace ut; + bool ok = false; + try { - const bool ok = mut(state).doFile(is_res ? getResourcePath(path) : path, features); - expect(ok) << fatal << "compilation failed"; + ok = mut(state).doFile(is_res ? getResourcePath(path) : path, features); + expect(ok) << "compilation failed"; } catch (const Ark::CodeError&) { - expect(false) << fatal << "encountered an exception while compiling"; + expect(false) << "encountered an exception while compiling"; } - Ark::VM vm(state); - should("return exit code 0") = [&] { - expect(mut(vm).run() == 0_i); - }; + if (ok) + { + Ark::VM vm(state); + should("return exit code 0") = [&] { + expect(mut(vm).run() == 0_i); + }; - should("have no failures") = [&] { - const auto failure_count = mut(vm).operator[]("failure_count"); - expect(failure_count.valueType() == Ark::ValueType::Number && - failure_count.number() == 0.0) - << "failure_count = 0\n"; - }; + should("have no failures") = [&] { + const auto failure_count = mut(vm).operator[]("failure_count"); + expect(failure_count.valueType() == Ark::ValueType::Number && + failure_count.number() == 0.0) + << "failure_count = 0\n"; + }; + } } ut::suite<"Lang"> lang_suite = [] { diff --git a/tests/unittests/Suites/RosettaSuite.cpp b/tests/unittests/Suites/RosettaSuite.cpp index 7bf9a1f7..087642cb 100644 --- a/tests/unittests/Suites/RosettaSuite.cpp +++ b/tests/unittests/Suites/RosettaSuite.cpp @@ -1,7 +1,5 @@ #include -#include - #include #include @@ -16,22 +14,27 @@ ut::suite<"Rosetta"> rosetta_suite = [] { [](TestData&& data) { Ark::State state({ lib_path }); + bool ok = false; + should("compile " + data.stem) = [&] { try { - const bool ok = mut(state).doFile(data.path); - expect(ok) << fatal << "compilation failed"; + ok = mut(state).doFile(data.path); + expect(ok) << "compilation failed"; } catch (const Ark::CodeError&) { - expect(false) << fatal << "encountered an exception while compiling"; + expect(false) << "encountered an exception while compiling"; } }; - Ark::VM vm(state); - should("run " + data.stem + " without errors (exit code 0)") = [&] { - expect(mut(vm).run() == 0); - }; + if (ok) + { + Ark::VM vm(state); + should("run " + data.stem + " without errors (exit code 0)") = [&] { + expect(mut(vm).run() == 0); + }; + } }); }; }; diff --git a/tests/unittests/Suites/UngolfedSuite.cpp b/tests/unittests/Suites/UngolfedSuite.cpp index e8ffe9f9..0611d665 100644 --- a/tests/unittests/Suites/UngolfedSuite.cpp +++ b/tests/unittests/Suites/UngolfedSuite.cpp @@ -1,7 +1,5 @@ #include -#include - #include #include @@ -16,22 +14,27 @@ ut::suite<"Ungolfed"> ungolfed_suite = [] { [](TestData&& data) { Ark::State state({ lib_path }); + bool ok = false; + should("compile " + data.stem) = [&] { try { - const bool ok = mut(state).doFile(data.path); - expect(ok) << fatal << "compilation failed"; + ok = mut(state).doFile(data.path); + expect(ok) << "compilation failed"; } catch (const Ark::CodeError&) { - expect(false) << fatal << "encountered an exception while compiling"; + expect(false) << "encountered an exception while compiling"; } }; - Ark::VM vm(state); - should("run " + data.stem + " without errors (exit code 0)") = [&] { - expect(mut(vm).run() == 0); - }; + if (ok) + { + Ark::VM vm(state); + should("run " + data.stem + " without errors (exit code 0)") = [&] { + expect(mut(vm).run() == 0); + }; + } }); }; }; From 29ec9097c565a2c4eab12b4e00207863fdc4bc59 Mon Sep 17 00:00:00 2001 From: Lexy Plateau Date: Mon, 16 Nov 2026 16:21:54 +0100 Subject: [PATCH 3/8] fix: lowercase packages' names when parsing --- src/arkreactor/Compiler/AST/Parser.cpp | 19 ++++++++++++++++--- .../Compiler/Package/ImportSolver.cpp | 11 +---------- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/src/arkreactor/Compiler/AST/Parser.cpp b/src/arkreactor/Compiler/AST/Parser.cpp index e20c6f78..ee41c614 100644 --- a/src/arkreactor/Compiler/AST/Parser.cpp +++ b/src/arkreactor/Compiler/AST/Parser.cpp @@ -286,6 +286,18 @@ namespace Ark::internal return positioned(leaf, filepos); } + std::string& lowercasePrefix(std::string& prefix) + { + // prefix to lowercase ; usually considered unsafe (https://devblogs.microsoft.com/oldnewthing/20241007-00/?p=110345) + // but we are dealing with prefix from filenames, thus we can somewhat assume we are in safe zone + std::ranges::transform( + prefix, prefix.begin(), + [](auto c) { + return std::tolower(c); + }); + return prefix; + } + std::optional Parser::import_(const FilePosition filepos) { std::optional leaf { NodeType::List }; @@ -316,7 +328,7 @@ namespace Ark::internal backtrack(pos); errorWithNextToken(fmt::format("Import name too long, expected at most 255 characters, got {}", import_data.prefix.size())); } - import_data.package.push_back(import_data.prefix); + import_data.package.push_back(lowercasePrefix(import_data.prefix)); Node packageNode = positioned(Node(NodeType::List), getCursor()).attachNearestCommentBefore(comment); packageNode.push_back(Node(NodeType::Symbol, import_data.prefix)); @@ -337,8 +349,9 @@ namespace Ark::internal { packageNode.push_back(positioned(Node(NodeType::Symbol, path), package_pos)); - import_data.package.push_back(path); - import_data.prefix = path; // in the end we will store the last element of the package, which is what we want + // in the end we will store the last element of the package, which is what we want + import_data.prefix = lowercasePrefix(path); + import_data.package.push_back(import_data.prefix); if (path.size() > 255) { diff --git a/src/arkreactor/Compiler/Package/ImportSolver.cpp b/src/arkreactor/Compiler/Package/ImportSolver.cpp index 17841bdb..37d58b2f 100644 --- a/src/arkreactor/Compiler/Package/ImportSolver.cpp +++ b/src/arkreactor/Compiler/Package/ImportSolver.cpp @@ -131,17 +131,8 @@ namespace Ark::internal { const auto import = m_packages[package].import; - // prefix to lowercase ; usually considered unsafe (https://devblogs.microsoft.com/oldnewthing/20241007-00/?p=110345) - // but we are dealing with prefix from filenames, thus we can somewhat assume we are in safe zone - std::string prefix = import.prefix; - std::ranges::transform( - prefix, prefix.begin(), - [](auto c) { - return std::tolower(c); - }); - x = Node(Namespace { - .name = prefix, + .name = import.prefix, .is_glob = import.is_glob, .with_prefix = import.with_prefix, .symbols = import.symbols, From eda6c4a35c02dc50454a7ef4ad2d3e98593302e6 Mon Sep 17 00:00:00 2001 From: Lexy Plateau Date: Wed, 18 Nov 2026 15:17:45 +0100 Subject: [PATCH 4/8] refactor(import solver): current namespace information is useless when replacing imports --- include/Ark/Compiler/Package/ImportSolver.hpp | 3 +-- .../Compiler/Package/ImportSolver.cpp | 19 ++++++++----------- 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/include/Ark/Compiler/Package/ImportSolver.hpp b/include/Ark/Compiler/Package/ImportSolver.hpp index 810c576d..de00f010 100644 --- a/include/Ark/Compiler/Package/ImportSolver.hpp +++ b/include/Ark/Compiler/Package/ImportSolver.hpp @@ -76,10 +76,9 @@ namespace Ark::internal /** * @brief Visits the AST, looking for import nodes to replace with their parsed module version * @param ast - * @param current_namespace_package * @return */ - std::pair findAndReplaceImports(const Node& ast, const std::string& current_namespace_package); + std::pair findAndReplaceImports(const Node& ast); /** * @brief Parse a given file and returns a list of its imports. diff --git a/src/arkreactor/Compiler/Package/ImportSolver.cpp b/src/arkreactor/Compiler/Package/ImportSolver.cpp index 37d58b2f..0ab6856e 100644 --- a/src/arkreactor/Compiler/Package/ImportSolver.cpp +++ b/src/arkreactor/Compiler/Package/ImportSolver.cpp @@ -47,17 +47,15 @@ namespace Ark::internal if (m_packages.contains(package)) { - // todo: actually don't do that, we need to keep a source -> vec that's accurate - // merge the definition, so that we can generate valid Full Qualified Names in the name & scope resolver - m_packages[package].import.with_prefix |= source.import.with_prefix; - m_packages[package].import.is_glob |= source.import.is_glob; + // we need to keep track of all the symbols imported for a package, + // so that NameResolutionPass can check that all the names exist for (auto&& symbol : source.import.symbols) m_packages[package].import.symbols.push_back(symbol); } else { std::vector temp = parseImport(source); - for (auto& additional_import : std::ranges::reverse_view(temp)) + for (const auto& additional_import : std::ranges::reverse_view(temp)) m_imports.push(additional_import); } } @@ -67,7 +65,7 @@ namespace Ark::internal addStat("ImportSolver.discoverAllPackages", m_logger.traceEnd()); m_logger.traceStart("findAndReplaceImports"); - m_ast = findAndReplaceImports(origin_ast, /* current_namespace_package= */ "").first; + m_ast = findAndReplaceImports(origin_ast).first; addStat("ImportSolver.findAndReplaceImports", m_logger.traceEnd()); addStat("ImportSolver.process", m_logger.traceEnd()); @@ -89,8 +87,7 @@ namespace Ark::internal std::erase_if(indirect_imports, [&import_list](const Import& import) -> bool { return std::ranges::find(import_list, import) != import_list.end(); }); - for (const Import& import : indirect_imports) - import_list.emplace_back(import); + std::ranges::copy(indirect_imports, std::back_inserter(import_list)); } m_package_to_imports[package] = import_list; @@ -109,7 +106,7 @@ namespace Ark::internal }); } - std::pair ImportSolver::findAndReplaceImports(const Node& ast, const std::string& current_namespace_package) + std::pair ImportSolver::findAndReplaceImports(const Node& ast) { Node x = ast; if (x.nodeType() == NodeType::List) @@ -137,7 +134,7 @@ namespace Ark::internal .with_prefix = import.with_prefix, .symbols = import.symbols, .imports = m_package_to_imports[package], - .ast = std::make_shared(findAndReplaceImports(x, /* current_namespace_package= */ package).first) }); + .ast = std::make_shared(findAndReplaceImports(x).first) }); x.arkNamespace().ast->setPositionFrom(ast); } @@ -153,7 +150,7 @@ namespace Ark::internal { for (std::size_t i = 0; i < x.constList().size(); ++i) { - auto [node, is_import] = findAndReplaceImports(x.constList()[i], current_namespace_package); + auto [node, is_import] = findAndReplaceImports(x.constList()[i]); x.list()[i] = node; } } From 4b6499791dd0cad1a82e617ec5605e3e4ca404ac Mon Sep 17 00:00:00 2001 From: Lexy Plateau Date: Sun, 8 Nov 2026 15:57:40 +0100 Subject: [PATCH 5/8] feat(name resolution): split registering symbols and qualifying them in two passes, now using a better name qualification algorithm. The new algorithm tracks the import list of each namespace, to allow precisely qualifying names, instead of merging all attributes of all imports of a package into the single namespace it represents (which could lead to a namespace being tagged as imported glob, imported symbols and prefixed). --- examples/closures.ark | 2 +- include/Ark/Compiler/AST/Import.hpp | 31 +- include/Ark/Compiler/AST/Namespace.hpp | 14 +- include/Ark/Compiler/Common.hpp | 2 - .../NameResolution/NameResolutionPass.hpp | 19 +- .../Compiler/NameResolution/ScopeResolver.hpp | 55 +- .../Compiler/NameResolution/StaticScope.hpp | 50 +- src/arkreactor/Compiler/AST/Parser.cpp | 12 +- .../NameResolution/NameResolutionPass.cpp | 560 +++++++++++------- .../Compiler/NameResolution/ScopeResolver.cpp | 174 +++--- .../Compiler/NameResolution/StaticScope.cpp | 102 +--- .../Compiler/Package/ImportSolver.cpp | 23 +- src/arkreactor/Compiler/Welder.cpp | 4 +- .../resources/CompilerSuite/ir/closures.ark | 2 +- .../CompilerSuite/ir/closures.expected | 2 +- .../CompilerSuite/optimised_ir/closures.ark | 2 +- .../optimised_ir/closures.expected | 2 +- .../unbound_but_namespace.expected | 2 +- .../use_not_in_import_list.expected | 2 +- 19 files changed, 556 insertions(+), 504 deletions(-) diff --git a/examples/closures.ark b/examples/closures.ark index 6277007f..83169cd7 100644 --- a/examples/closures.ark +++ b/examples/closures.ark @@ -33,7 +33,7 @@ # this function will return a closure capturing the number given # and modifying its value each time we'll call the closure, returning # the new number -(let countdown-from (fun (number) +(let countdown-from (fun ((mut number)) (fun (&number) { (set number (- number 1)) number }))) diff --git a/include/Ark/Compiler/AST/Import.hpp b/include/Ark/Compiler/AST/Import.hpp index 43bbc24f..6ecb4ede 100644 --- a/include/Ark/Compiler/AST/Import.hpp +++ b/include/Ark/Compiler/AST/Import.hpp @@ -22,13 +22,21 @@ namespace Ark::internal */ std::string prefix; + /** + * @brief Package with all the segments + * @details Example: `(import foo.bar)` => `foo.bar` + * `(import foo.bar.egg:*)` => `foo.bar.egg` + * `(import foo :a :b :c)` => `foo` + */ + std::string package; + /** * @brief Package with all the segments * @details Example: `(import foo.bar)` => `{foo, bar}` * `(import foo.bar.egg:*)` => `{foo, bar, egg}` * `(import foo :a :b :c)` => `{foo}` */ - std::vector package; + std::vector segments; /** * @brief Import with prefix (import package) @@ -47,21 +55,6 @@ namespace Ark::internal */ std::vector symbols; - /** - * - * @return a package string, eg a.b.c - */ - [[nodiscard]] std::string toPackageString() const - { - return std::accumulate( - package.begin() + 1, - package.end(), - package.front(), - [](const std::string& left, const std::string& right) { - return left + "." + right; - }); - } - /** * * @return a package as a path, eg a/b/c @@ -69,9 +62,9 @@ namespace Ark::internal [[nodiscard]] std::string packageToPath() const { return std::accumulate( - std::next(package.begin()), - package.end(), - package[0], + std::next(segments.begin()), + segments.end(), + segments[0], [](const std::string& a, const std::string& b) { return a + "/" + b; }); diff --git a/include/Ark/Compiler/AST/Namespace.hpp b/include/Ark/Compiler/AST/Namespace.hpp index 9920a367..ec4ea92d 100644 --- a/include/Ark/Compiler/AST/Namespace.hpp +++ b/include/Ark/Compiler/AST/Namespace.hpp @@ -13,22 +13,16 @@ namespace Ark::internal struct Namespace { - std::string name; - - // todo: not really important to keep? - bool is_glob; // (import package:*) - bool with_prefix; // (import package) - std::vector symbols; // (import package :a :b) - + std::string name; ///< Prefix for the namespace, eg egg + std::string package; ///< Complete package name, eg foo.bar.egg + std::vector symbols; std::vector imports; - std::shared_ptr ast; }; inline bool operator==(const Namespace& A, const Namespace& B) { - return A.name == B.name && A.is_glob == B.is_glob && - A.with_prefix == B.with_prefix; + return A.name == B.name && A.ast.get() == B.ast.get(); } inline bool operator<([[maybe_unused]] const Namespace&, [[maybe_unused]] const Namespace&) diff --git a/include/Ark/Compiler/Common.hpp b/include/Ark/Compiler/Common.hpp index 435e7fc4..8bc27aaa 100644 --- a/include/Ark/Compiler/Common.hpp +++ b/include/Ark/Compiler/Common.hpp @@ -101,8 +101,6 @@ namespace Ark::internal "del" }; - constexpr std::string_view HiddenSymbolSuffix = "#hidden"; - namespace Language { constexpr std::string_view AppendInPlace = "append!"; diff --git a/include/Ark/Compiler/NameResolution/NameResolutionPass.hpp b/include/Ark/Compiler/NameResolution/NameResolutionPass.hpp index ab801efe..d3d674cc 100644 --- a/include/Ark/Compiler/NameResolution/NameResolutionPass.hpp +++ b/include/Ark/Compiler/NameResolution/NameResolutionPass.hpp @@ -60,7 +60,7 @@ namespace Ark::internal * @param sym * @param is_mutable true if the symbol is inside mut/set, false otherwise (let) */ - std::string addDefinedSymbol(const std::string& sym, bool is_mutable); + std::string qualifyAndRegisterSymbol(const std::string& sym, bool is_mutable); private: Node m_ast; @@ -71,28 +71,25 @@ namespace Ark::internal ScopeResolver m_scope_resolver; /** - * @brief Recursively visit nodes + * @brief Recursively visit nodes and register variable declarations * * @param node node to visit - * @param register_declarations whether or not the visit should register declarations */ - void visit(Node& node, bool register_declarations); + void registerDeclarations(Node& node); /** + * @brief Recursively visit nodes and updates symbol names * - * @param node a list node whose first child is a keyword - * @param keyword - * @param register_declarations whether or not the visit should register declarations + * @param node node to visit and update */ - void visitKeyword(Node& node, Keyword keyword, bool register_declarations); + void qualifyNames(Node& node); /** * @brief Register a given node in the symbol table * * @param symbol - * @param old_name old name for symbol, to replace it with the new one if it was renamed */ - void addSymbolNode(const Node& symbol, const std::string& old_name = ""); + void savedAsKnownSymbol(const Node& symbol); /** * @brief Checking if a symbol may be coming from a plugin @@ -103,7 +100,7 @@ namespace Ark::internal */ [[nodiscard]] bool mayBeFromPlugin(const std::string& name) const noexcept; - std::string updateSymbolWithFullyQualifiedName(Node& symbol); + std::string tryQualifyAndUpdateSymbol(Node& symbol) const; /** * @brief Checks for undefined symbols, not present in the defined symbols table diff --git a/include/Ark/Compiler/NameResolution/ScopeResolver.hpp b/include/Ark/Compiler/NameResolution/ScopeResolver.hpp index 0bd03dc4..b95cedd9 100644 --- a/include/Ark/Compiler/NameResolution/ScopeResolver.hpp +++ b/include/Ark/Compiler/NameResolution/ScopeResolver.hpp @@ -17,18 +17,37 @@ #include #include +#include + #include namespace Ark::internal { + enum class QualifyingFailReason + { + NotInSymbolList, + NeedPrefixing + }; + + struct QualifiedName + { + struct Match + { + QualifyingFailReason reason; + std::string name; + }; + + std::optional qualified_name; + std::vector alternatives; + }; + class ScopeResolver { public: /** * @brief Create a ScopeResolver - * @details Kickstart by create a default global scope */ - ScopeResolver(); + ScopeResolver() = default; ScopeResolver(const ScopeResolver&) = delete; ScopeResolver& operator=(const ScopeResolver&) = delete; @@ -47,12 +66,11 @@ namespace Ark::internal /** * @brief Create a new namespace scope - * @param name - * @param with_prefix - * @param is_glob - * @param symbols + * @param prefix + * @param package + * @param imports */ - void createNewNamespace(const std::string& name, bool with_prefix, bool is_glob, const std::vector& symbols); + void createNewNamespace(const std::string& prefix, const std::string& package, const std::vector& imports); /** * @brief Register a Declaration in the current (last) scope @@ -92,21 +110,13 @@ namespace Ark::internal */ [[nodiscard]] bool isInScope(const std::string& name) const; - /** - * @brief Get a FQN from a variable name in the nearest scope it is declared in - * - * @param name - * @return std::string - */ - [[nodiscard]] std::string getFullyQualifiedNameInNearestScope(const std::string& name) const; - /** * @brief Checks if a name can be fully qualified (allows only unprefixed names to be resolved by glob namespaces or inside their own namespace) * * @param name - * @return std::pair if the name can be fully qualified, first element is true ; second element is the FQN + * @return std::pair, std::string> if the name can be fully qualified, first element is nullopt ; second element is the FQN */ - [[nodiscard]] std::pair canFullyQualifyName(const std::string& name); + [[nodiscard]] std::pair, std::string> tryFullyQualifyName(const std::string& name) const; /** * @brief Return a non-owning raw pointer to the current scope @@ -118,8 +128,17 @@ namespace Ark::internal private: std::vector> m_scopes; + ankerl::unordered_dense::map> m_saved_scopes; + + [[nodiscard]] StaticScope* currentNamespace() const; - [[nodiscard]] std::string currentNamespace() const; + /** + * @brief Get a FQN from a variable name in the nearest scope it is declared in + * + * @param name + * @return QualifiedName + */ + [[nodiscard]] QualifiedName getFullyQualifiedNameInNearestScope(const std::string& name) const; }; } diff --git a/include/Ark/Compiler/NameResolution/StaticScope.hpp b/include/Ark/Compiler/NameResolution/StaticScope.hpp index 008297e2..bcefd831 100644 --- a/include/Ark/Compiler/NameResolution/StaticScope.hpp +++ b/include/Ark/Compiler/NameResolution/StaticScope.hpp @@ -13,12 +13,11 @@ #include #include -#include #include -#include #include #include +#include namespace Ark::internal { @@ -27,6 +26,7 @@ namespace Ark::internal std::string name; ///< End name, can be modified to be hidden std::string original_name; ///< Original name, with the prefix, without hidden namespaces bool is_mutable; + std::optional argument_count; ///< Number of arguments, if the declaration is of a function bool operator==(const Declaration& other) const = default; }; @@ -66,10 +66,9 @@ namespace Ark::internal * @brief Try to return a Declaration from this scope with a given name. * @param name * @param origin_namespace unused in StaticScope - * @param extensive_lookup unused in StaticScope * @return std::optional std::nullopt if the Declaration isn't in scope */ - [[nodiscard]] virtual std::optional get(const std::string& name, const std::string& origin_namespace, bool extensive_lookup); + [[nodiscard]] virtual std::optional get(const std::string& name, const std::string& origin_namespace); /** * @brief Given a Declaration name, compute its fully qualified name @@ -78,19 +77,10 @@ namespace Ark::internal */ [[nodiscard]] virtual std::string fullyQualifiedName(const std::string& name) const; - /** - * @brief Save a namespace scope to help with lookup - * - * @return true if the scope was saved, on NamespaceScope - * @return false on StaticScope - */ - virtual bool saveNamespace(std::unique_ptr&); - [[nodiscard]] virtual bool isNamespace() const; - [[nodiscard]] inline virtual bool isGlob() const { return false; } - [[nodiscard]] inline virtual std::string prefix() const { return ""; } - [[nodiscard]] inline virtual bool hasSymbol(const std::string&) const { return false; } - [[nodiscard]] inline virtual bool recursiveHasSymbol(const std::string&) { return false; } + [[nodiscard]] virtual std::string prefix() const { return ""; } + [[nodiscard]] virtual std::string package() const { return ""; } + [[nodiscard]] virtual std::vector imports() const { return {}; } private: std::unordered_set m_vars {}; @@ -99,7 +89,7 @@ namespace Ark::internal class ARK_API NamespaceScope final : public StaticScope { public: - NamespaceScope(std::string name, bool with_prefix, bool is_glob, const std::vector& symbols); + NamespaceScope(std::string prefix, const std::string& package, const std::vector& imports); NamespaceScope(const NamespaceScope&) = delete; NamespaceScope& operator=(const NamespaceScope&) = delete; @@ -117,10 +107,9 @@ namespace Ark::internal * @brief Try to return a Declaration from this scope with a given name. * @param name * @param origin_namespace namespace's name of the variable we are trying to find - * @param extensive_lookup if true, use the additional saved namespaces * @return std::optional std::nullopt if the Declaration isn't in scope */ - [[nodiscard]] std::optional get(const std::string& name, const std::string& origin_namespace, bool extensive_lookup) override; + [[nodiscard]] std::optional get(const std::string& name, const std::string& origin_namespace) override; /** * @brief Given a Declaration name, compute its fully qualified name @@ -129,27 +118,16 @@ namespace Ark::internal */ [[nodiscard]] std::string fullyQualifiedName(const std::string& name) const override; - /** - * @brief Save a namespace scope to help with lookup - * - * @return true if the scope was saved, on NamespaceScope - * @return false on StaticScope - */ - bool saveNamespace(std::unique_ptr&) override; - [[nodiscard]] bool isNamespace() const override; - [[nodiscard]] inline bool isGlob() const override { return m_is_glob; } - [[nodiscard]] inline std::string prefix() const override { return m_namespace; } - [[nodiscard]] inline bool hasSymbol(const std::string& symbol) const override { return std::ranges::find(m_symbols, symbol) != m_symbols.end(); } - [[nodiscard]] bool recursiveHasSymbol(const std::string& symbol) override; + [[nodiscard]] std::string prefix() const override { return m_namespace; } + [[nodiscard]] std::string package() const override { return m_package; } + [[nodiscard]] std::vector imports() const override { return m_imports; } private: - std::string m_namespace; - bool m_with_prefix; - bool m_is_glob; - std::vector m_symbols; + std::string m_namespace; ///< Prefix for the namespace, eg egg + std::string m_package; ///< Complete package name, eg foo.bar.egg + std::vector m_imports; std::unordered_set m_vars {}; - std::vector> m_additional_namespaces; }; } diff --git a/src/arkreactor/Compiler/AST/Parser.cpp b/src/arkreactor/Compiler/AST/Parser.cpp index ee41c614..49b9dfbe 100644 --- a/src/arkreactor/Compiler/AST/Parser.cpp +++ b/src/arkreactor/Compiler/AST/Parser.cpp @@ -328,7 +328,8 @@ namespace Ark::internal backtrack(pos); errorWithNextToken(fmt::format("Import name too long, expected at most 255 characters, got {}", import_data.prefix.size())); } - import_data.package.push_back(lowercasePrefix(import_data.prefix)); + import_data.segments.push_back(import_data.prefix); + import_data.package = lowercasePrefix(import_data.prefix); Node packageNode = positioned(Node(NodeType::List), getCursor()).attachNearestCommentBefore(comment); packageNode.push_back(Node(NodeType::Symbol, import_data.prefix)); @@ -349,9 +350,10 @@ namespace Ark::internal { packageNode.push_back(positioned(Node(NodeType::Symbol, path), package_pos)); + import_data.package += "." + path; + import_data.segments.push_back(path); // in the end we will store the last element of the package, which is what we want import_data.prefix = lowercasePrefix(path); - import_data.package.push_back(import_data.prefix); if (path.size() > 255) { @@ -366,7 +368,7 @@ namespace Ark::internal leaf->push_back(positioned(Node(NodeType::Symbol, "*"), item_pos)); space(); - expectSuffixOrError(')', fmt::format("in import `{}'", import_data.toPackageString()), context); + expectSuffixOrError(')', fmt::format("in import `{}'", import_data.package), context); // save the import data structure to know we encounter an import node, and retrieve its data more easily later on import_data.with_prefix = false; @@ -394,7 +396,7 @@ namespace Ark::internal if (!name(&symbol_name)) errorWithNextToken("Expected a valid symbol to import"); if (symbol_name == "*") - error(fmt::format("Glob patterns can not be separated from the package, use (import {}:*) instead", import_data.toPackageString()), symbol_pos); + error(fmt::format("Glob patterns can not be separated from the package, use (import {}:*) instead", import_data.package), symbol_pos); if (symbol_name.size() >= 2 && symbol_name[symbol_name.size() - 2] == ':' && symbol_name.back() == '*') error("Glob pattern can not follow a symbol to import", FilePosition { .row = symbol_pos.row, .col = symbol_pos.col + symbol_name.size() - 2 }); @@ -425,7 +427,7 @@ namespace Ark::internal if (!comment.empty()) leaf->list().back().attachCommentAfter(comment); - expectSuffixOrError(')', fmt::format("in import `{}'", import_data.toPackageString()), context); + expectSuffixOrError(')', fmt::format("in import `{}'", import_data.package), context); return positioned(leaf, filepos); } diff --git a/src/arkreactor/Compiler/NameResolution/NameResolutionPass.cpp b/src/arkreactor/Compiler/NameResolution/NameResolutionPass.cpp index 76f66f37..ab769044 100644 --- a/src/arkreactor/Compiler/NameResolution/NameResolutionPass.cpp +++ b/src/arkreactor/Compiler/NameResolution/NameResolutionPass.cpp @@ -4,7 +4,9 @@ #include #include -// todo: remove +#include +#include + #include namespace Ark::internal @@ -12,8 +14,8 @@ namespace Ark::internal NameResolutionPass::NameResolutionPass(const unsigned debug, Statistics* stats_collector) : Pass("NameResolution", debug, stats_collector) { - for (const auto& builtin : Builtins::builtins) - m_language_symbols.emplace(builtin.first); + for (const auto& key : Builtins::builtins | std::views::keys) + m_language_symbols.emplace(key); for (auto ope : Language::operators) m_language_symbols.emplace(ope); for (auto inst : Language::listInstructions) @@ -25,31 +27,38 @@ namespace Ark::internal m_language_symbols.emplace(Language::SysProgramName); m_language_symbols.emplace(Language::SysVersion); m_language_symbols.emplace(Language::Apply); + + m_scope_resolver.createNew(); } void NameResolutionPass::setup(const std::vector& root_import_list) { - // todo: configure the m_scope_resolver with the root import list m_logger.info("Configuring NameResolutionPass. Root is importing:"); for (const Import& import : root_import_list) { if (import.is_glob) - m_logger.info(" - {} :*", import.toPackageString()); + m_logger.info(" - {} :*", import.package); else if (import.with_prefix) - m_logger.info(" - {}", import.toPackageString()); + m_logger.info(" - {}", import.package); else - m_logger.info(" - {} :{}", import.toPackageString(), fmt::join(import.symbols, " :")); + m_logger.info(" - {} :{}", import.package, fmt::join(import.symbols, " :")); } + + // the root namespace does NOT have a prefix! + m_scope_resolver.createNewNamespace("", "", root_import_list); } void NameResolutionPass::process(const Node& ast) { + assert(m_scope_resolver.currentScope()->isNamespace() && "The first scope should be a namespace"); + m_logger.traceStart("process"); m_ast = ast; - visit(m_ast, /* register_declarations= */ true); + registerDeclarations(m_ast); + qualifyNames(m_ast); - addStat("NameResolution.visit", m_logger.traceEnd()); + addStat("NameResolution.process", m_logger.traceEnd()); m_logger.debug("AST after name resolution"); if (m_logger.shouldDebug()) @@ -65,228 +74,329 @@ namespace Ark::internal return m_ast; } - std::string NameResolutionPass::addDefinedSymbol(const std::string& sym, const bool is_mutable) + std::string NameResolutionPass::qualifyAndRegisterSymbol(const std::string& sym, const bool is_mutable) { const std::string fully_qualified_name = m_scope_resolver.registerInCurrent(sym, is_mutable); m_defined_symbols.emplace(fully_qualified_name); return fully_qualified_name; } - void NameResolutionPass::visit(Node& node, const bool register_declarations) + void NameResolutionPass::registerDeclarations(Node& node) { - switch (node.nodeType()) + if (node.nodeType() == NodeType::List && !node.constList().empty()) { - case NodeType::Symbol: + if (node.constList()[0].nodeType() == NodeType::Keyword) { - const std::string old_name = node.string(); - updateSymbolWithFullyQualifiedName(node); - addSymbolNode(node, old_name); - break; - } + const Keyword keyword = node.constList()[0].keyword(); - case NodeType::Field: - for (std::size_t i = 0, end = node.list().size(); i < end; ++i) + switch (keyword) { - Node& child = node.list()[i]; - - if (i == 0) - { - const std::string old_name = child.string(); - // in case of field, no need to check if we can fully qualify names - child.setString(m_scope_resolver.getFullyQualifiedNameInNearestScope(old_name)); - addSymbolNode(child, old_name); - statIncrementCount(Stats::FullyQualifiedNames); - } - else - addSymbolNode(child); - } - break; - - case NodeType::List: - if (!node.constList().empty()) - { - if (node.constList()[0].nodeType() == NodeType::Keyword) - visitKeyword(node, node.constList()[0].keyword(), register_declarations); - else - { - // function calls - // the UpdateRef function calls kind get a special treatment, like let/mut/set, - // because we need to check for mutability errors - if (node.constList().size() > 1 && node.constList()[0].nodeType() == NodeType::Symbol && - node.constList()[1].nodeType() == NodeType::Symbol && register_declarations) + case Keyword::Set: + [[fallthrough]]; + case Keyword::Let: + [[fallthrough]]; + case Keyword::Mut: + // first, visit the value, then register the symbol + // this allows us to detect things like (let foo (fun (&foo) ())) + if (node.constList().size() > 2) + registerDeclarations(node.list()[2]); + if (node.constList().size() > 1 && node.constList()[1].nodeType() == NodeType::Symbol) { - const auto funcname = node.constList()[0].string(); - const auto arg = node.constList()[1].string(); + const std::string& name = node.constList()[1].string(); + if (m_language_symbols.contains(name)) + throw CodeError( + fmt::format("Can not use a reserved identifier ('{}') as a {} name.", name, keyword == Keyword::Let ? "constant" : "variable"), + CodeErrorContext(node.filename(), node.constList()[1].position())); + + // todo: maybe we'll have errors here (in the diag tests) because names aren't fully qualified anymore in this first pass - if (std::ranges::find(Language::UpdateRef, funcname) != Language::UpdateRef.end() && m_scope_resolver.isImmutable(arg).value_or(false)) + if (m_scope_resolver.isInScope(name) && keyword == Keyword::Let) throw CodeError( - fmt::format("MutabilityError: Can not modify the constant list `{}' using `{}'", arg, funcname), + fmt::format("MutabilityError: Can not use 'let' to redefine variable `{}'", name), CodeErrorContext(node.filename(), node.constList()[1].position())); + if (keyword == Keyword::Set && m_scope_resolver.isRegistered(name) && m_scope_resolver.isImmutable(name).value_or(false)) + throw CodeError( + fmt::format("MutabilityError: Can not set the constant `{}' to {}", name, node.constList()[2].repr()), + CodeErrorContext(node.filename(), node.constList()[1].position())); + + if (keyword != Keyword::Set) + m_scope_resolver.registerInCurrent(name, keyword == Keyword::Mut); + } + break; + + case Keyword::Import: + if (node.constList().size() >= 2 && !node.constList()[1].constList().empty()) + m_plugin_names.push_back(node.constList()[1].constList().back().string()); + break; - // check that we aren't doing a (append! a a) nor a (concat! a a) - if (funcname == Language::AppendInPlace || funcname == Language::ConcatInPlace) + case Keyword::While: + // create a new scope to track variables + m_scope_resolver.createNew(); + for (auto& child : node.list()) + registerDeclarations(child); + // remove the scope once the loop has been compiled, only we were registering declarations + m_scope_resolver.removeLastScope(); + break; + + case Keyword::Fun: + // create a new scope to track variables + m_scope_resolver.createNew(); + + if (node.constList()[1].nodeType() == NodeType::List) + { + for (auto& child : node.list()[1].list()) { - for (std::size_t i = 2, end = node.constList().size(); i < end; ++i) + if (child.nodeType() == NodeType::Capture) { - if (node.constList()[i].nodeType() == NodeType::Symbol && node.constList()[i].string() == arg) + if (!m_scope_resolver.isRegistered(child.string())) throw CodeError( - fmt::format("MutabilityError: Can not {} the list `{}' to itself", funcname, arg), - CodeErrorContext(node.filename(), node.constList()[1].position())); + fmt::format("Can not capture `{}' because it is referencing a variable defined in an unreachable scope.", child.string()), + CodeErrorContext(child.filename(), child.position())); + + // save the old unqualified name of the capture, so that we can use it in the + // ASTLowerer later one + if (!child.getUnqualifiedName()) + { + child.setUnqualifiedName(child.string()); + m_defined_symbols.emplace(child.string()); + } } + else if (child.nodeType() == NodeType::Symbol || child.nodeType() == NodeType::RefArg) + m_defined_symbols.emplace(m_scope_resolver.registerInCurrent(child.string(), /* is_mutable= */ false)); + else if (child.nodeType() == NodeType::MutArg) + m_defined_symbols.emplace(m_scope_resolver.registerInCurrent(child.string(), /* is_mutable= */ true)); } } - + if (node.constList().size() > 2) + registerDeclarations(node.list()[2]); + + // remove the scope once the function has been compiled, only we were registering declarations + m_scope_resolver.removeLastScope(); + break; + + case Keyword::Begin: + [[fallthrough]]; + case Keyword::Del: + [[fallthrough]]; + case Keyword::If: for (auto& child : node.list()) - visit(child, register_declarations); - } + registerDeclarations(child); + break; } - break; - - case NodeType::Namespace: + } + else { - auto& namespace_ = node.arkNamespace(); - // no need to guard createNewNamespace with an if (register_declarations), we want to keep the namespace node - // (which will get ignored by the compiler, that only uses its AST), so that we can (re)construct the - // scopes correctly - m_scope_resolver.createNewNamespace(namespace_.name, namespace_.with_prefix, namespace_.is_glob, namespace_.symbols); - StaticScope* scope = m_scope_resolver.currentScope(); - - visit(*namespace_.ast, /* register_declarations= */ true); - // dual visit so that we can handle forward references - visit(*namespace_.ast, /* register_declarations= */ false); - - // if we had specific symbols to import, check that those exist - if (!namespace_.symbols.empty()) + // function calls + // the UpdateRef function calls kind get a special treatment, like let/mut/set, + // because we need to check for mutability errors + if (node.constList().size() > 1 && node.constList()[0].nodeType() == NodeType::Symbol && + node.constList()[1].nodeType() == NodeType::Symbol) { - const auto it = std::ranges::find_if( - namespace_.symbols, - [&scope, &namespace_](const std::string& sym) -> bool { - return !scope->get(sym, namespace_.name, true).has_value(); - }); + const auto funcname = node.constList()[0].string(); + const auto arg = node.constList()[1].string(); - if (it != namespace_.symbols.end()) + if (std::ranges::find(Language::UpdateRef, funcname) != Language::UpdateRef.end() && m_scope_resolver.isImmutable(arg).value_or(false)) throw CodeError( - fmt::format("ImportError: Can not import symbol {} from {}, as it isn't in the package", *it, namespace_.name), - CodeErrorContext(namespace_.ast->filename(), namespace_.ast->position())); + fmt::format("MutabilityError: Can not modify the constant list `{}' using `{}'", arg, funcname), + CodeErrorContext(node.filename(), node.constList()[1].position())); + + // check that we aren't doing a (append! a a) nor a (concat! a a) + if (funcname == Language::AppendInPlace || funcname == Language::ConcatInPlace) + { + for (std::size_t i = 2, end = node.constList().size(); i < end; ++i) + { + if (node.constList()[i].nodeType() == NodeType::Symbol && node.constList()[i].string() == arg) + throw CodeError( + fmt::format("MutabilityError: Can not {} the list `{}' to itself", funcname, arg), + CodeErrorContext(node.filename(), node.constList()[1].position())); + } + } } - m_scope_resolver.saveNamespaceAndRemove(); - break; + for (auto& child : node.list()) + registerDeclarations(child); + } + } + else if (node.nodeType() == NodeType::Namespace) + { + auto& namespace_ = node.arkNamespace(); + // we want to keep the namespace node (which will get ignored by the compiler, + // that only uses its AST), so that we can (re)construct the scopes correctly + m_scope_resolver.createNewNamespace(namespace_.name, namespace_.package, namespace_.imports); + StaticScope* scope = m_scope_resolver.currentScope(); + + registerDeclarations(*namespace_.ast); + qualifyNames(*namespace_.ast); + + // if we had specific symbols to import, check that those exist + if (!namespace_.symbols.empty()) + { + const auto it = std::ranges::find_if( + namespace_.symbols, + [&scope, &namespace_](const std::string& sym) -> bool { + return !scope->get(sym, namespace_.name).has_value(); + }); + + if (it != namespace_.symbols.end()) + throw CodeError( + fmt::format("ImportError: Can not import symbol {} from {}, as it isn't in the package", *it, namespace_.name), + CodeErrorContext(namespace_.ast->filename(), namespace_.ast->position())); } - default: - break; + m_scope_resolver.saveNamespaceAndRemove(); } } - void NameResolutionPass::visitKeyword(Node& node, const Keyword keyword, const bool register_declarations) + void NameResolutionPass::qualifyNames(Node& node) { - switch (keyword) + switch (node.nodeType()) { - case Keyword::Set: - [[fallthrough]]; - case Keyword::Let: - [[fallthrough]]; - case Keyword::Mut: - // first, visit the value, then register the symbol - // this allows us to detect things like (let foo (fun (&foo) ())) - if (node.constList().size() > 2) - visit(node.list()[2], register_declarations); - if (node.constList().size() > 1 && node.constList()[1].nodeType() == NodeType::Symbol) - { - const std::string& name = node.constList()[1].string(); - if (m_language_symbols.contains(name) && register_declarations) - throw CodeError( - fmt::format("Can not use a reserved identifier ('{}') as a {} name.", name, keyword == Keyword::Let ? "constant" : "variable"), - CodeErrorContext(node.filename(), node.constList()[1].position())); + case NodeType::Symbol: + { + tryQualifyAndUpdateSymbol(node); + savedAsKnownSymbol(node); + break; + } - if (m_scope_resolver.isInScope(name) && keyword == Keyword::Let && register_declarations) - throw CodeError( - fmt::format("MutabilityError: Can not use 'let' to redefine variable `{}'", name), - CodeErrorContext(node.filename(), node.constList()[1].position())); - if (keyword == Keyword::Set && m_scope_resolver.isRegistered(name)) - { - if (m_scope_resolver.isImmutable(name).value_or(false) && register_declarations) - throw CodeError( - fmt::format("MutabilityError: Can not set the constant `{}' to {}", name, node.constList()[2].repr()), - CodeErrorContext(node.filename(), node.constList()[1].position())); + case NodeType::Field: + for (std::size_t i = 0, end = node.list().size(); i < end; ++i) + { + Node& child = node.list()[i]; - updateSymbolWithFullyQualifiedName(node.list()[1]); - } - else if (keyword != Keyword::Set) + if (i == 0) { - // update the declared variable name to use the fully qualified name - // this will prevent name conflicts, and handle scope resolution - const std::string fully_qualified_name = addDefinedSymbol(name, keyword != Keyword::Let); - if (register_declarations) - node.list()[1].setString(fully_qualified_name); + // in case of field, no need to check if we can fully qualify names + const auto [maybe_error, fqn] = m_scope_resolver.tryFullyQualifyName(child.string()); + child.setString(fqn); + savedAsKnownSymbol(child); + statIncrementCount(Stats::FullyQualifiedNames); } + else + savedAsKnownSymbol(child); } break; - case Keyword::Import: + case NodeType::List: if (!node.constList().empty()) - m_plugin_names.push_back(node.constList()[1].constList().back().string()); - break; - - case Keyword::While: - // create a new scope to track variables - m_scope_resolver.createNew(); - for (auto& child : node.list()) - visit(child, register_declarations); - // remove the scope once the loop has been compiled, only we were registering declarations - m_scope_resolver.removeLastScope(); - break; - - case Keyword::Fun: - // create a new scope to track variables - m_scope_resolver.createNew(); - - if (node.constList()[1].nodeType() == NodeType::List) { - for (auto& child : node.list()[1].list()) + if (node.constList()[0].nodeType() == NodeType::Keyword) { - if (child.nodeType() == NodeType::Capture) + const Keyword keyword = node.constList()[0].keyword(); + + switch (keyword) { - if (!m_scope_resolver.isRegistered(child.string()) && register_declarations) - throw CodeError( - fmt::format("Can not capture `{}' because it is referencing a variable defined in an unreachable scope.", child.string()), - CodeErrorContext(child.filename(), child.position())); + case Keyword::Set: + [[fallthrough]]; + case Keyword::Let: + [[fallthrough]]; + case Keyword::Mut: + if (node.constList().size() > 1 && node.constList()[1].nodeType() == NodeType::Symbol) + { + const std::string& name = node.constList()[1].string(); + + if (keyword == Keyword::Set && m_scope_resolver.isRegistered(name)) + tryQualifyAndUpdateSymbol(node.list()[1]); + else if (keyword != Keyword::Set) + { + // update the declared variable name to use the fully qualified name + // this will prevent name conflicts, and handle scope resolution + // TODO: if it's a function, add its argc when registering it + const std::string fully_qualified_name = qualifyAndRegisterSymbol(name, keyword != Keyword::Let); + node.list()[1].setString(fully_qualified_name); + } + } + if (node.constList().size() > 2) + qualifyNames(node.list()[2]); + break; - // save the old unqualified name of the capture, so that we can use it in the - // ASTLowerer later one - if (!child.getUnqualifiedName()) - { - child.setUnqualifiedName(child.string()); - m_defined_symbols.emplace(child.string()); - } - // update the declared variable name to use the fully qualified name - // this will prevent name conflicts, and handle scope resolution - std::string old_name = child.string(); - updateSymbolWithFullyQualifiedName(child); - addDefinedSymbol(old_name, true); + case Keyword::Import: + break; + + case Keyword::While: + m_scope_resolver.createNew(); + for (auto& child : node.list()) + qualifyNames(child); + m_scope_resolver.removeLastScope(); + break; + + case Keyword::Fun: + m_scope_resolver.createNew(); + + if (node.constList()[1].nodeType() == NodeType::List) + { + for (auto& child : node.list()[1].list()) + { + if (child.nodeType() == NodeType::Capture) + { + if (!m_scope_resolver.isRegistered(child.string())) + throw CodeError( + fmt::format("Can not capture `{}' because it is referencing a variable defined in an unreachable scope.", child.string()), + CodeErrorContext(child.filename(), child.position())); + + // save the old unqualified name of the capture, so that we can use it in the + // ASTLowerer later one + if (!child.getUnqualifiedName()) + { + child.setUnqualifiedName(child.string()); + m_defined_symbols.emplace(child.string()); + } + // update the declared variable name to use the fully qualified name + // this will prevent name conflicts, and handle scope resolution + std::string old_name = child.string(); + tryQualifyAndUpdateSymbol(child); + const std::string fully_qualified_name = m_scope_resolver.registerInCurrent(old_name, /* is_mutable= */ true); + m_defined_symbols.emplace(fully_qualified_name); + } + else if (child.nodeType() == NodeType::Symbol || child.nodeType() == NodeType::RefArg) + qualifyAndRegisterSymbol(child.string(), /* is_mutable= */ false); + else if (child.nodeType() == NodeType::MutArg) + qualifyAndRegisterSymbol(child.string(), /* is_mutable= */ true); + } + } + if (node.constList().size() > 2) + qualifyNames(node.list()[2]); + + m_scope_resolver.removeLastScope(); + break; + + default: + for (auto& child : node.list()) + qualifyNames(child); + break; } - else if (child.nodeType() == NodeType::Symbol || child.nodeType() == NodeType::RefArg) - addDefinedSymbol(child.string(), /* is_mutable= */ false); - else if (child.nodeType() == NodeType::MutArg) - addDefinedSymbol(child.string(), /* is_mutable= */ true); + } + else + { + for (auto& child : node.list()) + qualifyNames(child); } } - if (node.constList().size() > 2) - visit(node.list()[2], register_declarations); - - // remove the scope once the function has been compiled, only we were registering declarations - m_scope_resolver.removeLastScope(); break; - default: - for (auto& child : node.list()) - visit(child, register_declarations); + case NodeType::Namespace: + [[fallthrough]]; + case NodeType::MutArg: + [[fallthrough]]; + case NodeType::RefArg: + [[fallthrough]]; + case NodeType::Capture: + [[fallthrough]]; + case NodeType::Keyword: + [[fallthrough]]; + case NodeType::String: + [[fallthrough]]; + case NodeType::Number: + [[fallthrough]]; + case NodeType::Spread: + [[fallthrough]]; + case NodeType::Macro: + [[fallthrough]]; + case NodeType::Unused: break; } } - void NameResolutionPass::addSymbolNode(const Node& symbol, const std::string& old_name) + void NameResolutionPass::savedAsKnownSymbol(const Node& symbol) { const std::string& name = symbol.string(); @@ -294,42 +404,44 @@ namespace Ark::internal if (m_language_symbols.contains(name)) return; - // remove the old name node, to avoid false positive when looking for unbound symbols - if (!old_name.empty()) - { - auto it = std::ranges::find_if(m_symbol_nodes, [&old_name, &symbol](const Node& sym_node) -> bool { - return sym_node.string() == old_name && - sym_node.position().start == symbol.position().start && - sym_node.filename() == symbol.filename(); + // todo: maybe we could get rid of the check + const auto it = std::ranges::find_if( + m_symbol_nodes, + [&name](const Node& sym_node) -> bool { + return sym_node.string() == name; }); - if (it != m_symbol_nodes.end()) - { - it->setString(name); - return; - } - } - - const auto it = std::ranges::find_if(m_symbol_nodes, [&name](const Node& sym_node) -> bool { - return sym_node.string() == name; - }); if (it == m_symbol_nodes.end()) m_symbol_nodes.push_back(symbol); } bool NameResolutionPass::mayBeFromPlugin(const std::string& name) const noexcept { - std::string splitted = Utils::splitString(name, ':')[0]; - const auto it = std::ranges::find_if( - m_plugin_names, - [&splitted](const std::string& plugin) -> bool { - return plugin == splitted; - }); - return it != m_plugin_names.end(); + if (m_plugin_names.empty()) + return false; + + const std::string prefix = name.substr(0, name.find_first_of(':')); + return prefix.size() < name.size() && std::ranges::find(m_plugin_names, prefix) != m_plugin_names.end(); + } + + std::string messageNeedPrefixing(const std::string& symbol, const std::string& fqn) + { + const std::string prefix = fqn.substr(0, fqn.find_first_of(':')); + const std::string note_about_prefix = fmt::format( + " You either forgot to import it in the symbol list (eg `(import {} :{})') or need to fully qualify it by prefixing it with the namespace.", + prefix, + symbol); + const bool add_note = fqn.ends_with(":" + symbol); + return fmt::format(R"(Unbound variable "{}" (did you mean "{}"?){})", symbol, fqn, add_note ? note_about_prefix : ""); } - std::string NameResolutionPass::updateSymbolWithFullyQualifiedName(Node& symbol) + std::string NameResolutionPass::tryQualifyAndUpdateSymbol(Node& symbol) const { - auto [allowed, fqn] = m_scope_resolver.canFullyQualifyName(symbol.string()); + if (m_language_symbols.contains(symbol.string())) + return symbol.string(); + if (mayBeFromPlugin(symbol.string())) + return symbol.string(); + + auto [maybe_error, fqn] = m_scope_resolver.tryFullyQualifyName(symbol.string()); if (m_language_symbols.contains(fqn) && symbol.string() != fqn) { @@ -339,16 +451,28 @@ namespace Ark::internal symbol.string(), fqn), CodeErrorContext(symbol.filename(), symbol.position())); } - if (!allowed) + + if (maybe_error.has_value()) { std::string message; - if (fqn.ends_with(HiddenSymbolSuffix)) - message = fmt::format( - R"(Unbound variable "{}". However, it exists in a namespace as "{}", did you forget to add it to the symbol list while importing?)", - symbol.string(), - fqn.substr(0, fqn.find_first_of('#'))); - else - message = fmt::format(R"(Unbound variable "{}". However, it exists in a namespace as "{}", did you forget to prefix it with its namespace?)", symbol.string(), fqn); + switch (maybe_error.value()) + { + case QualifyingFailReason::NotInSymbolList: + { + const std::string prefix = fqn.substr(0, fqn.find_first_of(':')); + const std::string suffix = fqn.substr(fqn.find_first_of(':') + 1, fqn.size() - prefix.size() - 1); + message = fmt::format( + R"(Unbound variable "{0}". Did you forget to add '{1}' when importing '{2}', eg `(import {2} :{1})'? (symbol is visible but not available))", + symbol.string(), + suffix, + prefix); + break; + } + + case QualifyingFailReason::NeedPrefixing: + message = messageNeedPrefixing(symbol.string(), fqn); + break; + } if (m_logger.shouldTrace()) m_ast.debugPrint(std::cout) << '\n'; @@ -375,22 +499,8 @@ namespace Ark::internal const std::string suggestion = offerSuggestion(str); if (suggestion.empty()) message = fmt::format(R"(Unbound variable "{}" (variable is used but not defined))", str); - else if (suggestion.ends_with(HiddenSymbolSuffix)) - { - const std::string prefix = suggestion.substr(0, suggestion.find_first_of(':')); - const std::string suffix = suggestion.substr(suggestion.find_first_of(':') + 1, suggestion.size() - prefix.size() - 1 - HiddenSymbolSuffix.size()); - message = fmt::format(R"(Unbound variable "{0}". Did you forget to add '{1}' when importing '{2}', eg `(import {2} :{1})'? (symbol is visible but not available))", str, suffix, prefix); - } else - { - const std::string prefix = suggestion.substr(0, suggestion.find_first_of(':')); - const std::string note_about_prefix = fmt::format( - " You either forgot to import it in the symbol list (eg `(import {} :{})') or need to fully qualify it by adding the namespace", - prefix, - str); - const bool add_note = suggestion.ends_with(":" + str); - message = fmt::format(R"(Unbound variable "{}" (did you mean "{}"?{}))", str, suggestion, add_note ? note_about_prefix : ""); - } + message = messageNeedPrefixing(str, suggestion); throw CodeError(message, CodeErrorContext(sym.filename(), sym.position())); } @@ -405,12 +515,6 @@ namespace Ark::internal std::size_t suggestion_distance = word.size() / 2; for (const std::string& symbol : dict) { - if (symbol.starts_with(word) && symbol.ends_with(HiddenSymbolSuffix)) - { - suggestion = symbol; - break; - } - const std::size_t current_distance = Utils::levenshteinDistance(word, symbol); if (current_distance <= suggestion_distance) { diff --git a/src/arkreactor/Compiler/NameResolution/ScopeResolver.cpp b/src/arkreactor/Compiler/NameResolution/ScopeResolver.cpp index f2adaef4..deb14040 100644 --- a/src/arkreactor/Compiler/NameResolution/ScopeResolver.cpp +++ b/src/arkreactor/Compiler/NameResolution/ScopeResolver.cpp @@ -1,5 +1,6 @@ #include +#include #include #include @@ -7,10 +8,11 @@ namespace Ark::internal { - ScopeResolver::ScopeResolver() + struct ScopeAndOrigin { - createNewNamespace("", /* with_prefix= */ false, /* is_glob= */ true, /* symbols= */ {}); - } + Import imported_as; + StaticScope* scope; + }; void ScopeResolver::createNew() { @@ -22,9 +24,9 @@ namespace Ark::internal m_scopes.pop_back(); } - void ScopeResolver::createNewNamespace(const std::string& name, bool with_prefix, bool is_glob, const std::vector& symbols) + void ScopeResolver::createNewNamespace(const std::string& prefix, const std::string& package, const std::vector& imports) { - m_scopes.emplace_back(std::make_unique(name, with_prefix, is_glob, symbols)); + m_scopes.emplace_back(std::make_unique(prefix, package, imports)); } std::string ScopeResolver::registerInCurrent(const std::string& name, const bool is_mutable) @@ -34,12 +36,7 @@ namespace Ark::internal void ScopeResolver::saveNamespaceAndRemove() { - for (auto& m_scope : std::ranges::reverse_view(m_scopes) | std::ranges::views::drop(1)) - { - if (m_scope->saveNamespace(m_scopes.back())) - break; - } - + m_saved_scopes.insert_or_assign(m_scopes.back()->package(), std::move(m_scopes.back())); m_scopes.pop_back(); } @@ -47,7 +44,8 @@ namespace Ark::internal { for (const auto& m_scope : std::ranges::reverse_view(m_scopes)) { - if (auto maybe = m_scope->get(name, currentNamespace(), true); maybe.has_value()) + // todo: bfs lookup? + if (auto maybe = m_scope->get(name, currentNamespace()->prefix()); maybe.has_value()) return !maybe.value().is_mutable; } return std::nullopt; @@ -55,71 +53,36 @@ namespace Ark::internal bool ScopeResolver::isRegistered(const std::string& name) const { - const std::string origin_namespace = currentNamespace(); + const std::string origin_namespace = currentNamespace()->prefix(); return std::ranges::any_of(std::ranges::reverse_view(m_scopes), [&name, &origin_namespace](const auto& scope) { - return scope->get(name, origin_namespace, true).has_value(); + // todo: bfs lookup? + return scope->get(name, origin_namespace).has_value(); }); } bool ScopeResolver::isInScope(const std::string& name) const { - return m_scopes.back()->get(name, currentNamespace(), false).has_value(); - } - - std::string ScopeResolver::getFullyQualifiedNameInNearestScope(const std::string& name) const - { - const std::string prefix = currentNamespace(); - std::optional maybe_name; - for (const auto& scope : std::ranges::reverse_view(m_scopes)) - { - if (auto maybe_fqn = scope->get(name, prefix, true); maybe_fqn.has_value()) - { - // prioritize non-hidden symbols - if ((maybe_name.has_value() && - maybe_name.value().ends_with(HiddenSymbolSuffix) && - !maybe_fqn.value().name.ends_with(HiddenSymbolSuffix)) || - !maybe_name.has_value()) - maybe_name = maybe_fqn.value().name; - } - } - return maybe_name.value_or(name); + return m_scopes.back()->get(name, currentNamespace()->prefix()).has_value(); } - std::pair ScopeResolver::canFullyQualifyName(const std::string& name) + std::pair, std::string> ScopeResolver::tryFullyQualifyName(const std::string& name) const { - // a given name can be fully qualified if - // old == new - // old != new and new has prefix - // if the prefix namespace is glob - // if the prefix namespace has name in its symbols - // if the prefix namespace is with_prefix && it is the top most scope - const std::string maybe_fqn = getFullyQualifiedNameInNearestScope(name); - - if (maybe_fqn == name) - return std::make_pair(true, maybe_fqn); - - const std::string prefix = maybe_fqn.substr(0, maybe_fqn.find_first_of(':')); - const std::string unprefixed_name = name.substr(name.find_first_of(':') + 1); - auto namespaces = - std::ranges::reverse_view(m_scopes) | std::ranges::views::filter([](const auto& e) { - return e->isNamespace(); - }); - bool top = true; - for (auto& scope : namespaces) - { - if (top && prefix == scope->prefix()) - return std::make_pair(true, maybe_fqn); - if (!top && prefix == scope->prefix() && (scope->isGlob() || scope->hasSymbol(name))) - return std::make_pair(true, maybe_fqn); - - // check for the presence of the symbol in symbol imports and glob imports - if (scope->recursiveHasSymbol(unprefixed_name)) - return std::make_pair(true, maybe_fqn); - - top = false; - } - - return std::make_pair(false, maybe_fqn); + // todo: move the error handling of the NameResolutionPass here? -> complicated, probably not worth it + + // search in current scope and parent static scopes + // if nothing, look in other scopes that are in the namespace imports (direct + indirect) + // filter using the import list (glob, symbols, or prefix) + const auto [qualified_name, alternatives] = getFullyQualifiedNameInNearestScope(name); + + // in the original algorithm, if we couldn't qualify, we returned the original name as "qualified" + if (!qualified_name.has_value() && alternatives.empty()) + return std::make_pair(std::nullopt, name); + if (qualified_name.has_value()) + return std::make_pair(std::nullopt, qualified_name.value()); + + // qualified_name does not have a value here, but alternatives has to have at least one element + // since the empty case is checked a few lines above + return std::make_pair(alternatives.front().reason, alternatives.front().name); } StaticScope* ScopeResolver::currentScope() const @@ -129,15 +92,82 @@ namespace Ark::internal return nullptr; } - std::string ScopeResolver::currentNamespace() const + StaticScope* ScopeResolver::currentNamespace() const { for (const auto& scope : std::ranges::reverse_view(m_scopes)) { if (scope->isNamespace()) - return scope->prefix(); + return scope.get(); + } + + // this shouldn't reach, since we MUST have a namespace scope as the first created scope + // but just in case, let's have a default value + return m_scopes.front().get(); + } + + QualifiedName ScopeResolver::getFullyQualifiedNameInNearestScope(const std::string& name) const + { + const StaticScope* ns = currentNamespace(); + const std::string prefix = ns->prefix(); + const std::string name_prefix = name.substr(0, name.find_first_of(':')); + const std::string name_suffix = name.substr(name.find_first_of(':') + 1); + + QualifiedName res; + + for (const auto& scope : std::ranges::reverse_view(m_scopes)) + { + if (auto maybe_fqn = scope->get(name, prefix); maybe_fqn.has_value()) + { + if (!res.qualified_name.has_value()) + res.qualified_name = maybe_fqn->name; + } + } + + // if we didn't find a FQN for 'name' in the pile of active scopes, try via the import list + // todo: put this in a separate method + if (!res.qualified_name) + { + // todo: precompute the queue, given the import list + std::queue queue; + for (const auto& candidate : ns->imports()) + { + if (const auto it = m_saved_scopes.find(candidate.package); it != m_saved_scopes.end()) + queue.push(ScopeAndOrigin { candidate, it->second.get() }); + } + + while (!queue.empty()) + { + const auto& [imported_as, scope] = queue.front(); + + if (auto maybe_fqn = scope->get(name, prefix); maybe_fqn.has_value()) + { + if ((imported_as.with_prefix && imported_as.prefix == name_prefix) || + imported_as.is_glob || + std::ranges::find(imported_as.symbols, name) != imported_as.symbols.end() || + (imported_as.prefix == name_prefix && std::ranges::find(imported_as.symbols, name_suffix) != imported_as.symbols.end())) + { + res.qualified_name = maybe_fqn->name; + break; + } + + if (!imported_as.symbols.empty()) + res.alternatives.emplace_back(QualifiedName::Match { .reason = QualifyingFailReason::NotInSymbolList, .name = maybe_fqn->name }); + else if (imported_as.with_prefix && imported_as.prefix != name_prefix) + res.alternatives.emplace_back(QualifiedName::Match { .reason = QualifyingFailReason::NeedPrefixing, .name = maybe_fqn->name }); + } + else + { + for (const auto& candidate : scope->imports()) + { + if (const auto it = m_saved_scopes.find(candidate.package); it != m_saved_scopes.end()) + queue.push(ScopeAndOrigin { candidate, it->second.get() }); + } + } + + queue.pop(); + } } - // no namespace name, thus no prefix ; "" is either the default namespace, a function scope or a while loop - return ""; + return res; } } diff --git a/src/arkreactor/Compiler/NameResolution/StaticScope.cpp b/src/arkreactor/Compiler/NameResolution/StaticScope.cpp index 1dd845f6..e74c5df3 100644 --- a/src/arkreactor/Compiler/NameResolution/StaticScope.cpp +++ b/src/arkreactor/Compiler/NameResolution/StaticScope.cpp @@ -1,5 +1,6 @@ #include +#include #include #include #include @@ -14,7 +15,7 @@ namespace Ark::internal return name; } - std::optional StaticScope::get(const std::string& name, [[maybe_unused]] const std::string& origin_namespace, [[maybe_unused]] const bool extensive_lookup) + std::optional StaticScope::get(const std::string& name, [[maybe_unused]] const std::string& origin_namespace) { if (const auto it = std::ranges::find(m_vars, name, &Declaration::name); it != m_vars.end()) return *it; @@ -26,63 +27,36 @@ namespace Ark::internal return name; } - bool StaticScope::saveNamespace([[maybe_unused]] std::unique_ptr&) - { - // the scope can not be saved on a static scope - return false; - } - bool StaticScope::isNamespace() const { return false; } - NamespaceScope::NamespaceScope(std::string name, const bool with_prefix, const bool is_glob, const std::vector& symbols) : + NamespaceScope::NamespaceScope(std::string prefix, const std::string& package, const std::vector& imports) : StaticScope(), - m_namespace(std::move(name)), - m_with_prefix(with_prefix), - m_is_glob(is_glob), - m_symbols(symbols) + m_namespace(std::move(prefix)), + m_package(package), + m_imports(imports) {} std::string NamespaceScope::add(const std::string& name, bool is_mutable) { - // Since we do multiple passes on namespaces, we need to check if the given name is already hidden, - // so that we can save the name as it was on the first pass - if (name.ends_with(HiddenSymbolSuffix)) - { - std::string std_name = name.substr(0, name.find_first_of('#')); - return m_vars.emplace(name, std_name, is_mutable).first->name; - } - - // Otherwise, we also have to check for the presence of a namespace prefix, - // and remove it when checking against the symbols list, to determine if we - // need to hide the name or not - const bool starts_with_prefix = !m_namespace.empty() && name.starts_with(m_namespace + ":"); const std::string fqn = fullyQualifiedName(name); - const std::string unprefixed_name = starts_with_prefix ? name.substr(name.find_first_of(':') + 1) : name; - - if (!m_symbols.empty() && !hasSymbol(unprefixed_name) && !m_with_prefix && !m_is_glob) - return m_vars.emplace(fqn + std::string(HiddenSymbolSuffix), fqn, is_mutable).first->name; - return m_vars.emplace(fqn, fqn, is_mutable).first->name; + return m_vars.emplace(fqn, name, is_mutable).first->name; } - std::optional NamespaceScope::get(const std::string& name, const std::string& origin_namespace, const bool extensive_lookup) + std::optional NamespaceScope::get(const std::string& name, const std::string& origin_namespace) { - const bool starts_with_prefix = !m_namespace.empty() && name.starts_with(m_namespace + ":"); - // If the name starts with the namespace, and we imported the namespace with prefix - // search for name in the namespace - if (starts_with_prefix && m_with_prefix) + if (!m_namespace.empty() && name.starts_with(m_namespace + ":")) { if (const auto it = std::ranges::find(m_vars, name, &Declaration::name); it != m_vars.end()) return *it; } - // If the name does not start with the prefix, and we import through either glob or symbol list - // search for the name in the namespace - // If the name does not start with the prefix, in a namespace with a symbol list but can be resolved, - // modify it to hide it to the end user - // If the name wasn't qualified, in the current prefixed namespace, look up for it but by qualifying the name - else if (!starts_with_prefix) + // If the name does not start with the prefix, and we import through either glob or symbol list, + // Or if the name does not start with the prefix, in a namespace with a symbol list but can be resolved, + // Or if the name wasn't qualified, in the current prefixed namespace, + // search for the qualified name in the namespace + else { const auto fqn = fullyQualifiedName(name); @@ -92,67 +66,31 @@ namespace Ark::internal { if (j->name == fqn) it = j; - if (j->original_name == fqn) + if (j->original_name == name) it_original = j; if (it != end && it_original != end) break; } - if ((m_is_glob || hasSymbol(name) || (m_with_prefix && origin_namespace == m_namespace)) && it != m_vars.end()) + if (origin_namespace == m_namespace && it != m_vars.end()) return *it; - if (!m_symbols.empty() && it_original != m_vars.end()) + if (it_original != m_vars.end()) return *it_original; } - // lookup in the additional saved namespaces - if (extensive_lookup) - { - std::optional decl; - for (const auto& scope : m_additional_namespaces) - { - if (auto maybe_decl = scope->get(name, origin_namespace, extensive_lookup); maybe_decl.has_value()) - { - // prioritize non-hidden declarations - if ((decl.has_value() && decl->name.ends_with(HiddenSymbolSuffix)) || !decl.has_value()) - decl = maybe_decl; - } - } - return decl; - } // otherwise we didn't find the name in the namespace return std::nullopt; } std::string NamespaceScope::fullyQualifiedName(const std::string& name) const { - const bool starts_with_prefix = !m_namespace.empty() && name.starts_with(m_namespace + ":"); - if (!m_namespace.empty() && !starts_with_prefix) - return fmt::format("{}:{}", m_namespace, name); - return name; - } - - bool NamespaceScope::saveNamespace(std::unique_ptr& scope) - { - m_additional_namespaces.push_back(std::move(scope)); - return true; + if (m_namespace.empty() || name.starts_with(m_namespace + ":")) + return name; + return fmt::format("{}:{}", m_namespace, name); } bool NamespaceScope::isNamespace() const { return true; } - - bool NamespaceScope::recursiveHasSymbol(const std::string& symbol) - { - if (hasSymbol(symbol)) - return true; - if (isGlob() && std::ranges::find(m_vars, fullyQualifiedName(symbol), &Declaration::name) != m_vars.end()) - return true; - - return std::ranges::any_of( - m_additional_namespaces, - [&symbol](const auto& saved_scope) { - return saved_scope->recursiveHasSymbol(symbol); - }); - } } diff --git a/src/arkreactor/Compiler/Package/ImportSolver.cpp b/src/arkreactor/Compiler/Package/ImportSolver.cpp index 0ab6856e..b3b04028 100644 --- a/src/arkreactor/Compiler/Package/ImportSolver.cpp +++ b/src/arkreactor/Compiler/Package/ImportSolver.cpp @@ -34,13 +34,13 @@ namespace Ark::internal while (!m_imports.empty()) { const ImportWithSource source = m_imports.top(); - m_logger.debug("Importing {} from '{}' (in package '{}')", source.import.toPackageString(), source.file.string(), source.package); + m_logger.debug("Importing {} from '{}' (in package '{}')", source.import.package, source.file.string(), source.package); // Remove the top element to process the other imports // It needs to be removed first because we might be adding // other imports later and don't want to pop THEM m_imports.pop(); - const auto package = source.import.toPackageString(); + const auto package = source.import.package; // register that the current file is importing another one, with its attributes (glob, prefix, symbols...) m_package_to_imports[source.package].push_back(source.import); @@ -79,11 +79,11 @@ namespace Ark::internal for (std::size_t i = 0; i < import_list.size(); ++i) { // if we try to add ourselves to the current import list, we'll end up in an infinite loop - if (import_list[i].toPackageString() == package) + if (import_list[i].package == package) continue; // todo: this might fail on unknown imports? - std::vector indirect_imports = m_package_to_imports[import_list[i].toPackageString()]; + std::vector indirect_imports = m_package_to_imports[import_list[i].package]; std::erase_if(indirect_imports, [&import_list](const Import& import) -> bool { return std::ranges::find(import_list, import) != import_list.end(); }); @@ -130,8 +130,7 @@ namespace Ark::internal x = Node(Namespace { .name = import.prefix, - .is_glob = import.is_glob, - .with_prefix = import.with_prefix, + .package = package, .symbols = import.symbols, .imports = m_package_to_imports[package], .ast = std::make_shared(findAndReplaceImports(x).first) }); @@ -185,7 +184,7 @@ namespace Ark::internal auto package_node = Node(NodeType::List); std::ranges::transform( - source.import.package, + source.import.segments, std::back_inserter(package_node.list()), [](const std::string& stem) { return Node(NodeType::String, stem); }); @@ -193,7 +192,7 @@ namespace Ark::internal // empty symbols list module_node.push_back(Node(NodeType::List)); - m_packages[source.import.toPackageString()] = Package { + m_packages[source.import.package] = Package { module_node, source.import, true @@ -207,19 +206,19 @@ namespace Ark::internal parser.process(path.string(), code); const std::vector& imports = parser.imports(); - m_packages[source.import.toPackageString()] = Package { + m_packages[source.import.package] = Package { parser.ast(), source.import, false }; - addStat(fmt::format("ImportSolver.parseImport({})", source.import.toPackageString()), m_logger.traceEnd()); + addStat(fmt::format("ImportSolver.parseImport({})", source.import.package), m_logger.traceEnd()); std::vector output; std::ranges::transform( imports, std::back_inserter(output), [&path, &source](const Import& i) { - return ImportWithSource { path, source.import.toPackageString(), i }; + return ImportWithSource { path, source.import.package, i }; }); return output; } @@ -253,7 +252,7 @@ namespace Ark::internal // fallback, we couldn't find the file throw CodeError( fmt::format("While processing file {}, couldn't import {}: file not found", - is_source_file ? file.filename().string() : ARK_NO_NAME_FILE, import_.toPackageString()), + is_source_file ? file.filename().string() : ARK_NO_NAME_FILE, import_.package), CodeErrorContext( is_source_file ? file.generic_string() : ARK_NO_NAME_FILE, FileSpan { .start = FilePos { .line = import_.line, .column = import_.col }, .end = std::nullopt })); diff --git a/src/arkreactor/Compiler/Welder.cpp b/src/arkreactor/Compiler/Welder.cpp index 63092da1..b1e77086 100644 --- a/src/arkreactor/Compiler/Welder.cpp +++ b/src/arkreactor/Compiler/Welder.cpp @@ -34,7 +34,7 @@ namespace Ark void Welder::registerSymbol(const std::string& name) { - m_name_resolver.addDefinedSymbol(name, /* is_mutable= */ false); + m_name_resolver.qualifyAndRegisterSymbol(name, /* is_mutable= */ false); } bool Welder::computeASTFromFile(const std::string& filename) @@ -56,7 +56,7 @@ namespace Ark m_root_file = std::nullopt; for (const std::string& sym : symbols) - m_name_resolver.addDefinedSymbol(sym, /* is_mutable= */ true); + m_name_resolver.qualifyAndRegisterSymbol(sym, /* is_mutable= */ true); return computeAST(ARK_NO_NAME_FILE, code); } diff --git a/tests/unittests/resources/CompilerSuite/ir/closures.ark b/tests/unittests/resources/CompilerSuite/ir/closures.ark index a0161e12..de6a7d2b 100644 --- a/tests/unittests/resources/CompilerSuite/ir/closures.ark +++ b/tests/unittests/resources/CompilerSuite/ir/closures.ark @@ -34,7 +34,7 @@ # this function will return a closure capturing the number given # and modifying its value each time we'll call the closure, returning # the new number -(let countdown-from (fun (number) +(let countdown-from (fun ((mut number)) (fun (&number) { (set number (- number 1)) number }))) diff --git a/tests/unittests/resources/CompilerSuite/ir/closures.expected b/tests/unittests/resources/CompilerSuite/ir/closures.expected index a4875fd5..3a1f10a4 100644 --- a/tests/unittests/resources/CompilerSuite/ir/closures.expected +++ b/tests/unittests/resources/CompilerSuite/ir/closures.expected @@ -108,7 +108,7 @@ page_3 (#anonymous (0 arguments) simple closure, 3 instructions) RET 0 HALT 0 -page_4 (countdown-from (1 argument) function, 5 instructions) +page_4 (countdown-from (1 argument) mutating function, 5 instructions) STORE 9 CAPTURE 9 MAKE_CLOSURE 15 diff --git a/tests/unittests/resources/CompilerSuite/optimised_ir/closures.ark b/tests/unittests/resources/CompilerSuite/optimised_ir/closures.ark index b320e0b0..32cd8a5e 100644 --- a/tests/unittests/resources/CompilerSuite/optimised_ir/closures.ark +++ b/tests/unittests/resources/CompilerSuite/optimised_ir/closures.ark @@ -34,7 +34,7 @@ # this function will return a closure capturing the number given # and modifying its value each time we'll call the closure, returning # the new number -(let countdown-from (fun (number) +(let countdown-from (fun ((mut number)) (fun (&number) { (set number (- number 1)) number }))) diff --git a/tests/unittests/resources/CompilerSuite/optimised_ir/closures.expected b/tests/unittests/resources/CompilerSuite/optimised_ir/closures.expected index 2bba449a..66520bb7 100644 --- a/tests/unittests/resources/CompilerSuite/optimised_ir/closures.expected +++ b/tests/unittests/resources/CompilerSuite/optimised_ir/closures.expected @@ -75,7 +75,7 @@ page_3 (#anonymous (0 arguments) simple closure, 3 instructions) RET 0 HALT 0 -page_4 (countdown-from (1 argument) function, 5 instructions) +page_4 (countdown-from (1 argument) mutating function, 5 instructions) STORE 9 CAPTURE 9 MAKE_CLOSURE 15 diff --git a/tests/unittests/resources/DiagnosticsSuite/compileTime/unbound_but_namespace.expected b/tests/unittests/resources/DiagnosticsSuite/compileTime/unbound_but_namespace.expected index 28aee6da..188d78de 100644 --- a/tests/unittests/resources/DiagnosticsSuite/compileTime/unbound_but_namespace.expected +++ b/tests/unittests/resources/DiagnosticsSuite/compileTime/unbound_but_namespace.expected @@ -4,4 +4,4 @@ In file tests/unittests/resources/DiagnosticsSuite/compileTime/unbound_but_names 3 | (print bar) | ^~~ 4 | - Unbound variable "bar" (did you mean "b:bar"? You either forgot to import it in the symbol list (eg `(import b :bar)') or need to fully qualify it by adding the namespace) + Unbound variable "bar" (did you mean "b:bar"?) You either forgot to import it in the symbol list (eg `(import b :bar)') or need to fully qualify it by prefixing it with the namespace. diff --git a/tests/unittests/resources/DiagnosticsSuite/compileTime/use_not_in_import_list.expected b/tests/unittests/resources/DiagnosticsSuite/compileTime/use_not_in_import_list.expected index 52e3b16b..f544de71 100644 --- a/tests/unittests/resources/DiagnosticsSuite/compileTime/use_not_in_import_list.expected +++ b/tests/unittests/resources/DiagnosticsSuite/compileTime/use_not_in_import_list.expected @@ -4,4 +4,4 @@ In file tests/unittests/resources/DiagnosticsSuite/compileTime/use_not_in_import 3 | (print (abs 2)) | ^~~ 4 | - Unbound variable "abs". However, it exists in a namespace as "c:abs", did you forget to add it to the symbol list while importing? + Unbound variable "abs". Did you forget to add 'abs' when importing 'c', eg `(import c :abs)'? (symbol is visible but not available) From dbc0dc5091a41aaf5bfdc33193caebca0cc46c10 Mon Sep 17 00:00:00 2001 From: Lexy Plateau Date: Tue, 1 Dec 2026 13:34:15 +0100 Subject: [PATCH 6/8] tests(name resolution): verify that imported names are correctly resolved in different configurations that can produce shadowing --- .../unittests/Suites/NameResolutionSuite.cpp | 36 +++++++++++++++++++ .../shadowing_import_sym_and_glob/a.ark | 6 ++++ .../shadowing_import_sym_and_glob/b.ark | 3 ++ .../shadowing_import_sym_and_glob/c.ark | 6 ++++ .../a.ark | 6 ++++ .../b.ark | 3 ++ .../c.ark | 6 ++++ 7 files changed, 66 insertions(+) create mode 100644 tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob/a.ark create mode 100644 tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob/b.ark create mode 100644 tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob/c.ark create mode 100644 tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob_swapped/a.ark create mode 100644 tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob_swapped/b.ark create mode 100644 tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob_swapped/c.ark diff --git a/tests/unittests/Suites/NameResolutionSuite.cpp b/tests/unittests/Suites/NameResolutionSuite.cpp index 192b5a0e..120972a9 100644 --- a/tests/unittests/Suites/NameResolutionSuite.cpp +++ b/tests/unittests/Suites/NameResolutionSuite.cpp @@ -217,4 +217,40 @@ ut::suite<"NameResolution"> name_resolution_suite = [] { expect(a_ok.valueType() == Ark::ValueType::True) << "(and (= forEach \"b\") (= c:forEach \"c\") (= b:forEach \"b\"))\n"; }; }; + + "[importing a name as glob that could match a further prefixed namespace]"_test = [] { + Ark::State state({ lib_path }); + + should("compile the resource without any error") = [&] { + expect(mut(state).doFile(getResourcePath("NameResolutionSuite/shadowing_import_sym_and_glob/a.ark"))); + }; + + Ark::VM vm(state); + should("return exit code 0") = [&] { + expect(mut(vm).run() == 0_i); + }; + + should("resolve symbols from all namespaces without generating bad fully qualified names") = [&] { + const auto a_ok = mut(vm).operator[]("ok"); + expect(a_ok.valueType() == Ark::ValueType::True) << "(and (= max c:max) (= max \"c:max\"))\n"; + }; + }; + + "[importing a name as glob that could match a previous prefixed namespace]"_test = [] { + Ark::State state({ lib_path }); + + should("compile the resource without any error") = [&] { + expect(mut(state).doFile(getResourcePath("NameResolutionSuite/shadowing_import_sym_and_glob_swapped/a.ark"))); + }; + + Ark::VM vm(state); + should("return exit code 0") = [&] { + expect(mut(vm).run() == 0_i); + }; + + should("resolve symbols from all namespaces without generating bad fully qualified names") = [&] { + const auto a_ok = mut(vm).operator[]("ok"); + expect(a_ok.valueType() == Ark::ValueType::True) << "(and (= max c:max) (= max \"c:max\"))\n"; + }; + }; }; diff --git a/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob/a.ark b/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob/a.ark new file mode 100644 index 00000000..59d98e8b --- /dev/null +++ b/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob/a.ark @@ -0,0 +1,6 @@ +(import b :round) +(import c:*) + +# max -> expects c:max +# c:max -> expects c:max +(let ok (and (= max c:max) (= max "c:max"))) diff --git a/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob/b.ark b/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob/b.ark new file mode 100644 index 00000000..d71f8378 --- /dev/null +++ b/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob/b.ark @@ -0,0 +1,3 @@ +(let min "b:min") +(let max "b:max") +(let round "b:round") diff --git a/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob/c.ark b/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob/c.ark new file mode 100644 index 00000000..cf8949d2 --- /dev/null +++ b/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob/c.ark @@ -0,0 +1,6 @@ +(import b) + +(let min "c:min") +(let max "c:max") +(let transpose (fun () + (format "min called from c:transpose: {}" min))) diff --git a/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob_swapped/a.ark b/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob_swapped/a.ark new file mode 100644 index 00000000..6b66b06c --- /dev/null +++ b/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob_swapped/a.ark @@ -0,0 +1,6 @@ +(import c:*) +(import b :round) + +# max -> expects c:max +# c:max -> expects c:max +(let ok (and (= max c:max) (= max "c:max"))) diff --git a/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob_swapped/b.ark b/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob_swapped/b.ark new file mode 100644 index 00000000..d71f8378 --- /dev/null +++ b/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob_swapped/b.ark @@ -0,0 +1,3 @@ +(let min "b:min") +(let max "b:max") +(let round "b:round") diff --git a/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob_swapped/c.ark b/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob_swapped/c.ark new file mode 100644 index 00000000..cf8949d2 --- /dev/null +++ b/tests/unittests/resources/NameResolutionSuite/shadowing_import_sym_and_glob_swapped/c.ark @@ -0,0 +1,6 @@ +(import b) + +(let min "c:min") +(let max "c:max") +(let transpose (fun () + (format "min called from c:transpose: {}" min))) From 14cf2129120f6c785a32ba8fd9efbaacf4f38346 Mon Sep 17 00:00:00 2001 From: Lexy Plateau Date: Tue, 1 Dec 2026 12:50:53 +0100 Subject: [PATCH 7/8] chore: removing dead todos --- .clang-format | 2 +- .github/workflows/ci.yml | 2 +- .github/workflows/static_analysis.yml | 2 +- .../NameResolution/NameResolutionPass.hpp | 2 +- .../Ark/Compiler/NameResolution/StaticScope.hpp | 2 +- .../NameResolution/NameResolutionPass.cpp | 15 ++++++--------- .../Compiler/NameResolution/ScopeResolver.cpp | 5 ----- src/arkreactor/Compiler/Package/ImportSolver.cpp | 14 ++++++++------ src/arkreactor/State.cpp | 5 +++-- 9 files changed, 22 insertions(+), 27 deletions(-) diff --git a/.clang-format b/.clang-format index 5eedaafe..0b1af6f2 100644 --- a/.clang-format +++ b/.clang-format @@ -40,7 +40,7 @@ NamespaceIndentation: All SortIncludes: Never -SpaceInEmptyBlock: false +SpaceInEmptyBraces: Never SpacesBeforeTrailingComments: 2 UseTab: Never diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index edea2f36..d1f1f505 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,7 +52,7 @@ jobs: - name: Run clang-format style check for C/C++/Protobuf programs. uses: jidicula/clang-format-action@6cd220de46c89139a0365edae93eee8eb30ca8fe # v4.16.0 with: - clang-format-version: '19' + clang-format-version: '23' check-path: ${{ matrix.path }} fallback-style: 'Mozilla' # optional diff --git a/.github/workflows/static_analysis.yml b/.github/workflows/static_analysis.yml index 1c28710c..ab6036cb 100644 --- a/.github/workflows/static_analysis.yml +++ b/.github/workflows/static_analysis.yml @@ -20,7 +20,7 @@ jobs: - uses: actions/setup-python@v6 with: - python-version: '3.9' + python-version: '3.12' - run: | sudo apt install -yq cppcheck diff --git a/include/Ark/Compiler/NameResolution/NameResolutionPass.hpp b/include/Ark/Compiler/NameResolution/NameResolutionPass.hpp index d3d674cc..61f55b92 100644 --- a/include/Ark/Compiler/NameResolution/NameResolutionPass.hpp +++ b/include/Ark/Compiler/NameResolution/NameResolutionPass.hpp @@ -100,7 +100,7 @@ namespace Ark::internal */ [[nodiscard]] bool mayBeFromPlugin(const std::string& name) const noexcept; - std::string tryQualifyAndUpdateSymbol(Node& symbol) const; + void tryQualifyAndUpdateSymbol(Node& symbol); /** * @brief Checks for undefined symbols, not present in the defined symbols table diff --git a/include/Ark/Compiler/NameResolution/StaticScope.hpp b/include/Ark/Compiler/NameResolution/StaticScope.hpp index bcefd831..aa14cd9b 100644 --- a/include/Ark/Compiler/NameResolution/StaticScope.hpp +++ b/include/Ark/Compiler/NameResolution/StaticScope.hpp @@ -125,7 +125,7 @@ namespace Ark::internal private: std::string m_namespace; ///< Prefix for the namespace, eg egg - std::string m_package; ///< Complete package name, eg foo.bar.egg + std::string m_package; ///< Complete package name, eg foo.bar.egg std::vector m_imports; std::unordered_set m_vars {}; }; diff --git a/src/arkreactor/Compiler/NameResolution/NameResolutionPass.cpp b/src/arkreactor/Compiler/NameResolution/NameResolutionPass.cpp index ab769044..dccd121b 100644 --- a/src/arkreactor/Compiler/NameResolution/NameResolutionPass.cpp +++ b/src/arkreactor/Compiler/NameResolution/NameResolutionPass.cpp @@ -108,8 +108,6 @@ namespace Ark::internal fmt::format("Can not use a reserved identifier ('{}') as a {} name.", name, keyword == Keyword::Let ? "constant" : "variable"), CodeErrorContext(node.filename(), node.constList()[1].position())); - // todo: maybe we'll have errors here (in the diag tests) because names aren't fully qualified anymore in this first pass - if (m_scope_resolver.isInScope(name) && keyword == Keyword::Let) throw CodeError( fmt::format("MutabilityError: Can not use 'let' to redefine variable `{}'", name), @@ -404,7 +402,6 @@ namespace Ark::internal if (m_language_symbols.contains(name)) return; - // todo: maybe we could get rid of the check const auto it = std::ranges::find_if( m_symbol_nodes, [&name](const Node& sym_node) -> bool { @@ -434,12 +431,10 @@ namespace Ark::internal return fmt::format(R"(Unbound variable "{}" (did you mean "{}"?){})", symbol, fqn, add_note ? note_about_prefix : ""); } - std::string NameResolutionPass::tryQualifyAndUpdateSymbol(Node& symbol) const + void NameResolutionPass::tryQualifyAndUpdateSymbol(Node& symbol) { - if (m_language_symbols.contains(symbol.string())) - return symbol.string(); - if (mayBeFromPlugin(symbol.string())) - return symbol.string(); + if (m_language_symbols.contains(symbol.string()) || mayBeFromPlugin(symbol.string())) + return; auto [maybe_error, fqn] = m_scope_resolver.tryFullyQualifyName(symbol.string()); @@ -475,14 +470,16 @@ namespace Ark::internal } if (m_logger.shouldTrace()) + { + m_logger.debug("AST before error in tryQualifyAndUpdateSymbol"); m_ast.debugPrint(std::cout) << '\n'; + } throw CodeError(message, CodeErrorContext(symbol.filename(), symbol.position())); } symbol.setString(fqn); statIncrementCount(Stats::FullyQualifiedNames); - return fqn; } void NameResolutionPass::checkForUndefinedSymbol() const diff --git a/src/arkreactor/Compiler/NameResolution/ScopeResolver.cpp b/src/arkreactor/Compiler/NameResolution/ScopeResolver.cpp index deb14040..481d45fc 100644 --- a/src/arkreactor/Compiler/NameResolution/ScopeResolver.cpp +++ b/src/arkreactor/Compiler/NameResolution/ScopeResolver.cpp @@ -44,7 +44,6 @@ namespace Ark::internal { for (const auto& m_scope : std::ranges::reverse_view(m_scopes)) { - // todo: bfs lookup? if (auto maybe = m_scope->get(name, currentNamespace()->prefix()); maybe.has_value()) return !maybe.value().is_mutable; } @@ -55,7 +54,6 @@ namespace Ark::internal { const std::string origin_namespace = currentNamespace()->prefix(); return std::ranges::any_of(std::ranges::reverse_view(m_scopes), [&name, &origin_namespace](const auto& scope) { - // todo: bfs lookup? return scope->get(name, origin_namespace).has_value(); }); } @@ -67,8 +65,6 @@ namespace Ark::internal std::pair, std::string> ScopeResolver::tryFullyQualifyName(const std::string& name) const { - // todo: move the error handling of the NameResolutionPass here? -> complicated, probably not worth it - // search in current scope and parent static scopes // if nothing, look in other scopes that are in the namespace imports (direct + indirect) // filter using the import list (glob, symbols, or prefix) @@ -124,7 +120,6 @@ namespace Ark::internal } // if we didn't find a FQN for 'name' in the pile of active scopes, try via the import list - // todo: put this in a separate method if (!res.qualified_name) { // todo: precompute the queue, given the import list diff --git a/src/arkreactor/Compiler/Package/ImportSolver.cpp b/src/arkreactor/Compiler/Package/ImportSolver.cpp index b3b04028..aa3b9fcd 100644 --- a/src/arkreactor/Compiler/Package/ImportSolver.cpp +++ b/src/arkreactor/Compiler/Package/ImportSolver.cpp @@ -82,12 +82,14 @@ namespace Ark::internal if (import_list[i].package == package) continue; - // todo: this might fail on unknown imports? - std::vector indirect_imports = m_package_to_imports[import_list[i].package]; - std::erase_if(indirect_imports, [&import_list](const Import& import) -> bool { - return std::ranges::find(import_list, import) != import_list.end(); - }); - std::ranges::copy(indirect_imports, std::back_inserter(import_list)); + if (auto it = m_package_to_imports.find(import_list[i].package); it != m_package_to_imports.end()) + { + std::vector indirect_imports = it->second; + std::erase_if(indirect_imports, [&import_list](const Import& import) -> bool { + return std::ranges::find(import_list, import) != import_list.end(); + }); + std::ranges::copy(indirect_imports, std::back_inserter(import_list)); + } } m_package_to_imports[package] = import_list; diff --git a/src/arkreactor/State.cpp b/src/arkreactor/State.cpp index 1af7c211..fed4d351 100644 --- a/src/arkreactor/State.cpp +++ b/src/arkreactor/State.cpp @@ -3,14 +3,15 @@ #include #include #include +#include #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable : 4996) #endif +#include #include -#include #include #include @@ -68,7 +69,7 @@ namespace Ark if (stream != nullptr) welder.redirectLogsTo(*stream); - for (const auto& key : m_bound | std::views::keys) + for (const auto& key : m_bound | std::ranges::views::keys) welder.registerSymbol(key); if (!welder.computeASTFromFile(file)) From 43eb56f7747128346bd63aedfb6860985c1aaa01 Mon Sep 17 00:00:00 2001 From: Lexy Plateau Date: Tue, 1 Dec 2026 18:35:28 +0100 Subject: [PATCH 8/8] chore: update changelog --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13946911..74b3a228 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,9 @@ ### Added ### Changed +- import solver tracks imports per file, to be used later by the name resolution pass +- C++ unittests now keep running even when ArkScript code can't compile, so that we can have a complete picture of the failing tests +- name resolution isn't based on import order any more (GitHub issue #712) ### Removed