Skip to content

Commit

Permalink
Add scope and field classes for improved item management
Browse files Browse the repository at this point in the history
  • Loading branch information
riccardodebenedictis committed Nov 21, 2024
1 parent b536b5a commit 19fafa0
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 1 deletion.
2 changes: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ enable_testing()

option(COMPUTE_NAMES "Compute RiDDLe names" OFF)

add_library(RiDDLe src/core.cpp src/env.cpp src/type.cpp src/item.cpp src/lexer.cpp)
add_library(RiDDLe src/core.cpp src/scope.cpp src/env.cpp src/type.cpp src/item.cpp src/lexer.cpp)
target_compile_features(RiDDLe PUBLIC cxx_std_17)
target_include_directories(RiDDLe PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>)
if(NOT TARGET utils)
Expand Down
67 changes: 67 additions & 0 deletions include/scope.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#pragma once

#include <string>
#include <vector>
#include <memory>
#include <map>

namespace riddle
{
class core;
class type;

/**
* @brief A field.
*/
class field
{
public:
field(type &tp, std::string &&name) noexcept;

/**
* @brief Retrieves the type of the field.
*
* This function returns a reference to the type of the field.
*
* @return A reference to the type of the field.
*/
[[nodiscard]] type &get_type() const noexcept { return tp; }

/**
* @brief Retrieves the name of the field.
*
* This function returns a reference to the name of the field.
*
* @return A reference to the name of the field.
*/
[[nodiscard]] const std::string &get_name() const noexcept { return name; }

private:
type &tp;
std::string name;
};

class scope
{
public:
scope(core &c, scope &parent, std::vector<std::unique_ptr<field>> &&args = {});
virtual ~scope() = default;

protected:
/**
* @brief Adds a field to the scope.
*
* This function takes ownership of the provided field and adds it to the scope.
*
* @param field A unique pointer to the field to be added.
*/
void add_field(std::unique_ptr<field> field);

private:
core &cr;
scope &parent;

protected:
std::map<std::string, std::unique_ptr<field>, std::less<>> fields;
};
} // namespace riddle
19 changes: 19 additions & 0 deletions src/scope.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#include "scope.hpp"
#include <stdexcept>

namespace riddle
{
field::field(type &tp, std::string &&name) noexcept : tp(tp), name(std::move(name)) {}

scope::scope(core &c, scope &parent, std::vector<std::unique_ptr<field>> &&args) : cr(c), parent(parent)
{
for (auto &arg : args)
add_field(std::move(arg));
}

void scope::add_field(std::unique_ptr<field> field)
{
if (!fields.emplace(field->get_name(), std::move(field)).second)
throw std::runtime_error("Field already exists.");
}
} // namespace riddle

0 comments on commit 19fafa0

Please sign in to comment.