diff --git a/src/common.cpp b/src/common.cpp index 8296250..33e82d1 100644 --- a/src/common.cpp +++ b/src/common.cpp @@ -395,6 +395,21 @@ short cmp_tag(Tag lhs, Tag rhs) { return 0; } +Result Dict::create(const Array& arr) { + if (arr.size() % 2 != 0) return ERROR(KeyError); + + Dict res = TRY(Dict::create()); + + for (uint64_t i = 0; i < arr.size() / 2; i++) { + auto key = TRY(Value::create(arr._value->data[2 * i].get())); + auto value = TRY(Value::create(arr._value->data[2 * i + 1].get())); + + res = TRY(res.insert(key, value)); + } + + return std::move(res); +} + Result Dict::get(const Value& key) const { auto pos = TRY(find(key)); if (pos >= size()) return ERROR(KeyError); diff --git a/src/common.hpp b/src/common.hpp index 1360d28..e268729 100644 --- a/src/common.hpp +++ b/src/common.hpp @@ -149,6 +149,8 @@ class Nil : public Object { class Array : public Object { public: + friend class Dict; + Array() {} Array(Array&& rhs) : _value(std::move(rhs._value)) {} Array(GcRoot&& val) : _value(std::move(val)) {} @@ -356,6 +358,8 @@ class Dict : public Object { static Result create(PodDict* obj) { return Dict(TRY(MkGcRoot(obj))); } + static Result create(const Array& arr); + static Result create() { auto pod = TRY(arena_alloc()); pod->header.tag = Tag::Dict; diff --git a/src/stdlib.cpp b/src/stdlib.cpp index 958b7f9..17222e3 100644 --- a/src/stdlib.cpp +++ b/src/stdlib.cpp @@ -64,6 +64,11 @@ Result stdlib_assert(const Array& params) { return Value(TRY(Nil::create())); } +Result stdlib_dict(const Array& params) { + Value d = TRY(Dict::create(params)); + return d; +} + #define STDLIB_FUNCTION(name, id) \ [(uint64_t)StdlibFunctionId::id] = {#name, StdlibFunctionId::id, \ stdlib_##name} @@ -74,6 +79,7 @@ static StdlibFunctionEntry function_entries[] = { STDLIB_FUNCTION(println, PrintLn), STDLIB_FUNCTION(prn, Prn), STDLIB_FUNCTION(assert, Assert), + STDLIB_FUNCTION(dict, Dict), [(uint64_t)StdlibFunctionId::Max] = {0, StdlibFunctionId::Max, stdlib_unknown}, }; diff --git a/src/stdlib.hpp b/src/stdlib.hpp index 6043808..9403ecb 100644 --- a/src/stdlib.hpp +++ b/src/stdlib.hpp @@ -10,6 +10,7 @@ enum class StdlibFunctionId : uint64_t { PrintLn, Prn, Assert, + Dict, Max, };