summaryrefslogtreecommitdiffstats
path: root/js/src/vm/TupleType.cpp
blob: a9b4df784c12201209b67a29cce05f4681bf29a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "vm/TupleType.h"

#include "mozilla/FloatingPoint.h"
#include "mozilla/HashFunctions.h"

#include "jsapi.h"

#include "builtin/TupleObject.h"
#include "gc/Allocator.h"
#include "gc/AllocKind.h"

#include "js/TypeDecls.h"
#include "js/Value.h"
#include "util/StringBuffer.h"
#include "vm/EqualityOperations.h"
#include "vm/GlobalObject.h"
#include "vm/JSContext.h"
#include "vm/RecordTupleShared.h"
#include "vm/RecordType.h"
#include "vm/SelfHosting.h"
#include "vm/ToSource.h"

#include "vm/GeckoProfiler-inl.h"
#include "vm/JSObject-inl.h"
#include "vm/NativeObject-inl.h"

using namespace js;

static bool TupleConstructor(JSContext* cx, unsigned argc, Value* vp);

static const JSFunctionSpec tuple_static_methods[] = {
    JS_FN("isTuple", tuple_is_tuple, 1, 0),
    JS_SELF_HOSTED_FN("from", "TupleFrom", 1, 0), JS_FN("of", tuple_of, 0, 0),
    JS_FS_END};

static const JSFunctionSpec tuple_methods[] = {
    JS_SELF_HOSTED_FN("toSorted", "TupleToSorted", 1, 0),
    JS_SELF_HOSTED_FN("toSpliced", "TupleToSpliced", 2, 0),
    JS_SELF_HOSTED_FN("concat", "TupleConcat", 0, 0),
    JS_SELF_HOSTED_FN("includes", "TupleIncludes", 1, 0),
    JS_SELF_HOSTED_FN("indexOf", "TupleIndexOf", 1, 0),
    JS_SELF_HOSTED_FN("join", "TupleJoin", 1, 0),
    JS_SELF_HOSTED_FN("lastIndexOf", "TupleLastIndexOf", 1, 0),
    JS_SELF_HOSTED_FN("toLocaleString", "TupleToLocaleString", 2, 0),
    JS_SELF_HOSTED_FN("toString", "TupleToString", 0, 0),
    JS_SELF_HOSTED_FN("entries", "TupleEntries", 0, 0),
    JS_SELF_HOSTED_FN("every", "TupleEvery", 1, 0),
    JS_SELF_HOSTED_FN("filter", "TupleFilter", 1, 0),
    JS_SELF_HOSTED_FN("find", "TupleFind", 1, 0),
    JS_SELF_HOSTED_FN("findIndex", "TupleFindIndex", 1, 0),
    JS_SELF_HOSTED_FN("forEach", "TupleForEach", 1, 0),
    JS_SELF_HOSTED_FN("keys", "TupleKeys", 0, 0),
    JS_SELF_HOSTED_FN("map", "TupleMap", 1, 0),
    JS_SELF_HOSTED_FN("reduce", "TupleReduce", 1, 0),
    JS_SELF_HOSTED_FN("reduceRight", "TupleReduceRight", 1, 0),
    JS_SELF_HOSTED_FN("some", "TupleSome", 1, 0),
    JS_SELF_HOSTED_FN("values", "$TupleValues", 0, 0),
    JS_SELF_HOSTED_SYM_FN(iterator, "$TupleValues", 0, 0),
    JS_SELF_HOSTED_FN("flat", "TupleFlat", 0, 0),
    JS_SELF_HOSTED_FN("flatMap", "TupleFlatMap", 1, 0),
    JS_SELF_HOSTED_FN("toReversed", "TupleToReversed", 0, 0),
    JS_FN("with", tuple_with, 2, 0),
    JS_FN("slice", tuple_slice, 2, 0),
    JS_FN("valueOf", tuple_value_of, 0, 0),
    JS_FS_END};

Shape* TupleType::getInitialShape(JSContext* cx) {
  return SharedShape::getInitialShape(cx, &TupleType::class_, cx->realm(),
                                      TaggedProto(nullptr), 0);
  // tuples don't have slots, but only integer-indexed elements.
}

// Prototype methods

// Proposal
// Tuple.prototype.with()
bool js::tuple_with(JSContext* cx, unsigned argc, Value* vp) {
  AutoGeckoProfilerEntry pseudoFrame(
      cx, "Tuple.prototype.with", JS::ProfilingCategoryPair::JS,
      uint32_t(ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  CallArgs args = CallArgsFromVp(argc, vp);

  /* Step 1. */
  RootedValue v(cx, args.thisv());

  mozilla::Maybe<TupleType&> maybeTuple = js::ThisTupleValue(cx, v);
  if (!maybeTuple) {
    return false;
  }

  Rooted<TupleType*> tuple(cx, &(*maybeTuple));

  /* Step 2. */
  uint64_t length = tuple->getDenseInitializedLength();
  TupleType* list = TupleType::createUninitialized(cx, length);
  if (!list) {
    return false;
  }

  /* Step 4 */
  uint64_t index;
  if (!ToIndex(cx, args.get(0), JSMSG_BAD_TUPLE_INDEX, &index)) {
    return false;
  }
  /* Step 5 */
  if (index >= length) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_BAD_TUPLE_INDEX, "Tuple.with");
    return false;
  }
  /* Step 6 */
  RootedValue value(cx, args.get(1));
  if (value.isObject()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_RECORD_TUPLE_NO_OBJECT, "Tuple.with");
    return false;
  }
  /* Step 7 */
  uint64_t before = index;
  uint64_t after = length - index - 1;
  list->copyDenseElements(0, tuple->getDenseElements(), before);
  list->setDenseInitializedLength(index + 1);
  list->initDenseElement(index, value);
  list->copyDenseElements(
      index + 1, tuple->getDenseElements() + uint32_t(index + 1), after);
  list->setDenseInitializedLength(length);
  list->finishInitialization(cx);
  /* Step 8 */
  args.rval().setExtendedPrimitive(*list);
  return true;
}

// Proposal
// Tuple.prototype.slice()
bool js::tuple_slice(JSContext* cx, unsigned argc, Value* vp) {
  AutoGeckoProfilerEntry pseudoFrame(
      cx, "Tuple.prototype.slice", JS::ProfilingCategoryPair::JS,
      uint32_t(ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  CallArgs args = CallArgsFromVp(argc, vp);
  RootedValue v(cx, args.thisv());

  /* Steps 1-2. */
  mozilla::Maybe<TupleType&> maybeList = js::ThisTupleValue(cx, v);
  if (!maybeList) {
    return false;
  }

  Rooted<TupleType*> list(cx, &(*maybeList));
  /* Step 3. */
  uint32_t len = list->getDenseInitializedLength();

  /* Step 4. */
  double relativeStart;
  if (!ToInteger(cx, args.get(0), &relativeStart)) {
    return false;
  }

  /* Step 5. */
  uint32_t k;
  if (relativeStart < 0.0) {
    k = std::max(len + relativeStart, 0.0);
  } else {
    k = std::min(relativeStart, double(len));
  }

  /* Step 6. */
  double relativeEnd;
  if (argc > 1 && !args.get(1).isUndefined()) {
    if (!ToInteger(cx, args.get(1), &relativeEnd)) {
      return false;
    }
  } else {
    relativeEnd = len;
  }

  /* Step 7. */
  uint32_t finalIndex;
  if (relativeEnd < 0.0) {
    finalIndex = std::max(len + relativeEnd, 0.0);
  } else {
    finalIndex = std::min(relativeEnd, double(len));
  }

  /* Step 8. */

  uint32_t newLen = finalIndex >= k ? finalIndex - k : 0;
  TupleType* newList = TupleType::createUninitialized(cx, newLen);
  if (!newList) {
    return false;
  }

  /* Step 9. */
  HeapSlotArray oldElements = list->getDenseElements();
  newList->copyDenseElements(0, oldElements + k, newLen);
  newList->setDenseInitializedLength(newLen);
  newList->finishInitialization(cx);
  /* Step 10. */
  args.rval().setExtendedPrimitive(*newList);
  return true;
}

// Proposal
// Tuple.prototype.valueOf()
bool js::tuple_value_of(JSContext* cx, unsigned argc, Value* vp) {
  AutoGeckoProfilerEntry pseudoFrame(
      cx, "Tuple.prototype.valueOf", JS::ProfilingCategoryPair::JS,
      uint32_t(ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  CallArgs args = CallArgsFromVp(argc, vp);

  /* Step 1. */
  HandleValue thisv = args.thisv();
  mozilla::Maybe<TupleType&> tuple = js::ThisTupleValue(cx, thisv);
  if (!tuple) {
    return false;
  }

  args.rval().setExtendedPrimitive(*tuple);
  return true;
}

bool TupleType::copy(JSContext* cx, Handle<TupleType*> in,
                     MutableHandle<TupleType*> out) {
  out.set(TupleType::createUninitialized(cx, in->length()));
  if (!out) {
    return false;
  }
  RootedValue v(cx), vCopy(cx);
  for (uint32_t i = 0; i < in->length(); i++) {
    // Let v = in[i]
    v.set(in->getDenseElement(i));

    // Copy v
    if (!CopyRecordTupleElement(cx, v, &vCopy)) {
      return false;
    }

    // Set result[i] to v
    if (!out->initializeNextElement(cx, vCopy)) {
      return false;
    }
  }
  out->finishInitialization(cx);
  return true;
}

TupleType* TupleType::create(JSContext* cx, uint32_t length,
                             const Value* elements) {
  for (uint32_t index = 0; index < length; index++) {
    if (!elements[index].isPrimitive()) {
      JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                JSMSG_RECORD_TUPLE_NO_OBJECT);
      return nullptr;
    }
  }

  TupleType* tup = TupleType::createUninitialized(cx, length);
  if (!tup) {
    return nullptr;
  }

  tup->initDenseElements(elements, length);
  tup->finishInitialization(cx);

  return tup;
}

static TupleType* allocate(JSContext* cx, gc::AllocKind allocKind) {
  Rooted<Shape*> shape(cx, TupleType::getInitialShape(cx));
  if (!shape) {
    return nullptr;
  }

  TupleType* tup =
      cx->newCell<TupleType>(allocKind, gc::Heap::Default, &TupleType::class_);
  if (!tup) {
    return nullptr;
  }

  tup->initShape(shape);
  tup->initEmptyDynamicSlots();
  tup->initFixedElements(allocKind, 0);
  return tup;
}

TupleType* TupleType::createUninitialized(JSContext* cx, uint32_t length) {
  gc::AllocKind allocKind = GuessArrayGCKind(length);

  TupleType* tup = allocate(cx, allocKind);
  if (!tup) {
    return nullptr;
  }

  if (!tup->ensureElements(cx, length)) {
    return nullptr;
  }

  return tup;
}

bool TupleType::initializeNextElement(JSContext* cx, HandleValue elt) {
  if (!elt.isPrimitive()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_RECORD_TUPLE_NO_OBJECT);
    return false;
  }

  uint32_t length = getDenseInitializedLength();

  if (!ensureElements(cx, length + 1)) {
    return false;
  }
  setDenseInitializedLength(length + 1);
  initDenseElement(length, elt);

  return true;
}

void TupleType::finishInitialization(JSContext* cx) {
  shrinkCapacityToInitializedLength(cx);

  ObjectElements* header = getElementsHeader();
  header->length = header->initializedLength;
  header->setNotExtensible();
  header->seal();
  header->freeze();
}

bool TupleType::getOwnProperty(HandleId id, MutableHandleValue vp) const {
  if (!id.isInt()) {
    return false;
  }

  int32_t index = id.toInt();
  if (index < 0 || uint32_t(index) >= length()) {
    return false;
  }

  vp.set(getDenseElement(index));
  return true;
}

js::HashNumber TupleType::hash(const TupleType::ElementHasher& hasher) const {
  MOZ_ASSERT(isAtomized());

  js::HashNumber h = mozilla::HashGeneric(length());
  for (uint32_t i = 0; i < length(); i++) {
    h = mozilla::AddToHash(h, hasher(getDenseElement(i)));
  }
  return h;
}

bool TupleType::ensureAtomized(JSContext* cx) {
  if (isAtomized()) {
    return true;
  }

  RootedValue child(cx);
  bool changed;

  for (uint32_t i = 0; i < length(); i++) {
    child.set(getDenseElement(i));
    if (!EnsureAtomized(cx, &child, &changed)) {
      return false;
    }
    if (changed) {
      // We cannot use setDenseElement(), because this object is frozen.
      elements_[i].set(this, HeapSlot::Element, unshiftedIndex(i), child);
    }
  }

  getElementsHeader()->setTupleIsAtomized();

  return true;
}

bool TupleType::sameValueZero(JSContext* cx, TupleType* lhs, TupleType* rhs,
                              bool* equal) {
  return sameValueWith<SameValueZero>(cx, lhs, rhs, equal);
}

bool TupleType::sameValue(JSContext* cx, TupleType* lhs, TupleType* rhs,
                          bool* equal) {
  return sameValueWith<SameValue>(cx, lhs, rhs, equal);
}
bool TupleType::sameValueZero(TupleType* lhs, TupleType* rhs) {
  MOZ_ASSERT(lhs->isAtomized());
  MOZ_ASSERT(rhs->isAtomized());

  if (lhs == rhs) {
    return true;
  }
  if (lhs->length() != rhs->length()) {
    return false;
  }

  Value v1, v2;

  for (uint32_t index = 0; index < lhs->length(); index++) {
    v1 = lhs->getDenseElement(index);
    v2 = rhs->getDenseElement(index);

    if (!js::SameValueZeroLinear(v1, v2)) {
      return false;
    }
  }

  return true;
}

template <bool Comparator(JSContext*, HandleValue, HandleValue, bool*)>
bool TupleType::sameValueWith(JSContext* cx, TupleType* lhs, TupleType* rhs,
                              bool* equal) {
  MOZ_ASSERT(lhs->getElementsHeader()->isFrozen());
  MOZ_ASSERT(rhs->getElementsHeader()->isFrozen());

  if (lhs == rhs) {
    *equal = true;
    return true;
  }

  if (lhs->length() != rhs->length()) {
    *equal = false;
    return true;
  }

  *equal = true;

  RootedValue v1(cx);
  RootedValue v2(cx);

  for (uint32_t index = 0; index < lhs->length(); index++) {
    v1.set(lhs->getDenseElement(index));
    v2.set(rhs->getDenseElement(index));

    if (!Comparator(cx, v1, v2, equal)) {
      return false;
    }

    if (!*equal) {
      return true;
    }
  }

  return true;
}

JSString* js::TupleToSource(JSContext* cx, Handle<TupleType*> tup) {
  JSStringBuilder sb(cx);

  if (!sb.append("#[")) {
    return nullptr;
  }

  uint32_t length = tup->length();

  RootedValue elt(cx);
  for (uint32_t index = 0; index < length; index++) {
    elt.set(tup->getDenseElement(index));

    /* Get element's character string. */
    JSString* str = ValueToSource(cx, elt);
    if (!str) {
      return nullptr;
    }

    /* Append element to buffer. */
    if (!sb.append(str)) {
      return nullptr;
    }
    if (index + 1 != length) {
      if (!sb.append(", ")) {
        return nullptr;
      }
    }
  }

  /* Finalize the buffer. */
  if (!sb.append(']')) {
    return nullptr;
  }

  return sb.finishString();
}

// Record and Tuple proposal section 9.2.1
bool TupleConstructor(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  // Step 1.
  if (args.isConstructing()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_NOT_CONSTRUCTOR, "Tuple");
    return false;
  }

  TupleType* tup = TupleType::create(cx, args.length(), args.array());
  if (!tup) {
    return false;
  }

  args.rval().setExtendedPrimitive(*tup);
  return true;
}

/*===========================================================================*\
                       BEGIN: Tuple.prototype methods
\*===========================================================================*/

static bool ArrayToTuple(JSContext* cx, const CallArgs& args) {
  Rooted<ArrayObject*> aObj(cx, &args.rval().toObject().as<ArrayObject>());
  TupleType* tup = TupleType::createUnchecked(cx, aObj);

  if (!tup) {
    return false;
  }

  args.rval().setExtendedPrimitive(*tup);
  return true;
}

// Takes an array as a single argument and returns a tuple of the
// array elements. This method copies the array, because the callee
// may still hold a pointer to it and it would break garbage collection
// to change the type of the object from ArrayObject to TupleType (which
// is the only way to re-use the same object if it has fixed elements.)
// Should only be called from self-hosted tuple methods;
// assumes all elements are non-objects and the array is packed
bool js::tuple_construct(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  MOZ_ASSERT(args[0].toObject().is<ArrayObject>());

  args.rval().set(args[0]);
  return ArrayToTuple(cx, args);
}

bool js::tuple_is_tuple(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);
  return IsTupleUnchecked(cx, args);
}

TupleType* TupleType::createUnchecked(JSContext* cx,
                                      Handle<ArrayObject*> aObj) {
  size_t len = aObj->getDenseInitializedLength();
  MOZ_ASSERT(aObj->getElementsHeader()->numShiftedElements() == 0);
  TupleType* tup = createUninitialized(cx, len);
  if (!tup) {
    return nullptr;
  }
  tup->initDenseElements(aObj, 0, len);
  tup->finishInitialization(cx);
  return tup;
}

bool js::tuple_of(JSContext* cx, unsigned argc, Value* vp) {
  /* Step 1 */
  CallArgs args = CallArgsFromVp(argc, vp);
  size_t len = args.length();
  Value* items = args.array();

  /* Step 2 */
  for (size_t i = 0; i < len; i++) {
    if (items[i].isObject()) {
      JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                JSMSG_RECORD_TUPLE_NO_OBJECT, "Tuple.of");
      return false;
    }
  }
  /* Step 3 */
  ArrayObject* result = js::NewDenseCopiedArray(cx, len, items, GenericObject);
  if (!result) {
    return false;
  }
  args.rval().setObject(*result);
  /* Step 4 */
  return ArrayToTuple(cx, args);
}

bool js::IsTuple(const Value& v) {
  if (v.isExtendedPrimitive()) return v.toExtendedPrimitive().is<TupleType>();
  if (v.isObject()) return v.toObject().is<TupleObject>();
  return false;
}

// Caller is responsible for rooting the result
TupleType& TupleType::thisTupleValue(const Value& val) {
  MOZ_ASSERT(IsTuple(val));
  return (val.isExtendedPrimitive() ? val.toExtendedPrimitive().as<TupleType>()
                                    : val.toObject().as<TupleObject>().unbox());
}

bool HandleIsTuple(HandleValue v) { return IsTuple(v.get()); }

// 8.2.3.2 get Tuple.prototype.length
bool lengthAccessor_impl(JSContext* cx, const CallArgs& args) {
  // Step 1.
  TupleType& tuple = TupleType::thisTupleValue(args.thisv().get());
  // Step 2.
  args.rval().setInt32(tuple.length());
  return true;
}

bool TupleType::lengthAccessor(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);
  return CallNonGenericMethod<HandleIsTuple, lengthAccessor_impl>(cx, args);
}

/*===========================================================================*\
                         END: Tuple.prototype methods
\*===========================================================================*/

const JSClass TupleType::class_ = {"tuple", 0, JS_NULL_CLASS_OPS,
                                   &TupleType::classSpec_};

const JSClass TupleType::protoClass_ = {
    "Tuple.prototype", JSCLASS_HAS_CACHED_PROTO(JSProto_Tuple),
    JS_NULL_CLASS_OPS, &TupleType::classSpec_};

/* static */ const JSPropertySpec properties_[] = {
    JS_STRING_SYM_PS(toStringTag, "Tuple", JSPROP_READONLY),
    JS_PSG("length", TupleType::lengthAccessor, 0), JS_PS_END};

const ClassSpec TupleType::classSpec_ = {
    GenericCreateConstructor<TupleConstructor, 0, gc::AllocKind::FUNCTION>,
    GenericCreatePrototype<TupleType>,
    tuple_static_methods,
    nullptr,
    tuple_methods,
    properties_,
    nullptr};