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

Last change on this file since 569 was 545, checked in by Maciej Komosinski, 8 years ago

Dictionary.set() documentation updated

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