blob: c1f14adb277cd18a8e03024aab47246e8d34a824 [file] [log] [blame]
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001// Copyright 2014 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00005#include "src/runtime/runtime-utils.h"
Emily Bernierd0a1eb72015-03-24 16:35:39 -04006
7#include "src/arguments.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00008#include "src/regexp/jsregexp-inl.h"
Emily Bernierd0a1eb72015-03-24 16:35:39 -04009#include "src/string-builder.h"
10#include "src/string-search.h"
11
12namespace v8 {
13namespace internal {
14
15
16// Perform string match of pattern on subject, starting at start index.
17// Caller must ensure that 0 <= start_index <= sub->length(),
18// and should check that pat->length() + start_index <= sub->length().
19int StringMatch(Isolate* isolate, Handle<String> sub, Handle<String> pat,
20 int start_index) {
21 DCHECK(0 <= start_index);
22 DCHECK(start_index <= sub->length());
23
24 int pattern_length = pat->length();
25 if (pattern_length == 0) return start_index;
26
27 int subject_length = sub->length();
28 if (start_index + pattern_length > subject_length) return -1;
29
30 sub = String::Flatten(sub);
31 pat = String::Flatten(pat);
32
33 DisallowHeapAllocation no_gc; // ensure vectors stay valid
34 // Extract flattened substrings of cons strings before getting encoding.
35 String::FlatContent seq_sub = sub->GetFlatContent();
36 String::FlatContent seq_pat = pat->GetFlatContent();
37
38 // dispatch on type of strings
39 if (seq_pat.IsOneByte()) {
40 Vector<const uint8_t> pat_vector = seq_pat.ToOneByteVector();
41 if (seq_sub.IsOneByte()) {
42 return SearchString(isolate, seq_sub.ToOneByteVector(), pat_vector,
43 start_index);
44 }
45 return SearchString(isolate, seq_sub.ToUC16Vector(), pat_vector,
46 start_index);
47 }
48 Vector<const uc16> pat_vector = seq_pat.ToUC16Vector();
49 if (seq_sub.IsOneByte()) {
50 return SearchString(isolate, seq_sub.ToOneByteVector(), pat_vector,
51 start_index);
52 }
53 return SearchString(isolate, seq_sub.ToUC16Vector(), pat_vector, start_index);
54}
55
56
57// This may return an empty MaybeHandle if an exception is thrown or
58// we abort due to reaching the recursion limit.
59MaybeHandle<String> StringReplaceOneCharWithString(
60 Isolate* isolate, Handle<String> subject, Handle<String> search,
61 Handle<String> replace, bool* found, int recursion_limit) {
62 StackLimitCheck stackLimitCheck(isolate);
63 if (stackLimitCheck.HasOverflowed() || (recursion_limit == 0)) {
64 return MaybeHandle<String>();
65 }
66 recursion_limit--;
67 if (subject->IsConsString()) {
68 ConsString* cons = ConsString::cast(*subject);
69 Handle<String> first = Handle<String>(cons->first());
70 Handle<String> second = Handle<String>(cons->second());
71 Handle<String> new_first;
72 if (!StringReplaceOneCharWithString(isolate, first, search, replace, found,
73 recursion_limit).ToHandle(&new_first)) {
74 return MaybeHandle<String>();
75 }
76 if (*found) return isolate->factory()->NewConsString(new_first, second);
77
78 Handle<String> new_second;
79 if (!StringReplaceOneCharWithString(isolate, second, search, replace, found,
80 recursion_limit)
81 .ToHandle(&new_second)) {
82 return MaybeHandle<String>();
83 }
84 if (*found) return isolate->factory()->NewConsString(first, new_second);
85
86 return subject;
87 } else {
88 int index = StringMatch(isolate, subject, search, 0);
89 if (index == -1) return subject;
90 *found = true;
91 Handle<String> first = isolate->factory()->NewSubString(subject, 0, index);
92 Handle<String> cons1;
93 ASSIGN_RETURN_ON_EXCEPTION(
94 isolate, cons1, isolate->factory()->NewConsString(first, replace),
95 String);
96 Handle<String> second =
97 isolate->factory()->NewSubString(subject, index + 1, subject->length());
98 return isolate->factory()->NewConsString(cons1, second);
99 }
100}
101
102
103RUNTIME_FUNCTION(Runtime_StringReplaceOneCharWithString) {
104 HandleScope scope(isolate);
105 DCHECK(args.length() == 3);
106 CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
107 CONVERT_ARG_HANDLE_CHECKED(String, search, 1);
108 CONVERT_ARG_HANDLE_CHECKED(String, replace, 2);
109
110 // If the cons string tree is too deep, we simply abort the recursion and
111 // retry with a flattened subject string.
112 const int kRecursionLimit = 0x1000;
113 bool found = false;
114 Handle<String> result;
115 if (StringReplaceOneCharWithString(isolate, subject, search, replace, &found,
116 kRecursionLimit).ToHandle(&result)) {
117 return *result;
118 }
119 if (isolate->has_pending_exception()) return isolate->heap()->exception();
120
121 subject = String::Flatten(subject);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000122 if (StringReplaceOneCharWithString(isolate, subject, search, replace, &found,
123 kRecursionLimit).ToHandle(&result)) {
124 return *result;
125 }
126 if (isolate->has_pending_exception()) return isolate->heap()->exception();
127 // In case of empty handle and no pending exception we have stack overflow.
128 return isolate->StackOverflow();
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400129}
130
131
132RUNTIME_FUNCTION(Runtime_StringIndexOf) {
133 HandleScope scope(isolate);
134 DCHECK(args.length() == 3);
135
136 CONVERT_ARG_HANDLE_CHECKED(String, sub, 0);
137 CONVERT_ARG_HANDLE_CHECKED(String, pat, 1);
138 CONVERT_ARG_HANDLE_CHECKED(Object, index, 2);
139
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000140 uint32_t start_index = 0;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400141 if (!index->ToArrayIndex(&start_index)) return Smi::FromInt(-1);
142
Ben Murdoch61f157c2016-09-16 13:49:30 +0100143 CHECK(start_index <= static_cast<uint32_t>(sub->length()));
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400144 int position = StringMatch(isolate, sub, pat, start_index);
145 return Smi::FromInt(position);
146}
147
148
149template <typename schar, typename pchar>
150static int StringMatchBackwards(Vector<const schar> subject,
151 Vector<const pchar> pattern, int idx) {
152 int pattern_length = pattern.length();
153 DCHECK(pattern_length >= 1);
154 DCHECK(idx + pattern_length <= subject.length());
155
156 if (sizeof(schar) == 1 && sizeof(pchar) > 1) {
157 for (int i = 0; i < pattern_length; i++) {
158 uc16 c = pattern[i];
159 if (c > String::kMaxOneByteCharCode) {
160 return -1;
161 }
162 }
163 }
164
165 pchar pattern_first_char = pattern[0];
166 for (int i = idx; i >= 0; i--) {
167 if (subject[i] != pattern_first_char) continue;
168 int j = 1;
169 while (j < pattern_length) {
170 if (pattern[j] != subject[i + j]) {
171 break;
172 }
173 j++;
174 }
175 if (j == pattern_length) {
176 return i;
177 }
178 }
179 return -1;
180}
181
182
183RUNTIME_FUNCTION(Runtime_StringLastIndexOf) {
184 HandleScope scope(isolate);
185 DCHECK(args.length() == 3);
186
187 CONVERT_ARG_HANDLE_CHECKED(String, sub, 0);
188 CONVERT_ARG_HANDLE_CHECKED(String, pat, 1);
189 CONVERT_ARG_HANDLE_CHECKED(Object, index, 2);
190
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000191 uint32_t start_index = 0;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400192 if (!index->ToArrayIndex(&start_index)) return Smi::FromInt(-1);
193
194 uint32_t pat_length = pat->length();
195 uint32_t sub_length = sub->length();
196
197 if (start_index + pat_length > sub_length) {
198 start_index = sub_length - pat_length;
199 }
200
201 if (pat_length == 0) {
202 return Smi::FromInt(start_index);
203 }
204
205 sub = String::Flatten(sub);
206 pat = String::Flatten(pat);
207
208 int position = -1;
209 DisallowHeapAllocation no_gc; // ensure vectors stay valid
210
211 String::FlatContent sub_content = sub->GetFlatContent();
212 String::FlatContent pat_content = pat->GetFlatContent();
213
214 if (pat_content.IsOneByte()) {
215 Vector<const uint8_t> pat_vector = pat_content.ToOneByteVector();
216 if (sub_content.IsOneByte()) {
217 position = StringMatchBackwards(sub_content.ToOneByteVector(), pat_vector,
218 start_index);
219 } else {
220 position = StringMatchBackwards(sub_content.ToUC16Vector(), pat_vector,
221 start_index);
222 }
223 } else {
224 Vector<const uc16> pat_vector = pat_content.ToUC16Vector();
225 if (sub_content.IsOneByte()) {
226 position = StringMatchBackwards(sub_content.ToOneByteVector(), pat_vector,
227 start_index);
228 } else {
229 position = StringMatchBackwards(sub_content.ToUC16Vector(), pat_vector,
230 start_index);
231 }
232 }
233
234 return Smi::FromInt(position);
235}
236
237
238RUNTIME_FUNCTION(Runtime_StringLocaleCompare) {
239 HandleScope handle_scope(isolate);
240 DCHECK(args.length() == 2);
241
242 CONVERT_ARG_HANDLE_CHECKED(String, str1, 0);
243 CONVERT_ARG_HANDLE_CHECKED(String, str2, 1);
244
245 if (str1.is_identical_to(str2)) return Smi::FromInt(0); // Equal.
246 int str1_length = str1->length();
247 int str2_length = str2->length();
248
249 // Decide trivial cases without flattening.
250 if (str1_length == 0) {
251 if (str2_length == 0) return Smi::FromInt(0); // Equal.
252 return Smi::FromInt(-str2_length);
253 } else {
254 if (str2_length == 0) return Smi::FromInt(str1_length);
255 }
256
257 int end = str1_length < str2_length ? str1_length : str2_length;
258
259 // No need to flatten if we are going to find the answer on the first
260 // character. At this point we know there is at least one character
261 // in each string, due to the trivial case handling above.
262 int d = str1->Get(0) - str2->Get(0);
263 if (d != 0) return Smi::FromInt(d);
264
265 str1 = String::Flatten(str1);
266 str2 = String::Flatten(str2);
267
268 DisallowHeapAllocation no_gc;
269 String::FlatContent flat1 = str1->GetFlatContent();
270 String::FlatContent flat2 = str2->GetFlatContent();
271
272 for (int i = 0; i < end; i++) {
273 if (flat1.Get(i) != flat2.Get(i)) {
274 return Smi::FromInt(flat1.Get(i) - flat2.Get(i));
275 }
276 }
277
278 return Smi::FromInt(str1_length - str2_length);
279}
280
281
282RUNTIME_FUNCTION(Runtime_SubString) {
283 HandleScope scope(isolate);
284 DCHECK(args.length() == 3);
285
286 CONVERT_ARG_HANDLE_CHECKED(String, string, 0);
287 int start, end;
288 // We have a fast integer-only case here to avoid a conversion to double in
289 // the common case where from and to are Smis.
290 if (args[1]->IsSmi() && args[2]->IsSmi()) {
291 CONVERT_SMI_ARG_CHECKED(from_number, 1);
292 CONVERT_SMI_ARG_CHECKED(to_number, 2);
293 start = from_number;
294 end = to_number;
295 } else {
296 CONVERT_DOUBLE_ARG_CHECKED(from_number, 1);
297 CONVERT_DOUBLE_ARG_CHECKED(to_number, 2);
298 start = FastD2IChecked(from_number);
299 end = FastD2IChecked(to_number);
300 }
301 RUNTIME_ASSERT(end >= start);
302 RUNTIME_ASSERT(start >= 0);
303 RUNTIME_ASSERT(end <= string->length());
304 isolate->counters()->sub_string_runtime()->Increment();
305
306 return *isolate->factory()->NewSubString(string, start, end);
307}
308
309
310RUNTIME_FUNCTION(Runtime_StringAdd) {
311 HandleScope scope(isolate);
312 DCHECK(args.length() == 2);
313 CONVERT_ARG_HANDLE_CHECKED(String, str1, 0);
314 CONVERT_ARG_HANDLE_CHECKED(String, str2, 1);
315 isolate->counters()->string_add_runtime()->Increment();
Ben Murdoch61f157c2016-09-16 13:49:30 +0100316 RETURN_RESULT_OR_FAILURE(isolate,
317 isolate->factory()->NewConsString(str1, str2));
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400318}
319
320
321RUNTIME_FUNCTION(Runtime_InternalizeString) {
322 HandleScope handles(isolate);
Ben Murdoch61f157c2016-09-16 13:49:30 +0100323 DCHECK(args.length() == 1);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400324 CONVERT_ARG_HANDLE_CHECKED(String, string, 0);
325 return *isolate->factory()->InternalizeString(string);
326}
327
328
329RUNTIME_FUNCTION(Runtime_StringMatch) {
330 HandleScope handles(isolate);
331 DCHECK(args.length() == 3);
332
333 CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
334 CONVERT_ARG_HANDLE_CHECKED(JSRegExp, regexp, 1);
335 CONVERT_ARG_HANDLE_CHECKED(JSArray, regexp_info, 2);
336
Ben Murdoch61f157c2016-09-16 13:49:30 +0100337 CHECK(regexp_info->HasFastObjectElements());
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400338
Ben Murdoch097c5b22016-05-18 11:27:45 +0100339 RegExpImpl::GlobalCache global_cache(regexp, subject, isolate);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400340 if (global_cache.HasException()) return isolate->heap()->exception();
341
342 int capture_count = regexp->CaptureCount();
343
344 ZoneScope zone_scope(isolate->runtime_zone());
345 ZoneList<int> offsets(8, zone_scope.zone());
346
347 while (true) {
348 int32_t* match = global_cache.FetchNext();
349 if (match == NULL) break;
350 offsets.Add(match[0], zone_scope.zone()); // start
351 offsets.Add(match[1], zone_scope.zone()); // end
352 }
353
354 if (global_cache.HasException()) return isolate->heap()->exception();
355
356 if (offsets.length() == 0) {
357 // Not a single match.
358 return isolate->heap()->null_value();
359 }
360
361 RegExpImpl::SetLastMatchInfo(regexp_info, subject, capture_count,
362 global_cache.LastSuccessfulMatch());
363
364 int matches = offsets.length() / 2;
365 Handle<FixedArray> elements = isolate->factory()->NewFixedArray(matches);
366 Handle<String> substring =
367 isolate->factory()->NewSubString(subject, offsets.at(0), offsets.at(1));
368 elements->set(0, *substring);
Ben Murdochda12d292016-06-02 14:46:10 +0100369 FOR_WITH_HANDLE_SCOPE(isolate, int, i = 1, i, i < matches, i++, {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400370 int from = offsets.at(i * 2);
371 int to = offsets.at(i * 2 + 1);
372 Handle<String> substring =
373 isolate->factory()->NewProperSubString(subject, from, to);
374 elements->set(i, *substring);
Ben Murdochda12d292016-06-02 14:46:10 +0100375 });
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400376 Handle<JSArray> result = isolate->factory()->NewJSArrayWithElements(elements);
377 result->set_length(Smi::FromInt(matches));
378 return *result;
379}
380
381
382RUNTIME_FUNCTION(Runtime_StringCharCodeAtRT) {
383 HandleScope handle_scope(isolate);
384 DCHECK(args.length() == 2);
385
386 CONVERT_ARG_HANDLE_CHECKED(String, subject, 0);
387 CONVERT_NUMBER_CHECKED(uint32_t, i, Uint32, args[1]);
388
389 // Flatten the string. If someone wants to get a char at an index
390 // in a cons string, it is likely that more indices will be
391 // accessed.
392 subject = String::Flatten(subject);
393
394 if (i >= static_cast<uint32_t>(subject->length())) {
395 return isolate->heap()->nan_value();
396 }
397
398 return Smi::FromInt(subject->Get(i));
399}
400
401
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400402RUNTIME_FUNCTION(Runtime_StringCompare) {
403 HandleScope handle_scope(isolate);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000404 DCHECK_EQ(2, args.length());
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400405 CONVERT_ARG_HANDLE_CHECKED(String, x, 0);
406 CONVERT_ARG_HANDLE_CHECKED(String, y, 1);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400407 isolate->counters()->string_compare_runtime()->Increment();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000408 switch (String::Compare(x, y)) {
409 case ComparisonResult::kLessThan:
410 return Smi::FromInt(LESS);
411 case ComparisonResult::kEqual:
412 return Smi::FromInt(EQUAL);
413 case ComparisonResult::kGreaterThan:
414 return Smi::FromInt(GREATER);
415 case ComparisonResult::kUndefined:
416 break;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400417 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000418 UNREACHABLE();
419 return Smi::FromInt(0);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400420}
421
422
423RUNTIME_FUNCTION(Runtime_StringBuilderConcat) {
424 HandleScope scope(isolate);
425 DCHECK(args.length() == 3);
426 CONVERT_ARG_HANDLE_CHECKED(JSArray, array, 0);
427 int32_t array_length;
428 if (!args[1]->ToInt32(&array_length)) {
429 THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewInvalidStringLengthError());
430 }
431 CONVERT_ARG_HANDLE_CHECKED(String, special, 2);
432
433 size_t actual_array_length = 0;
Ben Murdoch61f157c2016-09-16 13:49:30 +0100434 CHECK(TryNumberToSize(isolate, array->length(), &actual_array_length));
435 CHECK(array_length >= 0);
436 CHECK(static_cast<size_t>(array_length) <= actual_array_length);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400437
438 // This assumption is used by the slice encoding in one or two smis.
439 DCHECK(Smi::kMaxValue >= String::kMaxLength);
440
Ben Murdoch61f157c2016-09-16 13:49:30 +0100441 CHECK(array->HasFastElements());
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400442 JSObject::EnsureCanContainHeapObjectElements(array);
443
444 int special_length = special->length();
445 if (!array->HasFastObjectElements()) {
446 return isolate->Throw(isolate->heap()->illegal_argument_string());
447 }
448
449 int length;
450 bool one_byte = special->HasOnlyOneByteChars();
451
452 {
453 DisallowHeapAllocation no_gc;
454 FixedArray* fixed_array = FixedArray::cast(array->elements());
455 if (fixed_array->length() < array_length) {
456 array_length = fixed_array->length();
457 }
458
459 if (array_length == 0) {
460 return isolate->heap()->empty_string();
461 } else if (array_length == 1) {
462 Object* first = fixed_array->get(0);
463 if (first->IsString()) return first;
464 }
465 length = StringBuilderConcatLength(special_length, fixed_array,
466 array_length, &one_byte);
467 }
468
469 if (length == -1) {
470 return isolate->Throw(isolate->heap()->illegal_argument_string());
471 }
472
473 if (one_byte) {
474 Handle<SeqOneByteString> answer;
475 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
476 isolate, answer, isolate->factory()->NewRawOneByteString(length));
477 StringBuilderConcatHelper(*special, answer->GetChars(),
478 FixedArray::cast(array->elements()),
479 array_length);
480 return *answer;
481 } else {
482 Handle<SeqTwoByteString> answer;
483 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
484 isolate, answer, isolate->factory()->NewRawTwoByteString(length));
485 StringBuilderConcatHelper(*special, answer->GetChars(),
486 FixedArray::cast(array->elements()),
487 array_length);
488 return *answer;
489 }
490}
491
492
493RUNTIME_FUNCTION(Runtime_StringBuilderJoin) {
494 HandleScope scope(isolate);
495 DCHECK(args.length() == 3);
496 CONVERT_ARG_HANDLE_CHECKED(JSArray, array, 0);
497 int32_t array_length;
498 if (!args[1]->ToInt32(&array_length)) {
499 THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewInvalidStringLengthError());
500 }
501 CONVERT_ARG_HANDLE_CHECKED(String, separator, 2);
Ben Murdoch61f157c2016-09-16 13:49:30 +0100502 CHECK(array->HasFastObjectElements());
503 CHECK(array_length >= 0);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400504
505 Handle<FixedArray> fixed_array(FixedArray::cast(array->elements()));
506 if (fixed_array->length() < array_length) {
507 array_length = fixed_array->length();
508 }
509
510 if (array_length == 0) {
511 return isolate->heap()->empty_string();
512 } else if (array_length == 1) {
513 Object* first = fixed_array->get(0);
Ben Murdoch61f157c2016-09-16 13:49:30 +0100514 CHECK(first->IsString());
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400515 return first;
516 }
517
518 int separator_length = separator->length();
Ben Murdoch61f157c2016-09-16 13:49:30 +0100519 CHECK(separator_length > 0);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400520 int max_nof_separators =
521 (String::kMaxLength + separator_length - 1) / separator_length;
522 if (max_nof_separators < (array_length - 1)) {
523 THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewInvalidStringLengthError());
524 }
525 int length = (array_length - 1) * separator_length;
526 for (int i = 0; i < array_length; i++) {
527 Object* element_obj = fixed_array->get(i);
Ben Murdoch61f157c2016-09-16 13:49:30 +0100528 CHECK(element_obj->IsString());
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400529 String* element = String::cast(element_obj);
530 int increment = element->length();
531 if (increment > String::kMaxLength - length) {
532 STATIC_ASSERT(String::kMaxLength < kMaxInt);
533 length = kMaxInt; // Provoke exception;
534 break;
535 }
536 length += increment;
537 }
538
539 Handle<SeqTwoByteString> answer;
540 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
541 isolate, answer, isolate->factory()->NewRawTwoByteString(length));
542
543 DisallowHeapAllocation no_gc;
544
545 uc16* sink = answer->GetChars();
546#ifdef DEBUG
547 uc16* end = sink + length;
548#endif
549
Ben Murdoch61f157c2016-09-16 13:49:30 +0100550 CHECK(fixed_array->get(0)->IsString());
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400551 String* first = String::cast(fixed_array->get(0));
552 String* separator_raw = *separator;
Ben Murdochda12d292016-06-02 14:46:10 +0100553
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400554 int first_length = first->length();
555 String::WriteToFlat(first, sink, 0, first_length);
556 sink += first_length;
557
558 for (int i = 1; i < array_length; i++) {
559 DCHECK(sink + separator_length <= end);
560 String::WriteToFlat(separator_raw, sink, 0, separator_length);
561 sink += separator_length;
562
Ben Murdoch61f157c2016-09-16 13:49:30 +0100563 CHECK(fixed_array->get(i)->IsString());
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400564 String* element = String::cast(fixed_array->get(i));
565 int element_length = element->length();
566 DCHECK(sink + element_length <= end);
567 String::WriteToFlat(element, sink, 0, element_length);
568 sink += element_length;
569 }
570 DCHECK(sink == end);
571
572 // Use %_FastOneByteArrayJoin instead.
573 DCHECK(!answer->IsOneByteRepresentation());
574 return *answer;
575}
576
Ben Murdochda12d292016-06-02 14:46:10 +0100577template <typename sinkchar>
578static void WriteRepeatToFlat(String* src, Vector<sinkchar> buffer, int cursor,
579 int repeat, int length) {
580 if (repeat == 0) return;
581
582 sinkchar* start = &buffer[cursor];
583 String::WriteToFlat<sinkchar>(src, start, 0, length);
584
585 int done = 1;
586 sinkchar* next = start + length;
587
588 while (done < repeat) {
589 int block = Min(done, repeat - done);
590 int block_chars = block * length;
591 CopyChars(next, start, block_chars);
592 next += block_chars;
593 done += block;
594 }
595}
596
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400597template <typename Char>
598static void JoinSparseArrayWithSeparator(FixedArray* elements,
599 int elements_length,
600 uint32_t array_length,
601 String* separator,
602 Vector<Char> buffer) {
603 DisallowHeapAllocation no_gc;
604 int previous_separator_position = 0;
605 int separator_length = separator->length();
Ben Murdochda12d292016-06-02 14:46:10 +0100606 DCHECK_LT(0, separator_length);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400607 int cursor = 0;
608 for (int i = 0; i < elements_length; i += 2) {
609 int position = NumberToInt32(elements->get(i));
610 String* string = String::cast(elements->get(i + 1));
611 int string_length = string->length();
612 if (string->length() > 0) {
Ben Murdochda12d292016-06-02 14:46:10 +0100613 int repeat = position - previous_separator_position;
614 WriteRepeatToFlat<Char>(separator, buffer, cursor, repeat,
615 separator_length);
616 cursor += repeat * separator_length;
617 previous_separator_position = position;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400618 String::WriteToFlat<Char>(string, &buffer[cursor], 0, string_length);
619 cursor += string->length();
620 }
621 }
Ben Murdochda12d292016-06-02 14:46:10 +0100622
623 int last_array_index = static_cast<int>(array_length - 1);
624 // Array length must be representable as a signed 32-bit number,
625 // otherwise the total string length would have been too large.
626 DCHECK(array_length <= 0x7fffffff); // Is int32_t.
627 int repeat = last_array_index - previous_separator_position;
628 WriteRepeatToFlat<Char>(separator, buffer, cursor, repeat, separator_length);
629 cursor += repeat * separator_length;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400630 DCHECK(cursor <= buffer.length());
631}
632
633
634RUNTIME_FUNCTION(Runtime_SparseJoinWithSeparator) {
635 HandleScope scope(isolate);
636 DCHECK(args.length() == 3);
637 CONVERT_ARG_HANDLE_CHECKED(JSArray, elements_array, 0);
638 CONVERT_NUMBER_CHECKED(uint32_t, array_length, Uint32, args[1]);
639 CONVERT_ARG_HANDLE_CHECKED(String, separator, 2);
640 // elements_array is fast-mode JSarray of alternating positions
641 // (increasing order) and strings.
Ben Murdoch61f157c2016-09-16 13:49:30 +0100642 CHECK(elements_array->HasFastSmiOrObjectElements());
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400643 // array_length is length of original array (used to add separators);
644 // separator is string to put between elements. Assumed to be non-empty.
Ben Murdoch61f157c2016-09-16 13:49:30 +0100645 CHECK(array_length > 0);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400646
647 // Find total length of join result.
648 int string_length = 0;
649 bool is_one_byte = separator->IsOneByteRepresentation();
650 bool overflow = false;
651 CONVERT_NUMBER_CHECKED(int, elements_length, Int32, elements_array->length());
Ben Murdoch61f157c2016-09-16 13:49:30 +0100652 CHECK(elements_length <= elements_array->elements()->length());
653 CHECK((elements_length & 1) == 0); // Even length.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400654 FixedArray* elements = FixedArray::cast(elements_array->elements());
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400655 {
656 DisallowHeapAllocation no_gc;
657 for (int i = 0; i < elements_length; i += 2) {
658 String* string = String::cast(elements->get(i + 1));
659 int length = string->length();
660 if (is_one_byte && !string->IsOneByteRepresentation()) {
661 is_one_byte = false;
662 }
663 if (length > String::kMaxLength ||
664 String::kMaxLength - length < string_length) {
665 overflow = true;
666 break;
667 }
668 string_length += length;
669 }
670 }
671
672 int separator_length = separator->length();
673 if (!overflow && separator_length > 0) {
674 if (array_length <= 0x7fffffffu) {
675 int separator_count = static_cast<int>(array_length) - 1;
676 int remaining_length = String::kMaxLength - string_length;
677 if ((remaining_length / separator_length) >= separator_count) {
678 string_length += separator_length * (array_length - 1);
679 } else {
680 // Not room for the separators within the maximal string length.
681 overflow = true;
682 }
683 } else {
684 // Nonempty separator and at least 2^31-1 separators necessary
685 // means that the string is too large to create.
686 STATIC_ASSERT(String::kMaxLength < 0x7fffffff);
687 overflow = true;
688 }
689 }
690 if (overflow) {
691 // Throw an exception if the resulting string is too large. See
692 // https://code.google.com/p/chromium/issues/detail?id=336820
693 // for details.
694 THROW_NEW_ERROR_RETURN_FAILURE(isolate, NewInvalidStringLengthError());
695 }
696
697 if (is_one_byte) {
698 Handle<SeqOneByteString> result = isolate->factory()
699 ->NewRawOneByteString(string_length)
700 .ToHandleChecked();
701 JoinSparseArrayWithSeparator<uint8_t>(
702 FixedArray::cast(elements_array->elements()), elements_length,
703 array_length, *separator,
704 Vector<uint8_t>(result->GetChars(), string_length));
705 return *result;
706 } else {
707 Handle<SeqTwoByteString> result = isolate->factory()
708 ->NewRawTwoByteString(string_length)
709 .ToHandleChecked();
710 JoinSparseArrayWithSeparator<uc16>(
711 FixedArray::cast(elements_array->elements()), elements_length,
712 array_length, *separator,
713 Vector<uc16>(result->GetChars(), string_length));
714 return *result;
715 }
716}
717
718
719// Copies Latin1 characters to the given fixed array looking up
720// one-char strings in the cache. Gives up on the first char that is
721// not in the cache and fills the remainder with smi zeros. Returns
722// the length of the successfully copied prefix.
723static int CopyCachedOneByteCharsToArray(Heap* heap, const uint8_t* chars,
724 FixedArray* elements, int length) {
725 DisallowHeapAllocation no_gc;
726 FixedArray* one_byte_cache = heap->single_character_string_cache();
727 Object* undefined = heap->undefined_value();
728 int i;
729 WriteBarrierMode mode = elements->GetWriteBarrierMode(no_gc);
730 for (i = 0; i < length; ++i) {
731 Object* value = one_byte_cache->get(chars[i]);
732 if (value == undefined) break;
733 elements->set(i, value, mode);
734 }
735 if (i < length) {
736 DCHECK(Smi::FromInt(0) == 0);
737 memset(elements->data_start() + i, 0, kPointerSize * (length - i));
738 }
739#ifdef DEBUG
740 for (int j = 0; j < length; ++j) {
741 Object* element = elements->get(j);
742 DCHECK(element == Smi::FromInt(0) ||
743 (element->IsString() && String::cast(element)->LooksValid()));
744 }
745#endif
746 return i;
747}
748
749
750// Converts a String to JSArray.
751// For example, "foo" => ["f", "o", "o"].
752RUNTIME_FUNCTION(Runtime_StringToArray) {
753 HandleScope scope(isolate);
754 DCHECK(args.length() == 2);
755 CONVERT_ARG_HANDLE_CHECKED(String, s, 0);
756 CONVERT_NUMBER_CHECKED(uint32_t, limit, Uint32, args[1]);
757
758 s = String::Flatten(s);
759 const int length = static_cast<int>(Min<uint32_t>(s->length(), limit));
760
761 Handle<FixedArray> elements;
762 int position = 0;
763 if (s->IsFlat() && s->IsOneByteRepresentation()) {
764 // Try using cached chars where possible.
765 elements = isolate->factory()->NewUninitializedFixedArray(length);
766
767 DisallowHeapAllocation no_gc;
768 String::FlatContent content = s->GetFlatContent();
769 if (content.IsOneByte()) {
770 Vector<const uint8_t> chars = content.ToOneByteVector();
771 // Note, this will initialize all elements (not only the prefix)
772 // to prevent GC from seeing partially initialized array.
773 position = CopyCachedOneByteCharsToArray(isolate->heap(), chars.start(),
774 *elements, length);
775 } else {
776 MemsetPointer(elements->data_start(), isolate->heap()->undefined_value(),
777 length);
778 }
779 } else {
780 elements = isolate->factory()->NewFixedArray(length);
781 }
782 for (int i = position; i < length; ++i) {
783 Handle<Object> str =
784 isolate->factory()->LookupSingleCharacterStringFromCode(s->Get(i));
785 elements->set(i, *str);
786 }
787
788#ifdef DEBUG
789 for (int i = 0; i < length; ++i) {
790 DCHECK(String::cast(elements->get(i))->length() == 1);
791 }
792#endif
793
794 return *isolate->factory()->NewJSArrayWithElements(elements);
795}
796
797
798static inline bool ToUpperOverflows(uc32 character) {
799 // y with umlauts and the micro sign are the only characters that stop
800 // fitting into one-byte when converting to uppercase.
801 static const uc32 yuml_code = 0xff;
802 static const uc32 micro_code = 0xb5;
803 return (character == yuml_code || character == micro_code);
804}
805
806
807template <class Converter>
808MUST_USE_RESULT static Object* ConvertCaseHelper(
809 Isolate* isolate, String* string, SeqString* result, int result_length,
810 unibrow::Mapping<Converter, 128>* mapping) {
811 DisallowHeapAllocation no_gc;
812 // We try this twice, once with the assumption that the result is no longer
813 // than the input and, if that assumption breaks, again with the exact
814 // length. This may not be pretty, but it is nicer than what was here before
815 // and I hereby claim my vaffel-is.
816 //
817 // NOTE: This assumes that the upper/lower case of an ASCII
818 // character is also ASCII. This is currently the case, but it
819 // might break in the future if we implement more context and locale
820 // dependent upper/lower conversions.
821 bool has_changed_character = false;
822
823 // Convert all characters to upper case, assuming that they will fit
824 // in the buffer
825 StringCharacterStream stream(string);
826 unibrow::uchar chars[Converter::kMaxWidth];
827 // We can assume that the string is not empty
828 uc32 current = stream.GetNext();
829 bool ignore_overflow = Converter::kIsToLower || result->IsSeqTwoByteString();
830 for (int i = 0; i < result_length;) {
831 bool has_next = stream.HasMore();
832 uc32 next = has_next ? stream.GetNext() : 0;
833 int char_length = mapping->get(current, next, chars);
834 if (char_length == 0) {
835 // The case conversion of this character is the character itself.
836 result->Set(i, current);
837 i++;
838 } else if (char_length == 1 &&
839 (ignore_overflow || !ToUpperOverflows(current))) {
840 // Common case: converting the letter resulted in one character.
841 DCHECK(static_cast<uc32>(chars[0]) != current);
842 result->Set(i, chars[0]);
843 has_changed_character = true;
844 i++;
845 } else if (result_length == string->length()) {
846 bool overflows = ToUpperOverflows(current);
847 // We've assumed that the result would be as long as the
848 // input but here is a character that converts to several
849 // characters. No matter, we calculate the exact length
850 // of the result and try the whole thing again.
851 //
852 // Note that this leaves room for optimization. We could just
853 // memcpy what we already have to the result string. Also,
854 // the result string is the last object allocated we could
855 // "realloc" it and probably, in the vast majority of cases,
856 // extend the existing string to be able to hold the full
857 // result.
858 int next_length = 0;
859 if (has_next) {
860 next_length = mapping->get(next, 0, chars);
861 if (next_length == 0) next_length = 1;
862 }
863 int current_length = i + char_length + next_length;
864 while (stream.HasMore()) {
865 current = stream.GetNext();
866 overflows |= ToUpperOverflows(current);
867 // NOTE: we use 0 as the next character here because, while
868 // the next character may affect what a character converts to,
869 // it does not in any case affect the length of what it convert
870 // to.
871 int char_length = mapping->get(current, 0, chars);
872 if (char_length == 0) char_length = 1;
873 current_length += char_length;
874 if (current_length > String::kMaxLength) {
875 AllowHeapAllocation allocate_error_and_return;
876 THROW_NEW_ERROR_RETURN_FAILURE(isolate,
877 NewInvalidStringLengthError());
878 }
879 }
880 // Try again with the real length. Return signed if we need
881 // to allocate a two-byte string for to uppercase.
882 return (overflows && !ignore_overflow) ? Smi::FromInt(-current_length)
883 : Smi::FromInt(current_length);
884 } else {
885 for (int j = 0; j < char_length; j++) {
886 result->Set(i, chars[j]);
887 i++;
888 }
889 has_changed_character = true;
890 }
891 current = next;
892 }
893 if (has_changed_character) {
894 return result;
895 } else {
896 // If we didn't actually change anything in doing the conversion
897 // we simple return the result and let the converted string
898 // become garbage; there is no reason to keep two identical strings
899 // alive.
900 return string;
901 }
902}
903
904
905static const uintptr_t kOneInEveryByte = kUintptrAllBitsSet / 0xFF;
906static const uintptr_t kAsciiMask = kOneInEveryByte << 7;
907
908// Given a word and two range boundaries returns a word with high bit
909// set in every byte iff the corresponding input byte was strictly in
910// the range (m, n). All the other bits in the result are cleared.
911// This function is only useful when it can be inlined and the
912// boundaries are statically known.
913// Requires: all bytes in the input word and the boundaries must be
914// ASCII (less than 0x7F).
915static inline uintptr_t AsciiRangeMask(uintptr_t w, char m, char n) {
916 // Use strict inequalities since in edge cases the function could be
917 // further simplified.
918 DCHECK(0 < m && m < n);
919 // Has high bit set in every w byte less than n.
920 uintptr_t tmp1 = kOneInEveryByte * (0x7F + n) - w;
921 // Has high bit set in every w byte greater than m.
922 uintptr_t tmp2 = w + kOneInEveryByte * (0x7F - m);
923 return (tmp1 & tmp2 & (kOneInEveryByte * 0x80));
924}
925
926
927#ifdef DEBUG
928static bool CheckFastAsciiConvert(char* dst, const char* src, int length,
929 bool changed, bool is_to_lower) {
930 bool expected_changed = false;
931 for (int i = 0; i < length; i++) {
932 if (dst[i] == src[i]) continue;
933 expected_changed = true;
934 if (is_to_lower) {
935 DCHECK('A' <= src[i] && src[i] <= 'Z');
936 DCHECK(dst[i] == src[i] + ('a' - 'A'));
937 } else {
938 DCHECK('a' <= src[i] && src[i] <= 'z');
939 DCHECK(dst[i] == src[i] - ('a' - 'A'));
940 }
941 }
942 return (expected_changed == changed);
943}
944#endif
945
946
947template <class Converter>
948static bool FastAsciiConvert(char* dst, const char* src, int length,
949 bool* changed_out) {
950#ifdef DEBUG
951 char* saved_dst = dst;
952 const char* saved_src = src;
953#endif
954 DisallowHeapAllocation no_gc;
955 // We rely on the distance between upper and lower case letters
956 // being a known power of 2.
957 DCHECK('a' - 'A' == (1 << 5));
958 // Boundaries for the range of input characters than require conversion.
959 static const char lo = Converter::kIsToLower ? 'A' - 1 : 'a' - 1;
960 static const char hi = Converter::kIsToLower ? 'Z' + 1 : 'z' + 1;
961 bool changed = false;
962 uintptr_t or_acc = 0;
963 const char* const limit = src + length;
964
965 // dst is newly allocated and always aligned.
966 DCHECK(IsAligned(reinterpret_cast<intptr_t>(dst), sizeof(uintptr_t)));
967 // Only attempt processing one word at a time if src is also aligned.
968 if (IsAligned(reinterpret_cast<intptr_t>(src), sizeof(uintptr_t))) {
969 // Process the prefix of the input that requires no conversion one aligned
970 // (machine) word at a time.
971 while (src <= limit - sizeof(uintptr_t)) {
972 const uintptr_t w = *reinterpret_cast<const uintptr_t*>(src);
973 or_acc |= w;
974 if (AsciiRangeMask(w, lo, hi) != 0) {
975 changed = true;
976 break;
977 }
978 *reinterpret_cast<uintptr_t*>(dst) = w;
979 src += sizeof(uintptr_t);
980 dst += sizeof(uintptr_t);
981 }
982 // Process the remainder of the input performing conversion when
983 // required one word at a time.
984 while (src <= limit - sizeof(uintptr_t)) {
985 const uintptr_t w = *reinterpret_cast<const uintptr_t*>(src);
986 or_acc |= w;
987 uintptr_t m = AsciiRangeMask(w, lo, hi);
988 // The mask has high (7th) bit set in every byte that needs
989 // conversion and we know that the distance between cases is
990 // 1 << 5.
991 *reinterpret_cast<uintptr_t*>(dst) = w ^ (m >> 2);
992 src += sizeof(uintptr_t);
993 dst += sizeof(uintptr_t);
994 }
995 }
996 // Process the last few bytes of the input (or the whole input if
997 // unaligned access is not supported).
998 while (src < limit) {
999 char c = *src;
1000 or_acc |= c;
1001 if (lo < c && c < hi) {
1002 c ^= (1 << 5);
1003 changed = true;
1004 }
1005 *dst = c;
1006 ++src;
1007 ++dst;
1008 }
1009
1010 if ((or_acc & kAsciiMask) != 0) return false;
1011
1012 DCHECK(CheckFastAsciiConvert(saved_dst, saved_src, length, changed,
1013 Converter::kIsToLower));
1014
1015 *changed_out = changed;
1016 return true;
1017}
1018
1019
1020template <class Converter>
1021MUST_USE_RESULT static Object* ConvertCase(
1022 Handle<String> s, Isolate* isolate,
1023 unibrow::Mapping<Converter, 128>* mapping) {
1024 s = String::Flatten(s);
1025 int length = s->length();
1026 // Assume that the string is not empty; we need this assumption later
1027 if (length == 0) return *s;
1028
1029 // Simpler handling of ASCII strings.
1030 //
1031 // NOTE: This assumes that the upper/lower case of an ASCII
1032 // character is also ASCII. This is currently the case, but it
1033 // might break in the future if we implement more context and locale
1034 // dependent upper/lower conversions.
1035 if (s->IsOneByteRepresentationUnderneath()) {
1036 // Same length as input.
1037 Handle<SeqOneByteString> result =
1038 isolate->factory()->NewRawOneByteString(length).ToHandleChecked();
1039 DisallowHeapAllocation no_gc;
1040 String::FlatContent flat_content = s->GetFlatContent();
1041 DCHECK(flat_content.IsFlat());
1042 bool has_changed_character = false;
1043 bool is_ascii = FastAsciiConvert<Converter>(
1044 reinterpret_cast<char*>(result->GetChars()),
1045 reinterpret_cast<const char*>(flat_content.ToOneByteVector().start()),
1046 length, &has_changed_character);
1047 // If not ASCII, we discard the result and take the 2 byte path.
1048 if (is_ascii) return has_changed_character ? *result : *s;
1049 }
1050
1051 Handle<SeqString> result; // Same length as input.
1052 if (s->IsOneByteRepresentation()) {
1053 result = isolate->factory()->NewRawOneByteString(length).ToHandleChecked();
1054 } else {
1055 result = isolate->factory()->NewRawTwoByteString(length).ToHandleChecked();
1056 }
1057
1058 Object* answer = ConvertCaseHelper(isolate, *s, *result, length, mapping);
Ben Murdoch61f157c2016-09-16 13:49:30 +01001059 if (answer->IsException(isolate) || answer->IsString()) return answer;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001060
1061 DCHECK(answer->IsSmi());
1062 length = Smi::cast(answer)->value();
1063 if (s->IsOneByteRepresentation() && length > 0) {
1064 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
1065 isolate, result, isolate->factory()->NewRawOneByteString(length));
1066 } else {
1067 if (length < 0) length = -length;
1068 ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
1069 isolate, result, isolate->factory()->NewRawTwoByteString(length));
1070 }
1071 return ConvertCaseHelper(isolate, *s, *result, length, mapping);
1072}
1073
1074
1075RUNTIME_FUNCTION(Runtime_StringToLowerCase) {
1076 HandleScope scope(isolate);
Ben Murdochc5610432016-08-08 18:44:38 +01001077 DCHECK_EQ(args.length(), 1);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001078 CONVERT_ARG_HANDLE_CHECKED(String, s, 0);
1079 return ConvertCase(s, isolate, isolate->runtime_state()->to_lower_mapping());
1080}
1081
1082
1083RUNTIME_FUNCTION(Runtime_StringToUpperCase) {
1084 HandleScope scope(isolate);
Ben Murdochc5610432016-08-08 18:44:38 +01001085 DCHECK_EQ(args.length(), 1);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001086 CONVERT_ARG_HANDLE_CHECKED(String, s, 0);
1087 return ConvertCase(s, isolate, isolate->runtime_state()->to_upper_mapping());
1088}
1089
Ben Murdochda12d292016-06-02 14:46:10 +01001090RUNTIME_FUNCTION(Runtime_StringLessThan) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001091 HandleScope handle_scope(isolate);
Ben Murdochda12d292016-06-02 14:46:10 +01001092 DCHECK_EQ(2, args.length());
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001093 CONVERT_ARG_HANDLE_CHECKED(String, x, 0);
1094 CONVERT_ARG_HANDLE_CHECKED(String, y, 1);
Ben Murdochda12d292016-06-02 14:46:10 +01001095 switch (String::Compare(x, y)) {
1096 case ComparisonResult::kLessThan:
1097 return isolate->heap()->true_value();
1098 case ComparisonResult::kEqual:
1099 case ComparisonResult::kGreaterThan:
1100 return isolate->heap()->false_value();
1101 case ComparisonResult::kUndefined:
1102 break;
1103 }
1104 UNREACHABLE();
1105 return Smi::FromInt(0);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001106}
1107
Ben Murdochda12d292016-06-02 14:46:10 +01001108RUNTIME_FUNCTION(Runtime_StringLessThanOrEqual) {
1109 HandleScope handle_scope(isolate);
1110 DCHECK_EQ(2, args.length());
1111 CONVERT_ARG_HANDLE_CHECKED(String, x, 0);
1112 CONVERT_ARG_HANDLE_CHECKED(String, y, 1);
1113 switch (String::Compare(x, y)) {
1114 case ComparisonResult::kEqual:
1115 case ComparisonResult::kLessThan:
1116 return isolate->heap()->true_value();
1117 case ComparisonResult::kGreaterThan:
1118 return isolate->heap()->false_value();
1119 case ComparisonResult::kUndefined:
1120 break;
1121 }
1122 UNREACHABLE();
1123 return Smi::FromInt(0);
1124}
1125
1126RUNTIME_FUNCTION(Runtime_StringGreaterThan) {
1127 HandleScope handle_scope(isolate);
1128 DCHECK_EQ(2, args.length());
1129 CONVERT_ARG_HANDLE_CHECKED(String, x, 0);
1130 CONVERT_ARG_HANDLE_CHECKED(String, y, 1);
1131 switch (String::Compare(x, y)) {
1132 case ComparisonResult::kGreaterThan:
1133 return isolate->heap()->true_value();
1134 case ComparisonResult::kEqual:
1135 case ComparisonResult::kLessThan:
1136 return isolate->heap()->false_value();
1137 case ComparisonResult::kUndefined:
1138 break;
1139 }
1140 UNREACHABLE();
1141 return Smi::FromInt(0);
1142}
1143
1144RUNTIME_FUNCTION(Runtime_StringGreaterThanOrEqual) {
1145 HandleScope handle_scope(isolate);
1146 DCHECK_EQ(2, args.length());
1147 CONVERT_ARG_HANDLE_CHECKED(String, x, 0);
1148 CONVERT_ARG_HANDLE_CHECKED(String, y, 1);
1149 switch (String::Compare(x, y)) {
1150 case ComparisonResult::kEqual:
1151 case ComparisonResult::kGreaterThan:
1152 return isolate->heap()->true_value();
1153 case ComparisonResult::kLessThan:
1154 return isolate->heap()->false_value();
1155 case ComparisonResult::kUndefined:
1156 break;
1157 }
1158 UNREACHABLE();
1159 return Smi::FromInt(0);
1160}
1161
1162RUNTIME_FUNCTION(Runtime_StringEqual) {
1163 HandleScope handle_scope(isolate);
1164 DCHECK_EQ(2, args.length());
1165 CONVERT_ARG_HANDLE_CHECKED(String, x, 0);
1166 CONVERT_ARG_HANDLE_CHECKED(String, y, 1);
1167 return isolate->heap()->ToBoolean(String::Equals(x, y));
1168}
1169
1170RUNTIME_FUNCTION(Runtime_StringNotEqual) {
1171 HandleScope handle_scope(isolate);
1172 DCHECK_EQ(2, args.length());
1173 CONVERT_ARG_HANDLE_CHECKED(String, x, 0);
1174 CONVERT_ARG_HANDLE_CHECKED(String, y, 1);
1175 return isolate->heap()->ToBoolean(!String::Equals(x, y));
1176}
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001177
1178RUNTIME_FUNCTION(Runtime_FlattenString) {
1179 HandleScope scope(isolate);
1180 DCHECK(args.length() == 1);
1181 CONVERT_ARG_HANDLE_CHECKED(String, str, 0);
1182 return *String::Flatten(str);
1183}
1184
1185
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001186RUNTIME_FUNCTION(Runtime_StringCharFromCode) {
1187 HandleScope handlescope(isolate);
1188 DCHECK_EQ(1, args.length());
1189 if (args[0]->IsNumber()) {
1190 CONVERT_NUMBER_CHECKED(uint32_t, code, Uint32, args[0]);
1191 code &= 0xffff;
1192 return *isolate->factory()->LookupSingleCharacterStringFromCode(code);
1193 }
1194 return isolate->heap()->empty_string();
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001195}
1196
Ben Murdochc5610432016-08-08 18:44:38 +01001197RUNTIME_FUNCTION(Runtime_ExternalStringGetChar) {
1198 SealHandleScope shs(isolate);
1199 DCHECK_EQ(2, args.length());
1200 CONVERT_ARG_CHECKED(ExternalString, string, 0);
1201 CONVERT_INT32_ARG_CHECKED(index, 1);
1202 return Smi::FromInt(string->Get(index));
1203}
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001204
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001205RUNTIME_FUNCTION(Runtime_StringCharCodeAt) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001206 SealHandleScope shs(isolate);
1207 DCHECK(args.length() == 2);
1208 if (!args[0]->IsString()) return isolate->heap()->undefined_value();
1209 if (!args[1]->IsNumber()) return isolate->heap()->undefined_value();
1210 if (std::isinf(args.number_at(1))) return isolate->heap()->nan_value();
1211 return __RT_impl_Runtime_StringCharCodeAtRT(args, isolate);
1212}
1213
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001214} // namespace internal
1215} // namespace v8