ArkScript
A small, fast, functional and scripting language for video games
LocalsLocator.cpp
Go to the documentation of this file.
2
3#include <ranges>
4
5namespace Ark::internal
6{
8 {
9 // create a default scope
10 m_scopes.emplace_back();
11 }
12
13 void LocalsLocator::addLocal(const std::string& name)
14 {
15 auto& scope = m_scopes.back();
16 if (std::ranges::find(scope.data, name) == scope.data.end())
17 scope.data.push_back(name);
18 }
19
20 std::optional<std::size_t> LocalsLocator::lookupLastScopeByName(const std::string& name)
21 {
22 auto& [data, type] = m_scopes.back();
23
24 if (type != ScopeType::Closure)
25 {
26 // Compute the index of the variable in the active scope from the end.
27 if (const auto it = std::ranges::find(data, name); it != data.end())
28 return static_cast<std::size_t>(std::distance(it, data.end())) - 1;
29 }
30
31 return std::nullopt;
32 }
33
35 {
36 m_scopes.emplace_back(Scope {
37 .data = {},
38 .type = type });
39 }
40
42 {
43 m_scopes.pop_back();
44 }
45
47 {
48 m_drop_for_conds.push_back(m_scopes.back().data.size());
49 }
50
52 {
53 const auto old_length = m_drop_for_conds.back();
54 m_drop_for_conds.pop_back();
55
56 auto& back = m_scopes.back();
57 if (back.data.size() > old_length)
58 back.data.erase(
59 back.data.begin() + static_cast<decltype(back.data)::difference_type>(old_length),
60 back.data.end());
61 }
62}
Track locals at compile.
void saveScopeLengthForBranch()
Save the current scope length before entering a branch, so that we can ignore variable definitions in...
std::vector< Scope > m_scopes
std::vector< std::size_t > m_drop_for_conds
Needed to drop variables inside if/else branches since they don't have their own scope.
std::optional< std::size_t > lookupLastScopeByName(const std::string &name)
Search for a local in the current scope. Returns std::nullopt in case of closure scopes or if the var...
void dropVarsForBranch()
Drop potentially defined variables in the last saved branch.
void deleteScope()
Delete the last scope.
void addLocal(const std::string &name)
Register a local in the current scope, triggered by a STORE instruction. If the local already exists,...
LocalsLocator()
Create a new LocalsLocator to track the position of variables in the scope stack.
void createScope(ScopeType type=ScopeType::Default)
Create a new scope.