• Skip to content
  • Skip to link menu
Trinity API Reference
  • Trinity API Reference
  • kjs
 

kjs

  • kjs
array_object.cpp
1 // -*- c-basic-offset: 2 -*-
2 /*
3  * This file is part of the KDE libraries
4  * Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
5  * Copyright (C) 2003 Apple Computer, Inc.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  *
21  */
22 
23 #include "value.h"
24 #include "object.h"
25 #include "types.h"
26 #include "interpreter.h"
27 #include "operations.h"
28 #include "array_object.h"
29 #include "internal.h"
30 #include "error_object.h"
31 
32 #include "array_object.lut.h"
33 
34 #include <stdio.h>
35 #include <string.h>
36 #include <assert.h>
37 
38 #define MAX_INDEX 4294967294U // 2^32-2
39 
40 using namespace KJS;
41 
42 // ------------------------------ ArrayInstanceImp -----------------------------
43 
44 const unsigned sparseArrayCutoff = 10000;
45 
46 const ClassInfo ArrayInstanceImp::info = {"Array", 0, 0, 0};
47 
48 ArrayInstanceImp::ArrayInstanceImp(ObjectImp *proto, unsigned initialLength)
49  : ObjectImp(proto)
50  , length(initialLength)
51  , storageLength(initialLength < sparseArrayCutoff ? initialLength : 0)
52  , capacity(storageLength)
53  , storage(capacity ? (ValueImp **)calloc(capacity, sizeof(ValueImp *)) : 0)
54 {
55 }
56 
57 ArrayInstanceImp::ArrayInstanceImp(ObjectImp *proto, const List &list)
58  : ObjectImp(proto)
59  , length(list.size())
60  , storageLength(length)
61  , capacity(storageLength)
62  , storage(capacity ? (ValueImp **)malloc(sizeof(ValueImp *) * capacity) : 0)
63 {
64  ListIterator it = list.begin();
65  unsigned l = length;
66  for (unsigned i = 0; i < l; ++i) {
67  storage[i] = (it++).imp();
68  }
69 }
70 
71 ArrayInstanceImp::~ArrayInstanceImp()
72 {
73  free(storage);
74 }
75 
76 Value ArrayInstanceImp::get(ExecState *exec, const Identifier &propertyName) const
77 {
78  if (propertyName == lengthPropertyName)
79  return Number(length);
80 
81  bool ok;
82  unsigned index = propertyName.toArrayIndex(&ok);
83  if (ok) {
84  if (index >= length)
85  return Undefined();
86  if (index < storageLength) {
87  ValueImp *v = storage[index];
88  return v ? Value(v) : Undefined();
89  }
90  }
91 
92  return ObjectImp::get(exec, propertyName);
93 }
94 
95 Value ArrayInstanceImp::getPropertyByIndex(ExecState *exec,
96  unsigned index) const
97 {
98  if (index > MAX_INDEX)
99  return ObjectImp::get(exec, Identifier::from(index));
100  if (index >= length)
101  return Undefined();
102  if (index < storageLength) {
103  ValueImp *v = storage[index];
104  return v ? Value(v) : Undefined();
105  }
106 
107  return ObjectImp::get(exec, Identifier::from(index));
108 }
109 
110 // Special implementation of [[Put]] - see ECMA 15.4.5.1
111 void ArrayInstanceImp::put(ExecState *exec, const Identifier &propertyName, const Value &value, int attr)
112 {
113  if (propertyName == lengthPropertyName) {
114  unsigned int newLen = value.toUInt32(exec);
115  if (value.toNumber(exec) != double(newLen)) {
116  Object err = Error::create(exec, RangeError, "Invalid array length.");
117  exec->setException(err);
118  return;
119  }
120  setLength(newLen, exec);
121  return;
122  }
123 
124  bool ok;
125  unsigned index = propertyName.toArrayIndex(&ok);
126  if (ok) {
127  putPropertyByIndex(exec, index, value, attr);
128  return;
129  }
130 
131  ObjectImp::put(exec, propertyName, value, attr);
132 }
133 
134 void ArrayInstanceImp::putPropertyByIndex(ExecState *exec, unsigned index,
135  const Value &value, int attr)
136 {
137  if (index < sparseArrayCutoff && index >= storageLength) {
138  resizeStorage(index + 1);
139  }
140 
141  if (index >= length && index <= MAX_INDEX) {
142  length = index + 1;
143  }
144 
145  if (index < storageLength) {
146  storage[index] = value.imp();
147  return;
148  }
149 
150  assert(index >= sparseArrayCutoff);
151  ObjectImp::put(exec, Identifier::from(index), value, attr);
152 }
153 
154 bool ArrayInstanceImp::hasProperty(ExecState *exec, const Identifier &propertyName) const
155 {
156  if (propertyName == lengthPropertyName)
157  return true;
158 
159  bool ok;
160  unsigned index = propertyName.toArrayIndex(&ok);
161  if (ok) {
162  if (index >= length)
163  return false;
164  if (index < storageLength) {
165  ValueImp *v = storage[index];
166  return v && v != UndefinedImp::staticUndefined;
167  }
168  }
169 
170  return ObjectImp::hasProperty(exec, propertyName);
171 }
172 
173 bool ArrayInstanceImp::hasPropertyByIndex(ExecState *exec, unsigned index) const
174 {
175  if (index > MAX_INDEX)
176  return ObjectImp::hasProperty(exec, Identifier::from(index));
177  if (index >= length)
178  return false;
179  if (index < storageLength) {
180  ValueImp *v = storage[index];
181  return v && v != UndefinedImp::staticUndefined;
182  }
183 
184  return ObjectImp::hasProperty(exec, Identifier::from(index));
185 }
186 
187 bool ArrayInstanceImp::deleteProperty(ExecState *exec, const Identifier &propertyName)
188 {
189  if (propertyName == lengthPropertyName)
190  return false;
191 
192  bool ok;
193  unsigned index = propertyName.toArrayIndex(&ok);
194  if (ok) {
195  if (index >= length)
196  return true;
197  if (index < storageLength) {
198  storage[index] = 0;
199  return true;
200  }
201  }
202 
203  return ObjectImp::deleteProperty(exec, propertyName);
204 }
205 
206 bool ArrayInstanceImp::deletePropertyByIndex(ExecState *exec, unsigned index)
207 {
208  if (index > MAX_INDEX)
209  return ObjectImp::deleteProperty(exec, Identifier::from(index));
210  if (index >= length)
211  return true;
212  if (index < storageLength) {
213  storage[index] = 0;
214  return true;
215  }
216 
217  return ObjectImp::deleteProperty(exec, Identifier::from(index));
218 }
219 
220 ReferenceList ArrayInstanceImp::propList(ExecState *exec, bool recursive)
221 {
222  ReferenceList properties = ObjectImp::propList(exec,recursive);
223 
224  // avoid fetching this every time through the loop
225  ValueImp *undefined = UndefinedImp::staticUndefined;
226 
227  for (unsigned i = 0; i < storageLength; ++i) {
228  ValueImp *imp = storage[i];
229  if (imp && imp != undefined && !ObjectImp::hasProperty(exec,Identifier::from(i))) {
230  properties.append(Reference(this, i));
231  }
232  }
233  return properties;
234 }
235 
236 void ArrayInstanceImp::resizeStorage(unsigned newLength)
237 {
238  if (newLength < storageLength) {
239  memset(storage + newLength, 0, sizeof(ValueImp *) * (storageLength - newLength));
240  }
241  if (newLength > capacity) {
242  unsigned newCapacity;
243  if (newLength > sparseArrayCutoff) {
244  newCapacity = newLength;
245  } else {
246  newCapacity = (newLength * 3 + 1) / 2;
247  if (newCapacity > sparseArrayCutoff) {
248  newCapacity = sparseArrayCutoff;
249  }
250  }
251  storage = (ValueImp **)realloc(storage, newCapacity * sizeof (ValueImp *));
252  memset(storage + capacity, 0, sizeof(ValueImp *) * (newCapacity - capacity));
253  capacity = newCapacity;
254  }
255  storageLength = newLength;
256 }
257 
258 void ArrayInstanceImp::setLength(unsigned newLength, ExecState *exec)
259 {
260  if (newLength <= storageLength) {
261  resizeStorage(newLength);
262  }
263 
264  if (newLength < length) {
265  ReferenceList sparseProperties;
266 
267  _prop.addSparseArrayPropertiesToReferenceList(sparseProperties, Object(this));
268 
269  ReferenceListIterator it = sparseProperties.begin();
270  while (it != sparseProperties.end()) {
271  Reference ref = it++;
272  bool ok;
273  unsigned index = ref.getPropertyName(exec).toArrayIndex(&ok);
274  if (ok && index > newLength) {
275  ref.deleteValue(exec);
276  }
277  }
278  }
279 
280  length = newLength;
281 }
282 
283 void ArrayInstanceImp::mark()
284 {
285  ObjectImp::mark();
286  unsigned l = storageLength;
287  for (unsigned i = 0; i < l; ++i) {
288  ValueImp *imp = storage[i];
289  if (imp && !imp->marked())
290  imp->mark();
291  }
292 }
293 
294 static ExecState *execForCompareByStringForQSort;
295 
296 static int compareByStringForQSort(const void *a, const void *b)
297 {
298  ExecState *exec = execForCompareByStringForQSort;
299  ValueImp *va = *(ValueImp **)a;
300  ValueImp *vb = *(ValueImp **)b;
301  if (va->dispatchType() == UndefinedType) {
302  return vb->dispatchType() == UndefinedType ? 0 : 1;
303  }
304  if (vb->dispatchType() == UndefinedType) {
305  return -1;
306  }
307  return compare(va->dispatchToString(exec), vb->dispatchToString(exec));
308 }
309 
310 void ArrayInstanceImp::sort(ExecState *exec)
311 {
312  int lengthNotIncludingUndefined = pushUndefinedObjectsToEnd(exec);
313 
314  execForCompareByStringForQSort = exec;
315  qsort(storage, lengthNotIncludingUndefined, sizeof(ValueImp *), compareByStringForQSort);
316  execForCompareByStringForQSort = 0;
317 }
318 
319 namespace KJS {
320 
321 struct CompareWithCompareFunctionArguments {
322  CompareWithCompareFunctionArguments(ExecState *e, ObjectImp *cf)
323  : exec(e)
324  , compareFunction(cf)
325  , globalObject(e->dynamicInterpreter()->globalObject())
326  {
327  arguments.append(Undefined());
328  arguments.append(Undefined());
329  }
330 
331  ExecState *exec;
332  ObjectImp *compareFunction;
333  List arguments;
334  Object globalObject;
335 };
336 
337 }
338 
339 static CompareWithCompareFunctionArguments *compareWithCompareFunctionArguments;
340 
341 static int compareWithCompareFunctionForQSort(const void *a, const void *b)
342 {
343  CompareWithCompareFunctionArguments *args = compareWithCompareFunctionArguments;
344 
345  ValueImp *va = *(ValueImp **)a;
346  ValueImp *vb = *(ValueImp **)b;
347  if (va->dispatchType() == UndefinedType) {
348  return vb->dispatchType() == UndefinedType ? 0 : 1;
349  }
350  if (vb->dispatchType() == UndefinedType) {
351  return -1;
352  }
353 
354  args->arguments.clear();
355  args->arguments.append(va);
356  args->arguments.append(vb);
357  double compareResult = args->compareFunction->call
358  (args->exec, args->globalObject, args->arguments).toNumber(args->exec);
359  return compareResult < 0 ? -1 : compareResult > 0 ? 1 : 0;
360 }
361 
362 void ArrayInstanceImp::sort(ExecState *exec, Object &compareFunction)
363 {
364  int lengthNotIncludingUndefined = pushUndefinedObjectsToEnd(exec);
365 
366  CompareWithCompareFunctionArguments args(exec, compareFunction.imp());
367  compareWithCompareFunctionArguments = &args;
368  qsort(storage, lengthNotIncludingUndefined, sizeof(ValueImp *), compareWithCompareFunctionForQSort);
369  compareWithCompareFunctionArguments = 0;
370 }
371 
372 unsigned ArrayInstanceImp::pushUndefinedObjectsToEnd(ExecState *exec)
373 {
374  ValueImp *undefined = UndefinedImp::staticUndefined;
375 
376  unsigned o = 0;
377 
378  for (unsigned i = 0; i != storageLength; ++i) {
379  ValueImp *v = storage[i];
380  if (v && v != undefined) {
381  if (o != i)
382  storage[o] = v;
383  o++;
384  }
385  }
386 
387  ReferenceList sparseProperties;
388  _prop.addSparseArrayPropertiesToReferenceList(sparseProperties, Object(this));
389  unsigned newLength = o + sparseProperties.length();
390 
391  if (newLength > storageLength) {
392  resizeStorage(newLength);
393  }
394 
395  ReferenceListIterator it = sparseProperties.begin();
396  while (it != sparseProperties.end()) {
397  Reference ref = it++;
398  storage[o] = ref.getValue(exec).imp();
399  ObjectImp::deleteProperty(exec, ref.getPropertyName(exec));
400  o++;
401  }
402 
403  if (newLength != storageLength)
404  memset(storage + o, 0, sizeof(ValueImp *) * (storageLength - o));
405 
406  return o;
407 }
408 
409 // ------------------------------ ArrayPrototypeImp ----------------------------
410 
411 const ClassInfo ArrayPrototypeImp::info = {"Array", &ArrayInstanceImp::info, &arrayTable, 0};
412 
413 /* Source for array_object.lut.h
414 @begin arrayTable 17
415  toString ArrayProtoFuncImp::ToString DontEnum|Function 0
416  toLocaleString ArrayProtoFuncImp::ToLocaleString DontEnum|Function 0
417  concat ArrayProtoFuncImp::Concat DontEnum|Function 1
418  join ArrayProtoFuncImp::Join DontEnum|Function 1
419  pop ArrayProtoFuncImp::Pop DontEnum|Function 0
420  push ArrayProtoFuncImp::Push DontEnum|Function 1
421  reverse ArrayProtoFuncImp::Reverse DontEnum|Function 0
422  shift ArrayProtoFuncImp::Shift DontEnum|Function 0
423  slice ArrayProtoFuncImp::Slice DontEnum|Function 2
424  sort ArrayProtoFuncImp::Sort DontEnum|Function 1
425  splice ArrayProtoFuncImp::Splice DontEnum|Function 2
426  unshift ArrayProtoFuncImp::UnShift DontEnum|Function 1
427 @end
428 */
429 
430 // ECMA 15.4.4
431 ArrayPrototypeImp::ArrayPrototypeImp(ExecState */*exec*/,
432  ObjectPrototypeImp *objProto)
433  : ArrayInstanceImp(objProto, 0)
434 {
435  Value protect(this);
436  setInternalValue(Null());
437 }
438 
439 Value ArrayPrototypeImp::get(ExecState *exec, const Identifier &propertyName) const
440 {
441  //fprintf( stderr, "[kjs-array_object] ArrayPrototypeImp::get(%s)\n", propertyName.ascii() );
442  return lookupGetFunction<ArrayProtoFuncImp, ArrayInstanceImp>( exec, propertyName, &arrayTable, this );
443 }
444 
445 // ------------------------------ ArrayProtoFuncImp ----------------------------
446 
447 ArrayProtoFuncImp::ArrayProtoFuncImp(ExecState *exec, int i, int len)
448  : InternalFunctionImp(
449  static_cast<FunctionPrototypeImp*>(exec->lexicalInterpreter()->builtinFunctionPrototype().imp())
450  ), id(i)
451 {
452  Value protect(this);
453  put(exec,lengthPropertyName,Number(len),DontDelete|ReadOnly|DontEnum);
454 }
455 
456 bool ArrayProtoFuncImp::implementsCall() const
457 {
458  return true;
459 }
460 
461 // ECMA 15.4.4
462 Value ArrayProtoFuncImp::call(ExecState *exec, Object &thisObj, const List &args)
463 {
464  unsigned int length = thisObj.get(exec,lengthPropertyName).toUInt32(exec);
465 
466  Value result;
467  switch (id) {
468  case ToLocaleString:
469  case ToString:
470 
471  if (!thisObj.inherits(&ArrayInstanceImp::info)) {
472  Object err = Error::create(exec,TypeError);
473  exec->setException(err);
474  return err;
475  }
476 
477  // fall through
478  case Join: {
479  UString separator = ",";
480  UString str = "";
481 
482  if (id == Join && args.size() > 0 && !args[0].isA(UndefinedType))
483  separator = args[0].toString(exec);
484  for (unsigned int k = 0; k < length; k++) {
485  if (k >= 1)
486  str += separator;
487 
488  Value element = thisObj.get(exec, k);
489  if (element.type() == UndefinedType || element.type() == NullType)
490  continue;
491 
492  bool fallback = false;
493  if (id == ToLocaleString) {
494  Object o = element.toObject(exec);
495  Object conversionFunction =
496  Object::dynamicCast(o.get(exec, toLocaleStringPropertyName));
497  if (conversionFunction.isValid() &&
498  conversionFunction.implementsCall()) {
499  str += conversionFunction.call(exec, o, List()).toString(exec);
500  } else {
501  // try toString() fallback
502  fallback = true;
503  }
504  }
505  if (id == ToString || id == Join || fallback) {
506  if (element.type() == ObjectType) {
507  Object o = Object::dynamicCast(element);
508  Object conversionFunction =
509  Object::dynamicCast(o.get(exec, toStringPropertyName));
510  if (conversionFunction.isValid() &&
511  conversionFunction.implementsCall()) {
512  str += conversionFunction.call(exec, o, List()).toString(exec);
513  } else {
514  UString msg = "Can't convert " + o.className() +
515  " object to string";
516  Object error = Error::create(exec, RangeError,
517  msg.cstring().c_str());
518  exec->setException(error);
519  return error;
520  }
521  } else {
522  str += element.toString(exec);
523  }
524  }
525  if ( exec->hadException() )
526  break;
527  }
528  result = String(str);
529  break;
530  }
531  case Concat: {
532  Object arr = Object::dynamicCast(exec->lexicalInterpreter()->builtinArray().construct(exec,List::empty()));
533  int n = 0;
534  Value curArg = thisObj;
535  Object curObj = Object::dynamicCast(thisObj);
536  ListIterator it = args.begin();
537  for (;;) {
538  if (curArg.type() == ObjectType &&
539  curObj.inherits(&ArrayInstanceImp::info)) {
540  unsigned int k = 0;
541  // Older versions tried to optimize out getting the length of thisObj
542  // by checking for n != 0, but that doesn't work if thisObj is an empty array.
543  length = curObj.get(exec,lengthPropertyName).toUInt32(exec);
544  while (k < length) {
545  if (curObj.hasProperty(exec,k))
546  arr.put(exec, n, curObj.get(exec, k));
547  n++;
548  k++;
549  }
550  } else {
551  arr.put(exec, n, curArg);
552  n++;
553  }
554  if (it == args.end())
555  break;
556  curArg = *it;
557  curObj = Object::dynamicCast(it++); // may be 0
558  }
559  arr.put(exec,lengthPropertyName, Number(n), DontEnum | DontDelete);
560 
561  result = arr;
562  break;
563  }
564  case Pop:{
565  if (length == 0) {
566  thisObj.put(exec, lengthPropertyName, Number(length), DontEnum | DontDelete);
567  result = Undefined();
568  } else {
569  result = thisObj.get(exec, length - 1);
570  thisObj.put(exec, lengthPropertyName, Number(length - 1), DontEnum | DontDelete);
571  }
572  break;
573  }
574  case Push: {
575  for (int n = 0; n < args.size(); n++)
576  thisObj.put(exec, length + n, args[n]);
577  length += args.size();
578  thisObj.put(exec,lengthPropertyName, Number(length), DontEnum | DontDelete);
579  result = Number(length);
580  break;
581  }
582  case Reverse: {
583 
584  unsigned int middle = length / 2;
585 
586  for (unsigned int k = 0; k < middle; k++) {
587  unsigned lk1 = length - k - 1;
588  Value obj = thisObj.get(exec,k);
589  Value obj2 = thisObj.get(exec,lk1);
590  if (thisObj.hasProperty(exec,lk1)) {
591  if (thisObj.hasProperty(exec,k)) {
592  thisObj.put(exec, k, obj2);
593  thisObj.put(exec, lk1, obj);
594  } else {
595  thisObj.put(exec, k, obj2);
596  thisObj.deleteProperty(exec, lk1);
597  }
598  } else {
599  if (thisObj.hasProperty(exec, k)) {
600  thisObj.deleteProperty(exec, k);
601  thisObj.put(exec, lk1, obj);
602  } else {
603  // why delete something that's not there ? Strange.
604  thisObj.deleteProperty(exec, k);
605  thisObj.deleteProperty(exec, lk1);
606  }
607  }
608  }
609  result = thisObj;
610  break;
611  }
612  case Shift: {
613  if (length == 0) {
614  thisObj.put(exec, lengthPropertyName, Number(length), DontEnum | DontDelete);
615  result = Undefined();
616  } else {
617  result = thisObj.get(exec, 0);
618  for(unsigned int k = 1; k < length; k++) {
619  if (thisObj.hasProperty(exec, k)) {
620  Value obj = thisObj.get(exec, k);
621  thisObj.put(exec, k-1, obj);
622  } else
623  thisObj.deleteProperty(exec, k-1);
624  }
625  thisObj.deleteProperty(exec, length - 1);
626  thisObj.put(exec, lengthPropertyName, Number(length - 1), DontEnum | DontDelete);
627  }
628  break;
629  }
630  case Slice: {
631  // http://developer.netscape.com/docs/manuals/js/client/jsref/array.htm#1193713 or 15.4.4.10
632 
633  // We return a new array
634  Object resObj = Object::dynamicCast(exec->lexicalInterpreter()->builtinArray().construct(exec,List::empty()));
635  result = resObj;
636  int begin = 0;
637  if (args[0].type() != UndefinedType) {
638  begin = args[0].toInteger(exec);
639  if ( begin < 0 )
640  begin = maxInt( begin + length, 0 );
641  else
642  begin = minInt( begin, length );
643  }
644  int end = length;
645  if (args[1].type() != UndefinedType)
646  {
647  end = args[1].toInteger(exec);
648  if ( end < 0 )
649  end = maxInt( end + length, 0 );
650  else
651  end = minInt( end, length );
652  }
653 
654  //printf( "Slicing from %d to %d \n", begin, end );
655  int n = 0;
656  for(int k = begin; k < end; k++, n++) {
657  if (thisObj.hasProperty(exec, k)) {
658  Value obj = thisObj.get(exec, k);
659  resObj.put(exec, n, obj);
660  }
661  }
662  resObj.put(exec, lengthPropertyName, Number(n), DontEnum | DontDelete);
663  break;
664  }
665  case Sort:{
666 #if 0
667  printf("KJS Array::Sort length=%d\n", length);
668  for ( unsigned int i = 0 ; i<length ; ++i )
669  printf("KJS Array::Sort: %d: %s\n", i, thisObj.get(exec, i).toString(exec).ascii() );
670 #endif
671  Object sortFunction;
672  bool useSortFunction = (args[0].type() != UndefinedType);
673  if (useSortFunction)
674  {
675  sortFunction = args[0].toObject(exec);
676  if (!sortFunction.implementsCall())
677  useSortFunction = false;
678  }
679 
680  if (thisObj.imp()->classInfo() == &ArrayInstanceImp::info) {
681  if (useSortFunction)
682  ((ArrayInstanceImp *)thisObj.imp())->sort(exec, sortFunction);
683  else
684  ((ArrayInstanceImp *)thisObj.imp())->sort(exec);
685  result = thisObj;
686  break;
687  }
688 
689  if (length == 0) {
690  thisObj.put(exec, lengthPropertyName, Number(0), DontEnum | DontDelete);
691  result = thisObj;
692  break;
693  }
694 
695  // "Min" sort. Not the fastest, but definitely less code than heapsort
696  // or quicksort, and much less swapping than bubblesort/insertionsort.
697  for ( unsigned int i = 0 ; i<length-1 ; ++i )
698  {
699  Value iObj = thisObj.get(exec,i);
700  unsigned int themin = i;
701  Value minObj = iObj;
702  for ( unsigned int j = i+1 ; j<length ; ++j )
703  {
704  Value jObj = thisObj.get(exec,j);
705  double cmp;
706  if (jObj.type() == UndefinedType) {
707  cmp = 1; // don't check minObj because there's no need to differentiate == (0) from > (1)
708  } else if (minObj.type() == UndefinedType) {
709  cmp = -1;
710  } else if (useSortFunction) {
711  List l;
712  l.append(jObj);
713  l.append(minObj);
714  cmp = sortFunction.call(exec, exec->dynamicInterpreter()->globalObject(), l).toNumber(exec);
715  } else {
716  cmp = (jObj.toString(exec) < minObj.toString(exec)) ? -1 : 1;
717  }
718  if ( cmp < 0 )
719  {
720  themin = j;
721  minObj = jObj;
722  }
723  }
724  // Swap themin and i
725  if ( themin > i )
726  {
727  //printf("KJS Array::Sort: swapping %d and %d\n", i, themin );
728  thisObj.put( exec, i, minObj );
729  thisObj.put( exec, themin, iObj );
730  }
731  }
732 #if 0
733  printf("KJS Array::Sort -- Resulting array:\n");
734  for ( unsigned int i = 0 ; i<length ; ++i )
735  printf("KJS Array::Sort: %d: %s\n", i, thisObj.get(exec, i).toString(exec).ascii() );
736 #endif
737  result = thisObj;
738  break;
739  }
740  case Splice: {
741  // 15.4.4.12 - oh boy this is huge
742  Object resObj = Object::dynamicCast(exec->lexicalInterpreter()->builtinArray().construct(exec,List::empty()));
743  result = resObj;
744  int begin = args[0].toUInt32(exec);
745  if ( begin < 0 )
746  begin = maxInt( begin + length, 0 );
747  else
748  begin = minInt( begin, length );
749  unsigned int deleteCount = minInt( maxInt( args[1].toUInt32(exec), 0 ), length - begin );
750 
751  //printf( "Splicing from %d, deleteCount=%d \n", begin, deleteCount );
752  for(unsigned int k = 0; k < deleteCount; k++) {
753  if (thisObj.hasProperty(exec,k+begin)) {
754  Value obj = thisObj.get(exec, k+begin);
755  resObj.put(exec, k, obj);
756  }
757  }
758  resObj.put(exec, lengthPropertyName, Number(deleteCount), DontEnum | DontDelete);
759 
760  unsigned int additionalArgs = maxInt( args.size() - 2, 0 );
761  if ( additionalArgs != deleteCount )
762  {
763  if ( additionalArgs < deleteCount )
764  {
765  for ( unsigned int k = begin; k < length - deleteCount; ++k )
766  {
767  if (thisObj.hasProperty(exec,k+deleteCount)) {
768  Value obj = thisObj.get(exec, k+deleteCount);
769  thisObj.put(exec, k+additionalArgs, obj);
770  }
771  else
772  thisObj.deleteProperty(exec, k+additionalArgs);
773  }
774  for ( unsigned int k = length ; k > length - deleteCount + additionalArgs; --k )
775  thisObj.deleteProperty(exec, k-1);
776  }
777  else
778  {
779  for ( unsigned int k = length - deleteCount; (int)k > begin; --k )
780  {
781  if (thisObj.hasProperty(exec,k+deleteCount-1)) {
782  Value obj = thisObj.get(exec, k+deleteCount-1);
783  thisObj.put(exec, k+additionalArgs-1, obj);
784  }
785  else
786  thisObj.deleteProperty(exec, k+additionalArgs-1);
787  }
788  }
789  }
790  for ( unsigned int k = 0; k < additionalArgs; ++k )
791  {
792  thisObj.put(exec, k+begin, args[k+2]);
793  }
794  thisObj.put(exec, lengthPropertyName, Number(length - deleteCount + additionalArgs), DontEnum | DontDelete);
795  break;
796  }
797  case UnShift: { // 15.4.4.13
798  unsigned int nrArgs = args.size();
799  for ( unsigned int k = length; k > 0; --k )
800  {
801  if (thisObj.hasProperty(exec,k-1)) {
802  Value obj = thisObj.get(exec, k-1);
803  thisObj.put(exec, k+nrArgs-1, obj);
804  } else {
805  thisObj.deleteProperty(exec, k+nrArgs-1);
806  }
807  }
808  for ( unsigned int k = 0; k < nrArgs; ++k )
809  thisObj.put(exec, k, args[k]);
810  result = Number(length + nrArgs);
811  thisObj.put(exec, lengthPropertyName, result, DontEnum | DontDelete);
812  break;
813  }
814  default:
815  assert(0);
816  break;
817  }
818  return result;
819 }
820 
821 // ------------------------------ ArrayObjectImp -------------------------------
822 
823 ArrayObjectImp::ArrayObjectImp(ExecState *exec,
824  FunctionPrototypeImp *funcProto,
825  ArrayPrototypeImp *arrayProto)
826  : InternalFunctionImp(funcProto)
827 {
828  Value protect(this);
829  // ECMA 15.4.3.1 Array.prototype
830  put(exec,prototypePropertyName, Object(arrayProto), DontEnum|DontDelete|ReadOnly);
831 
832  // no. of arguments for constructor
833  put(exec,lengthPropertyName, Number(1), ReadOnly|DontDelete|DontEnum);
834 }
835 
836 bool ArrayObjectImp::implementsConstruct() const
837 {
838  return true;
839 }
840 
841 // ECMA 15.4.2
842 Object ArrayObjectImp::construct(ExecState *exec, const List &args)
843 {
844  // a single numeric argument denotes the array size (!)
845  if (args.size() == 1 && args[0].type() == NumberType) {
846  unsigned int n = args[0].toUInt32(exec);
847  if (n != args[0].toNumber(exec)) {
848  Object error = Error::create(exec, RangeError, "Invalid array length.");
849  exec->setException(error);
850  return error;
851  }
852  return Object(new ArrayInstanceImp(exec->lexicalInterpreter()->builtinArrayPrototype().imp(), n));
853  }
854 
855  // otherwise the array is constructed with the arguments in it
856  return Object(new ArrayInstanceImp(exec->lexicalInterpreter()->builtinArrayPrototype().imp(), args));
857 }
858 
859 bool ArrayObjectImp::implementsCall() const
860 {
861  return true;
862 }
863 
864 // ECMA 15.6.1
865 Value ArrayObjectImp::call(ExecState *exec, Object &/*thisObj*/, const List &args)
866 {
867  // equivalent to 'new Array(....)'
868  return construct(exec,args);
869 }
KJS::Value
Value objects are act as wrappers ("smart pointers") around ValueImp objects and their descendents...
Definition: value.h:168
KJS::Object::hasProperty
bool hasProperty(ExecState *exec, const Identifier &propertyName) const
Checks to see whether the object (or any object in it&#39;s prototype chain) has a property with the spec...
Definition: object.h:679
KJS::Value::toString
UString toString(ExecState *exec) const
Performs the ToString type conversion operation on this value (ECMA 9.8)
Definition: value.h:247
KJS::Value::toNumber
double toNumber(ExecState *exec) const
Performs the ToNumber type conversion operation on this value (ECMA 9.3)
Definition: value.h:222
KJS::InternalFunctionImp
Base class for all function objects.
Definition: function.h:41
KJS::Value::toObject
Object toObject(ExecState *exec) const
Performs the ToObject type conversion operation on this value (ECMA 9.9)
Definition: object.h:359
KJS::Object::construct
Object construct(ExecState *exec, const List &args)
Creates a new object based on this object.
Definition: object.h:697
KJS::Number
Represents an primitive Number value.
Definition: value.h:368
KJS::ReferenceListIterator
An iterator for a ReferenceList.
Definition: reference_list.h:37
KJS::Reference::getValue
Value getValue(ExecState *exec) const
Performs the GetValue type conversion operation on this value (ECMA 8.7.1)
Definition: reference.cpp:118
KJS::List::append
void append(const Value &val)
Append an object to the end of the list.
Definition: list.h:66
KJS::Object::get
Value get(ExecState *exec, const Identifier &propertyName) const
Retrieves the specified property from the object.
Definition: object.h:664
KJS::Object::deleteProperty
bool deleteProperty(ExecState *exec, const Identifier &propertyName)
Removes the specified property from the object.
Definition: object.h:685
KJS::Value::type
Type type() const
Returns the type of value.
Definition: value.h:196
KJS::ExecState::lexicalInterpreter
Interpreter * lexicalInterpreter() const
Returns the interpreter associated with the current scope&#39;s global object.
Definition: interpreter.cpp:395
KJS::Null
Represents an primitive Null value.
Definition: value.h:295
KJS::UString::ascii
char * ascii() const
Convert the Unicode string to plain ASCII chars chopping of any higher bytes.
Definition: ustring.cpp:486
KJS::ExecState::dynamicInterpreter
Interpreter * dynamicInterpreter() const
Returns the interpreter associated with this execution state.
Definition: interpreter.h:453
KJS::FunctionPrototypeImp
The initial value of Function.prototype (and thus all objects created with the Function constructor) ...
Definition: function_object.h:35
KJS::List::end
ListIterator end() const
Definition: list.h:187
KJS::Interpreter::builtinArrayPrototype
Object builtinArrayPrototype() const
Returns the builtin "Array.prototype" object.
Definition: interpreter.cpp:229
KJS::Interpreter::builtinArray
Object builtinArray() const
Returns the builtin "Array" object.
Definition: interpreter.cpp:184
KJS::List::size
int size() const
Definition: list.h:90
KJS::Object::className
UString className() const
Returns the class name of the object.
Definition: object.h:661
KJS::Object
Represents an Object.
Definition: object.h:82
TDEStdAccel::end
const TDEShortcut & end()
KJS::Undefined
Represents an primitive Undefined value.
Definition: value.h:270
KJS::UString
Unicode string class.
Definition: ustring.h:190
KJS::String
Represents an primitive String value.
Definition: value.h:341
KJS::Reference
Defines a Javascript reference.
Definition: reference.h:35
KJS::Object::implementsCall
bool implementsCall() const
Whether or not the object implements the call() method.
Definition: object.h:700
KJS
Definition: array_instance.h:28
KJS::ValueImp
ValueImp is the base type for all primitives (Undefined, Null, Boolean, String, Number) and objects i...
Definition: value.h:79
KJS::Interpreter::globalObject
Object & globalObject() const
Returns the object that is used as the global object during all script execution performed by this in...
Definition: interpreter.cpp:129
KJS::Value::isValid
bool isValid() const
Returns whether or not this is a valid value.
Definition: value.h:182
KJS::ReferenceList
A list of Reference objects.
Definition: reference_list.h:54
KJS::Value::toUInt32
unsigned int toUInt32(ExecState *exec) const
Performs the ToUInt32 type conversion operation on this value (ECMA 9.6)
Definition: value.h:237
KJS::Object::put
void put(ExecState *exec, const Identifier &propertyName, const Value &value, int attr=None)
Sets the specified property.
Definition: object.h:670
KJS::List
Native list type.
Definition: list.h:48
KJS::ClassInfo
Class Information.
Definition: object.h:59
KJS::Object::call
Value call(ExecState *exec, Object &thisObj, const List &args)
Calls this object as if it is a function.
Definition: object.cpp:54
KJS::List::begin
ListIterator begin() const
Definition: list.h:186
KJS::Reference::getPropertyName
Identifier getPropertyName(ExecState *exec) const
Performs the GetPropertyName type conversion operation on this value (ECMA 8.7)
Definition: reference.cpp:104
KJS::ExecState
Represents the current state of script execution.
Definition: interpreter.h:439
KJS::UString::cstring
CString cstring() const
Definition: ustring.cpp:481
KJS::Identifier
Represents an Identifier for a Javascript object.
Definition: identifier.h:32
KJS::ListIterator
Iterator for KJS::List objects.
Definition: list.h:138

kjs

Skip menu "kjs"
  • Main Page
  • Class Hierarchy
  • Alphabetical List
  • Class List
  • File List
  • Class Members
  • Related Pages

kjs

Skip menu "kjs"
  • arts
  • dcop
  • dnssd
  • interfaces
  •   kspeech
  •     interface
  •     library
  •   tdetexteditor
  • kate
  • kded
  • kdoctools
  • kimgio
  • kjs
  • libtdemid
  • libtdescreensaver
  • tdeabc
  • tdecmshell
  • tdecore
  • tdefx
  • tdehtml
  • tdeinit
  • tdeio
  •   bookmarks
  •   httpfilter
  •   kpasswdserver
  •   kssl
  •   tdefile
  •   tdeio
  •   tdeioexec
  • tdeioslave
  •   http
  • tdemdi
  •   tdemdi
  • tdenewstuff
  • tdeparts
  • tdeprint
  • tderandr
  • tderesources
  • tdespell2
  • tdesu
  • tdeui
  • tdeunittest
  • tdeutils
  • tdewallet
Generated for kjs by doxygen 1.8.13
This website is maintained by Timothy Pearson.