source: cpp/frams/vm/classes/collectionobj.cpp @ 849

Last change on this file since 849 was 849, checked in by Maciej Komosinski, 5 years ago

Added Dictionary.hasKey(). Accessing non-existent dictionary keys becomes an error.

  • Property svn:eol-style set to native
File size: 16.7 KB
RevLine 
[286]1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
[849]2// Copyright (C) 1999-2019  Maciej Komosinski and Szymon Ulatowski.
[286]3// See LICENSE.txt for details.
[109]4
5#include "collectionobj.h"
6#include <common/nonstd_math.h> //sqrt in borland
[375]7#include <frams/util/validitychecks.h>
[109]8#include <common/nonstd_stl.h>
9#include <frams/util/sstringutils.h>
10#ifndef NO_VMACHINE
11#include <frams/vm/vmachine.h>
12#endif
13
14#define FIELDSTRUCT VectorObject
[746]15ParamEntry vector_paramtab[] =
[109]16{
[746]17        { "Vector", 1, 15, "Vector", "Vector is a 1-dimensional array indexed by an integer value (starting from 0). "
18        "Multidimensional arrays can be simulated by putting other Vector objects into a Vector.\n"
19        "Examples:\n"
20        "\tvar v1=Vector.new();\n"
21        "\tv1.add(123);\n"
22        "\tv1.add(\"string\");\n"
23        "A short way of doing the same (square brackets create a vector):\n"
24        "\tvar v2=[123,\"string\"];\n"
25        "Simulate a 2D array:\n"
26        "\tvar v3=[[1,2,3],[4,5],[6]];\n"
27        "You can iterate directly over values of a Vector using for(...in...) loops:\n"
28        "\tfor(var element in v3) Simulator.print(element);"
29        },
30        { "clear", 0, PARAM_NOSTATIC, "Clear data", "p()", PROCEDURE(p_clear), },
31        { "size", 0, PARAM_READONLY | PARAM_NOSTATIC, "Element count", "d", GETONLY(size), },
32        { "remove", 0, PARAM_NOSTATIC, "Remove at position", "p(d position)", PROCEDURE(p_remove), },
33        { "get", 0, PARAM_NOSTATIC, "Get value at position", "p x(d position)", PROCEDURE(p_get), "object[position] can be always used instead of object.get(position)" },
34        { "set", 0, PARAM_NOSTATIC, "Set value at position", "p(d position,x value)", PROCEDURE(p_set), "object[position]=value can be always used instead of object.set(position,value)" },
35        { "insert", 0, PARAM_NOSTATIC, "Insert value at position", "p(d position,x value)", PROCEDURE(p_insert), },
36        { "add", 0, PARAM_NOSTATIC, "Append at the end", "p(x value)", PROCEDURE(p_add), },
37        { "find", 0, PARAM_NOSTATIC, "Find", "p d(x value)", PROCEDURE(p_find), "returns the element index or -1 if not found" },
38        { "avg", 0, PARAM_READONLY | PARAM_NOSTATIC, "Average", "f", GETONLY(avg) },
39        { "stdev", 0, PARAM_READONLY | PARAM_NOSTATIC, "Standard deviation", "f", GETONLY(stdev), "=sqrt(sum((element[i]-avg)^2)/(size-1)) which is estimated population std.dev. from sample std.dev." },
40        { "toString", 0, PARAM_READONLY | PARAM_NOSTATIC, "Textual form", "s", GETONLY(toString), },
41        { "new", 0, 0, "Create new Vector", "p oVector()", STATICPROCEDURE(p_new), },
42        { "sort", 0, PARAM_NOSTATIC, "Sort elements (in place)", "p(oFunctionReference comparator)", PROCEDURE(p_sort), "comparator can be null, giving the \"natural\" sorting order (depending on element type), otherwise it must be a function reference obtained from the 'function' operator.\n\nExample:\nfunction compareLastDigit(a,b) {return (a%10)<(b%10);}\nvar v=[16,23,35,42,54,61];\nv.sort(function compareLastDigit);" },
43        { "iterator", 0, PARAM_NOSTATIC | PARAM_READONLY, "Iterator", "o", GETONLY(iterator), },
44        { "clone", 0, PARAM_NOSTATIC, "Create a clone", "p oVector()", PROCEDURE(p_clone), "The resulting clone is a shallow copy (contains the same object references as the original). A deep copy can be obtained through serialization: String.deserialize(String.serialize(object));" },
45        { 0, 0, 0, },
[109]46};
47#undef FIELDSTRUCT
48
49#define FIELDSTRUCT DictionaryObject
[746]50ParamEntry dictionary_paramtab[] =
[109]51{
[849]52        { "Dictionary", 1, 12, "Dictionary", "Dictionary associates stored values with string keys "
[746]53        "(\"key\" is the first argument in get/set/remove functions). Integer key can be "
54        "used to enumerate all elements (note that while iterating, the elements are returned in no particular order).\n"
55        "Examples:\n"
56        "\tvar d;\n"
57        "\td=Dictionary.new();\n"
58        "\td.set(\"name\",\"John\");\n"
59        "\td.set(\"age\",44);\n"
60        "Another way of doing the same:\n"
61        "\td={};\n"
62        "\td[\"name\"]=\"John\";\n"
63        "\td[\"age\"]=44;\n"
64        "And the most concise way:\n"
65        "\td={ \"name\":\"John\", \"age\":44 };\n"
66        "Iterating:\n"
67        "\tfor(var i=0;i<d.size;i++) Simulator.print(d.getKey(i)+\" is \"+d.get(i));",
68        },
69        { "clear", 0, PARAM_NOSTATIC, "Clear data", "p()", PROCEDURE(p_clear), },
70        { "size", 0, PARAM_NOSTATIC | PARAM_READONLY, "Element count", "d", GETONLY(size), },
71        { "remove", 0, PARAM_NOSTATIC, "Remove", "p(x key)", PROCEDURE(p_remove), "Removes the named or indexed element (depending on the argument type: string or int)." },
[849]72        { "get", 0, PARAM_NOSTATIC, "Get element", "p x(x key)", PROCEDURE(p_get), "Retrieves the named or indexed element (depending on the argument type: string or int). Accessing nonexistent keys is an error (use hasKey() if necessary).\nobject.get(key) can be shortened to 'object[key]'" },
[746]73        { "getKey", 0, PARAM_NOSTATIC, "Get a key", "p s(d index)", PROCEDURE(p_getKey), "Returns the key of the indexed element (0 <= index < size)" },
[849]74        { "hasKey", 0, PARAM_NOSTATIC, "Check if key exists", "p d(s key)", PROCEDURE(p_hasKey), "Returns 1 (interpreted as true) if dictionary contains the supplied key, or 0 (false) otherwise.\nExample:\n   if (obj.hasKey(\"a\"))\n      x = obj->a;" },
[746]75        { "set", 0, PARAM_NOSTATIC, "Set element", "p x(x key,x value)", PROCEDURE(p_set), "Set element value for the specified key or index (depending on the argument type: string or int).\n"
76        "Returns the value previously associated with the given key (or index).\n"
77        "object.set(key,value) can be shortened to object[key]=value. Literal string keys can use even shorter notation: object->key=value instead of object.set(\"key\",value)\n"
78        "Note the difference in the returned value:\n"
79        "  var old_value=object.set(\"key\",new_value); //'old_value' gets the value previously associated with \"key\"\n"
80        "  var x=object[\"key\"]=new_value; //'x' becomes 'new_value', consistently with the semantics of the assignment operator. The value previously associated with \"key\" is lost." },
81        { "find", 0, PARAM_NOSTATIC, "Find", "p x(x value)", PROCEDURE(p_find), "Returns the element key or null if not found." },
82        { "new", 0, 0, "Create a Dictionary", "p oDictionary()", STATICPROCEDURE(p_new), "Empty directory can be also created using the {} expression." },
83        { "toString", 0, PARAM_READONLY | PARAM_NOSTATIC, "Textual form", "s", GETONLY(toString), },
84        { "clone", 0, PARAM_NOSTATIC, "Create a clone", "p oDictionary()", PROCEDURE(p_clone), "The resulting clone is a shallow copy (contains the same object references as the original). A deep copy can be obtained through serialization: String.deserialize(String.serialize(object));" },
85        { "assign", 0, PARAM_NOSTATIC, "Assign from another object", "p(x)", PROCEDURE(p_assign), "Replaces current dictionary with dictionary contents from another object." },
[478]86
[746]87        { 0, 0, 0, },
[109]88};
89#undef FIELDSTRUCT
90
91Param VectorObject::par(vector_paramtab);
92Param DictionaryObject::par(dictionary_paramtab);
93
94/////////////////////////////////////////
95
96VectorObject::VectorObject(Pt3D &pt)
[746]97        :readonly(0), owndata(1)
[109]98{
[746]99        set_or_insert(0, ExtValue(pt.x), false);
100        set_or_insert(1, ExtValue(pt.y), false);
101        set_or_insert(2, ExtValue(pt.z), false);
[109]102}
103
104void VectorObject::clear()
105{
[746]106        if (owndata)
107                for (int i = data.size() - 1; i >= 0; i--)
108                {
[849]109                        ExtValue *v = (ExtValue*)data.get(i);
110                        if (v) delete v;
[746]111                }
112        data.clear();
[109]113}
114
115void VectorObject::p_remove(PARAMPROCARGS)
116{
[746]117        if (readonly) return;
118        int i = args->getInt();
119        if (!listIndexCheck(&data, i, "VectorObject", "remove")) return;
120        ExtValue *v = (ExtValue*)data.get(i);
121        if (v) delete v;
122        data -= i;
[109]123}
124
[746]125void VectorObject::set_or_insert(int i, const ExtValue& val, bool insert)
[109]126{
[746]127        if (i < 0) return;
128        int oldsize = data.size();
129        if (i > oldsize)
[109]130        {
[746]131                data.setSize(i);
132                while (i > oldsize)
133                        data.set(oldsize++, 0);
[109]134        }
[746]135        if (insert)
136                data.insert(i, new ExtValue(val));
137        else
[642]138        {
[746]139                ExtValue *v = (ExtValue*)data.get(i);
140                if (v) delete v;
141                data.set(i, new ExtValue(val));
[642]142        }
[109]143}
144
145void VectorObject::p_get(PARAMPROCARGS)
146{
[746]147        int i = args->getInt();
148        if (listIndexCheck(&data, i, "VectorObject", "get"))
[109]149        {
[746]150                ExtValue *v = get(i);
151                if (v)
[109]152                {
[746]153                        *ret = *v;
154                        return;
[109]155                }
156        }
[746]157        *ret = ExtValue();
[109]158}
159
160void VectorObject::get_avg(ExtValue* ret)
161{
[746]162        if (!data.size()) { ret->setEmpty(); return; }
163        double s = 0.0;
164        for (int i = data.size() - 1; i >= 0; i--)
165                s += ((ExtValue*)data.get(i))->getDouble();
166        s /= data.size();
167        ret->setDouble(s);
[109]168}
169
[464]170SString VectorObject::serialize(SerializationFormat format) const
[109]171{
[746]172        SString out = "[";
[109]173        {
[746]174                for (int i = 0; i < data.size(); i++)
[109]175                {
[746]176                        ExtValue* v = (ExtValue*)data.get(i);
177                        if (i) out += ",";
178                        if (v)
179                                out += v->serialize(format);
180                        else
181                                out += "null";
[109]182                }
183        }
[746]184        out += "]";
185        //sprintf(out.directAppend(20),"<Vector@%p>",this);out.endAppend();
186        return out;
[109]187}
188
[746]189static THREAD_LOCAL_DEF(SList, VectorObject_tostring_trace);
[109]190
191void VectorObject::get_toString(ExtValue* ret)
192{
[746]193        SString out = "[";
194        //static SListTempl<VectorObject*> trace;
195        if (tlsGetRef(VectorObject_tostring_trace).find(this) >= 0)
196                out += "...";
197        else
[109]198        {
[746]199                tlsGetRef(VectorObject_tostring_trace) += this;
200                for (int i = 0; i < data.size(); i++)
[109]201                {
[746]202                        ExtValue* v = (ExtValue*)data.get(i);
203                        if (i) out += ",";
204                        if (v)
205                                out += v->getString();
206                        else
207                                out += "null";
[109]208                }
[746]209                tlsGetRef(VectorObject_tostring_trace) -= this;
[109]210        }
[746]211        out += "]";
212        ret->setString(out);
[109]213}
214
215void VectorObject::get_stdev(ExtValue* ret)
216{
[746]217        if (!data.size()) { ret->setEmpty(); return; }
218        get_avg(ret);
219        double a = ret->getDouble();
220        double s = 0.0;
221        for (int i = data.size() - 1; i >= 0; i--)
[109]222        {
[746]223                double d = a - ((ExtValue*)data.get(i))->getDouble();
[849]224                s += d * d;
[109]225        }
[746]226        ret->setDouble(sqrt(s / max(1, data.size() - 1)));
[109]227}
228
229void VectorObject::p_find(PARAMPROCARGS)
230{
[746]231        short i;
232        for (i = 0; i < data.size(); i++)
[109]233        {
[746]234                if ((*args) == (*get(i)))
235                {
236                        ret->setInt(i); return;
237                }
[109]238        }
[746]239        ret->setInt(-1);
[109]240}
241
[453]242void VectorObject::p_clone(PARAMPROCARGS)
243{
[746]244        VectorObject *c = new VectorObject;
245        c->data.setSize(data.size());
246        for (int i = 0; i < data.size(); i++)
[453]247        {
[746]248                ExtValue *v = (ExtValue*)get(i);
249                if (v)
250                        c->data.set(i, new ExtValue(*v));
[453]251        }
[746]252        ret->setObject(ExtObject(&par, c));
[453]253}
254
[109]255class VEComparator
256{
257public:
[746]258        bool operator()(const ExtValue *a, const ExtValue *b) { return a->compare(*b) == ExtValue::ResultLower; }
[109]259};
260
261#ifndef NO_VMACHINE
262class VMVEComparator
263{
264public:
[746]265        VMachine::JumpTargetObject *jto;
266        VMachine *vm;
267        VMVEComparator(VMachine::JumpTargetObject *_jto) :jto(_jto), vm(jto->vm) {}
268        bool operator()(const ExtValue *a, const ExtValue *b);
[109]269};
270
[746]271bool VMVEComparator::operator()(const ExtValue *a, const ExtValue *b)
[109]272{
[746]273        if (!VMCode::prepareDynamicJumpTarget(jto->pc, jto->code))
274                return false;
[109]275
[746]276        vm->push(*a);
277        vm->push(*b);
278        vm->pushNewCallState();
279        vm->jumpDynamicJumpTarget(jto->pc);
280        vm->run();
281        vm->popCallState();
282        bool ret;
283        ExtValue& retval = vm->getValue();
284        if (retval.type == TInvalid)
[109]285        {
[746]286                ret = false;
287                logPrintf("VectorElementComparator", "", LOG_ERROR, "Comparison function returned no value");
[109]288        }
[746]289        else
290                ret = (retval.getInt() != 0);
291        vm->drop(2);
292        return ret;
[109]293}
294#endif
295
296void VectorObject::p_sort(PARAMPROCARGS)
297{
298#ifndef NO_VMACHINE
[746]299        VMachine::JumpTargetObject *jto = VMachine::JumpTargetObject::fromObject(args->getObject(), false);
300        if (jto)
[109]301        {
[746]302                VMVEComparator cmp(jto);
303                ExtValue **first = (ExtValue**)&data.getref(0);
304                std::sort(first, first + data.size(), cmp);
[109]305        }
[746]306        else
[109]307#endif
308        {
[746]309                VEComparator cmp;
310                ExtValue **first = (ExtValue**)&data.getref(0);
311                std::sort(first, first + data.size(), cmp);
[109]312        }
[746]313        ret->setEmpty();
[109]314}
315
316void VectorObject::get_iterator(ExtValue* ret)
317{
[746]318        ret->setObject(VectorIterator::makeFrom(this));
[109]319}
320
[171]321VectorObject* VectorObject::fromObject(const ExtObject& o, bool warn)
[109]322{
[746]323        return (VectorObject*)o.getTarget(par.getName(), true, warn);
[109]324}
325
326/////////////////////////////
327
328void DictionaryObject::clear()
329{
[746]330        for (HashEntryIterator it(hash); it.isValid();)
[109]331        {
[746]332                ExtValue *v = (ExtValue*)hash.remove(it);
333                if (v) delete v;
[109]334        }
[746]335        hash.clear();
336        hash.init();
[109]337}
338
339void DictionaryObject::p_find(PARAMPROCARGS)
340{
[746]341        for (HashEntryIterator it(hash); it.isValid(); it++)
[109]342        {
[746]343                if ((*args) == (*((ExtValue*)it->value)))
[109]344                {
[746]345                        ret->setString(it->key);
346                        return;
[109]347                }
348        }
[746]349        ret->setEmpty();
[109]350}
351
352HashEntryIterator* DictionaryObject::getIndexIterator(int i)
353{
[746]354        if (i < 0) return 0;
355        if (i >= hash.getSize()) return 0;
[109]356
[746]357        if ((!it.isValid()) || (it_index > i))
[109]358        {
[746]359                it = HashEntryIterator(hash);
360                it_index = 0;
[109]361        }
[746]362        while (it.isValid())
[109]363        {
[746]364                if (it_index == i)
365                        return &it;
366                it_index++;
367                it++;
[109]368        }
[746]369        return 0;
[109]370}
371
372void DictionaryObject::p_remove(PARAMPROCARGS)
373{
[746]374        if ((args->type == TInt) || (args->type == TDouble))
[109]375        {
[746]376                HashEntryIterator* iter = getIndexIterator(args->getInt());
377                if (iter)
[109]378                {
[746]379                        ExtValue *oldval = (ExtValue*)hash.remove(*iter);
380                        if (oldval) { *ret = *oldval; delete oldval; }
381                        else *ret = ExtValue();
[109]382                }
383        }
[746]384        else
[109]385        {
[746]386                ExtValue *oldval = (ExtValue*)hash.remove(args[0].getString());
387                if (oldval) { *ret = *oldval; delete oldval; }
388                else *ret = ExtValue();
[109]389        }
390}
391
[478]392ExtValue DictionaryObject::get(SString key)
393{
[849]394        int found = 0;
395        ExtValue *val = (ExtValue*)hash.get(key, &found);
396        if (found == 0)
397        {
398                logPrintf("Dictionary", "get", LOG_ERROR, "Key '%s' not found", key.c_str());
399                return ExtValue::invalid();
400        }
401        else
402        {
403                if (val)
404                        return *val;
405                return ExtValue::empty();
406        }
[478]407}
408
409ExtValue DictionaryObject::get(int index)
410{
[746]411        HashEntryIterator* iter = getIndexIterator(index);
412        if (iter && (*iter)->value)
413                return *((ExtValue*)(*iter)->value);
414        return ExtValue::empty();
[478]415}
416
[109]417void DictionaryObject::p_get(PARAMPROCARGS)
418{
[746]419        if ((args->type == TInt) || (args->type == TDouble))
420                *ret = get(args->getInt());
421        else
422                *ret = get(args[0].getString());
[109]423}
424
425void DictionaryObject::p_getKey(PARAMPROCARGS)
426{
[746]427        HashEntryIterator* iter = getIndexIterator(args->getInt());
428        if (iter)
[109]429        {
[746]430                *ret = (*iter)->key;
431                return;
[109]432        }
[746]433        *ret = ExtValue();
[109]434}
435
[849]436void DictionaryObject::p_hasKey(PARAMPROCARGS)
437{
438        int found = 0;
439        hash.get(args->getString(), &found);
440        ret->setInt(found);
441}
442
[746]443ExtValue DictionaryObject::set(SString key, ExtValue new_value)
[478]444{
[746]445        ExtValue ret;
446        ExtValue *new_ext = (new_value.getType() == TUnknown) ? NULL : new ExtValue(new_value);
447        ExtValue *old_ext = (ExtValue*)hash.put(key, new_ext);
448        if (old_ext) { ret = *old_ext; delete old_ext; }
449        return ret;
[478]450}
451
[109]452void DictionaryObject::p_set(PARAMPROCARGS)
453{
[746]454        *ret = set(args[1].getString(), args[0]);
[109]455}
456
[464]457SString DictionaryObject::serialize(SerializationFormat format) const
[109]458{
[746]459        SString out = "{";
[109]460        {
[746]461                for (HashEntryIterator it(hash); it.isValid();)
[109]462                {
[746]463                        out += "\"";
464                        SString q = it->key; sstringQuote(q);
465                        out += q;
466                        out += "\":";
467                        if (it->value != NULL)
468                                out += ((ExtValue*)it->value)->serialize(format);
469                        else
470                                out += "null";
471                        it++;
472                        if (it.isValid()) out += ",";
[109]473                }
474        }
[746]475        out += "}";
476        return out;
[109]477}
478
479void DictionaryObject::get_toString(ExtValue* ret)
480{
[746]481        SString out = "{";
482        //static SListTempl<DictionaryObject*> trace;
483        if (tlsGetRef(VectorObject_tostring_trace).find(this) >= 0)
484                out += "...";
485        else
[109]486        {
[746]487                tlsGetRef(VectorObject_tostring_trace) += this;
488                for (HashEntryIterator it(hash); it.isValid();)
[109]489                {
[746]490                        out += it->key;
491                        out += ":";
492                        if (it->value != NULL)
493                                out += ((ExtValue*)it->value)->getString();
494                        else
495                                out += "null";
496                        it++;
497                        if (it.isValid()) out += ",";
[109]498                }
[746]499                tlsGetRef(VectorObject_tostring_trace) -= this;
[109]500        }
[746]501        out += "}";
502        ret->setString(out);
[109]503}
504
[478]505void DictionaryObject::copyFrom(DictionaryObject *other)
[453]506{
[746]507        for (HashEntryIterator it(other->hash); it.isValid(); it++)
[453]508        {
[746]509                ExtValue *v = (ExtValue*)it->value;
510                hash.put(it->key, v ? new ExtValue(*v) : NULL);
[453]511        }
[478]512}
513
514void DictionaryObject::p_clone(PARAMPROCARGS)
515{
[746]516        DictionaryObject *c = new DictionaryObject;
517        c->copyFrom(this);
518        ret->setObject(ExtObject(&par, c));
[453]519}
520
[478]521void DictionaryObject::p_assign(PARAMPROCARGS)
522{
[746]523        clear();
524        DictionaryObject *other = DictionaryObject::fromObject(args[0].getObject(), false);
525        if (other)
[478]526                copyFrom(other);
[746]527        ret->setEmpty();
[478]528}
529
[171]530DictionaryObject* DictionaryObject::fromObject(const ExtObject& o, bool warn)
[109]531{
[746]532        return (DictionaryObject*)o.getTarget(par.getName(), true, warn);
[109]533}
534
535////////////////
536
537VectorIterator::VectorIterator(VectorObject* v)
538{
[746]539        vec = v;
540        vec->incref();
541        pos = -1;
[109]542}
543
544#define FIELDSTRUCT VectorIterator
[746]545ParamEntry vectoriterator_paramtab[] =
[109]546{
[746]547        { "VectorIterator", 1, 2, "VectorIterator", "VectorIterator" },
548        { "next", 0, PARAM_READONLY | PARAM_NOSTATIC, "next", "d 0 1", GETONLY(next), },
549        { "value", 0, PARAM_READONLY | PARAM_NOSTATIC, "value", "x", GETONLY(value), },
550        { 0, 0, 0, },
[109]551};
552#undef FIELDSTRUCT
553
554ExtObject VectorIterator::makeFrom(VectorObject *v)
555{
[746]556        static Param par(vectoriterator_paramtab);
557        return ExtObject(&par, new VectorIterator(v));
[109]558}
559
560VectorIterator::~VectorIterator()
561{
[746]562        vec->decref();
[109]563}
564
565void VectorIterator::get_next(ExtValue* ret)
566{
[746]567        pos++;
568        ret->setInt((pos < vec->data.size()) ? 1 : 0);
[109]569}
570
571void VectorIterator::get_value(ExtValue* ret)
572{
[746]573        ExtValue *v = (ExtValue*)(((pos >= 0) && (pos < vec->data.size())) ? vec->data(pos) : NULL);
574        if (v)
575                *ret = *v;
576        else
577                ret->setEmpty();
[109]578}
[490]579
580// not actually needed for deserialization (vector and dict are special cases) but findDeserializableClass can be also used in other contexts
581REGISTER_DESERIALIZABLE(VectorObject)
582REGISTER_DESERIALIZABLE(DictionaryObject)
Note: See TracBrowser for help on using the repository browser.