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

Last change on this file since 490 was 490, checked in by Maciej Komosinski, 9 years ago

Introduced general-use ErrorObject?, fixed enumeration of mixed private/public property lists

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